산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> java

자바 - 메소드

Java 메소드는 작업을 수행하기 위해 함께 그룹화되는 명령문의 모음입니다. System.out.println()을 호출할 때 예를 들어, 시스템은 콘솔에 메시지를 표시하기 위해 실제로 여러 명령문을 실행합니다.

이제 반환 값이 있거나 없는 고유한 메서드를 만들고 매개 변수가 있거나 없는 메서드를 호출하고 프로그램 디자인에서 메서드 추상화를 적용하는 방법을 배웁니다.

생성 방법

메소드의 구문을 설명하기 위해 다음 예를 고려하십시오 -

구문

public static int methodName(int a, int b) {
   // body
}

여기,

메서드 정의는 메서드 헤더와 메서드 본문으로 구성됩니다. 다음 구문에 동일하게 표시됩니다. -

구문

modifier returnType nameOfMethod (Parameter List) {
   // method body
}

위에 표시된 구문에는 -

가 포함됩니다.

다음은 min()이라는 위에서 정의한 메서드의 소스 코드입니다. . 이 메서드는 두 개의 매개변수 num1과 num2를 사용하고 두 매개변수 사이의 최대값을 반환합니다. -

/** the snippet returns the minimum between two numbers */

public static int minFunction(int n1, int n2) {
   int min;
   if (n1 > n2)
      min = n2;
   else
      min = n1;

   return min; 
}

메소드 호출

메서드를 사용하려면 호출해야 합니다. 메소드가 호출되는 두 가지 방법이 있습니다. 즉, 메소드가 값을 반환하거나 아무 것도 반환하지 않습니다(반환 값 없음).

메소드 호출 과정은 간단합니다. 프로그램이 메서드를 호출하면 프로그램 제어가 호출된 메서드로 전송됩니다. 이 호출된 메서드는 다음과 같은 두 가지 조건에서 호출자에게 제어를 반환합니다.

void를 반환하는 메서드는 문에 대한 호출로 간주됩니다. 예를 들어 보겠습니다 -

System.out.println("This is tutorialspoint.com!");

값을 반환하는 메서드는 다음 예에서 이해할 수 있습니다. -

int result = sum(6, 9);

다음은 메서드를 정의하는 방법과 메서드를 호출하는 방법을 보여주는 예입니다. -

라이브 데모
public class ExampleMinNumber {
   
   public static void main(String[] args) {
      int a = 11;
      int b = 6;
      int c = minFunction(a, b);
      System.out.println("Minimum Value = " + c);
   }

   /** returns the minimum of two numbers */
   public static int minFunction(int n1, int n2) {
      int min;
      if (n1 > n2)
         min = n2;
      else
         min = n1;

      return min; 
   }
}

이것은 다음과 같은 결과를 생성합니다 -

출력

Minimum value = 6

빈 키워드

void 키워드를 사용하면 값을 반환하지 않는 메서드를 만들 수 있습니다. 여기, 다음 예에서 우리는 void 메소드 methodRankPoints를 고려하고 있습니다. . 이 메서드는 값을 반환하지 않는 void 메서드입니다. void 메서드에 대한 호출은 methodRankPoints(255.7);와 같은 문이어야 합니다. . 다음 예와 같이 세미콜론으로 끝나는 Java 문입니다.

라이브 데모
public class ExampleVoid {

   public static void main(String[] args) {
      methodRankPoints(255.7);
   }

   public static void methodRankPoints(double points) {
      if (points >= 202.5) {
         System.out.println("Rank:A1");
      }else if (points >= 122.4) {
         System.out.println("Rank:A2");
      }else {
         System.out.println("Rank:A3");
      }
   }
}

이것은 다음과 같은 결과를 생성합니다 -

출력

Rank:A1

값으로 매개변수 전달

호출 프로세스에서 작업하는 동안 인수가 전달됩니다. 이는 메소드 사양의 해당 매개변수와 동일한 순서여야 합니다. 매개변수는 값 또는 참조로 전달할 수 있습니다.

값으로 매개변수를 전달한다는 것은 매개변수가 있는 메소드를 호출하는 것을 의미합니다. 이를 통해 인수 값이 매개변수로 전달됩니다.

다음 프로그램은 값으로 매개변수를 전달하는 예를 보여줍니다. 메서드를 호출한 후에도 인수 값은 동일하게 유지됩니다.

라이브 데모
public class swappingExample {

   public static void main(String[] args) {
      int a = 30;
      int b = 45;
      System.out.println("Before swapping, a = " + a + " and b = " + b);

      // Invoke the swap method
      swapFunction(a, b);
      System.out.println("\n**Now, Before and After swapping values will be same here**:");
      System.out.println("After swapping, a = " + a + " and b is " + b);
   }

   public static void swapFunction(int a, int b) {
      System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
      
      // Swap n1 with n2
      int c = a;
      a = b;
      b = c;
      System.out.println("After swapping(Inside), a = " + a + " b = " + b);
   }
}

이것은 다음과 같은 결과를 생성합니다 -

출력

Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30

**Now, Before and After swapping values will be same here**:
After swapping, a = 30 and b is 45

메서드 오버로딩

클래스에 이름은 같지만 매개변수가 다른 두 개 이상의 메서드가 있는 경우 이를 메서드 오버로딩이라고 합니다. 재정의하는 것과는 다릅니다. 재정의에서 메소드는 동일한 메소드 이름, 유형, 매개변수 수 등을 갖습니다.

정수 유형의 최소 수를 찾기 위해 앞에서 논의한 예를 살펴보겠습니다. 그렇다면 최소 double 유형의 수를 찾고 싶다고 가정해 보겠습니다. 그런 다음 오버로딩의 개념을 도입하여 이름은 같지만 매개변수가 다른 두 개 이상의 메소드를 생성합니다.

다음 예는 같은 것을 설명합니다 -

라이브 데모
public class ExampleOverloading {

   public static void main(String[] args) {
      int a = 11;
      int b = 6;
      double c = 7.3;
      double d = 9.4;
      int result1 = minFunction(a, b);
      
      // same function name with different parameters
      double result2 = minFunction(c, d);
      System.out.println("Minimum Value = " + result1);
      System.out.println("Minimum Value = " + result2);
   }

   // for integer
   public static int minFunction(int n1, int n2) {
      int min;
      if (n1 > n2)
         min = n2;
      else
         min = n1;

      return min; 
   }
   
   // for double
   public static double minFunction(double n1, double n2) {
     double min;
      if (n1 > n2)
         min = n2;
      else
         min = n1;

      return min; 
   }
}

이것은 다음과 같은 결과를 생성합니다 -

출력

Minimum Value = 6
Minimum Value = 7.3

메서드를 오버로딩하면 프로그램을 읽을 수 있습니다. 여기에서 두 가지 메소드가 이름은 같지만 매개변수가 다릅니다. 정수 및 이중 유형의 최소 숫자가 결과입니다.

명령줄 인수 사용

때로는 프로그램을 실행할 때 일부 정보를 프로그램에 전달하고 싶을 것입니다. 이는 main( )에 명령줄 인수를 전달하여 수행됩니다.

명령줄 인수는 실행될 때 명령줄에서 프로그램 이름 바로 뒤에 오는 정보입니다. Java 프로그램 내에서 명령줄 인수에 액세스하는 것은 매우 쉽습니다. main( )에 전달된 String 배열에 문자열로 저장됩니다.

다음 프로그램은 −

로 호출되는 모든 명령줄 인수를 표시합니다.
public class CommandLine {

   public static void main(String args[]) { 
      for(int i = 0; i<args.length; i++) {
         System.out.println("args[" + i + "]: " +  args[i]);
      }
   }
}

여기에 표시된 대로 이 프로그램을 실행해 보십시오. −

$java CommandLine this is a command line 200 -100

이것은 다음과 같은 결과를 생성합니다 -

출력

args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100

이 키워드

인스턴스 메소드 또는 생성자와 함께 현재 클래스의 객체에 대한 참조로 사용되는 Java의 키워드입니다. 이것 사용 생성자, 변수 및 메서드와 같은 클래스의 멤버를 참조할 수 있습니다.

참고 − 키워드 이것 인스턴스 메소드 또는 생성자 내에서만 사용됩니다.

일반적으로 키워드 이것 는 -

에 사용됩니다.
class Student {
   int age;   
   Student(int age) {
      this.age = age;	
   }
}
class Student {
   int age
   Student() {
      this(20);
   }
   
   Student(int age) {
      this.age = age;	
   }
}

다음은 this를 사용하는 예입니다. 클래스의 멤버에 액세스하는 키워드입니다. This_Example.java라는 이름의 파일에 다음 프로그램을 복사하여 붙여넣습니다. .

라이브 데모
public class This_Example {
   // Instance variable num
   int num = 10;
	
   This_Example() {
      System.out.println("This is an example program on keyword this");	
   }

   This_Example(int num) {
      // Invoking the default constructor
      this();
      
      // Assigning the local variable num to the instance variable num
      this.num = num;	   
   }
   
   public void greet() {
      System.out.println("Hi Welcome to Tutorialspoint");
   }
      
   public void print() {
      // Local variable num
      int num = 20;
      
      // Printing the local variable
      System.out.println("value of local variable num is : "+num);
      
      // Printing the instance variable
      System.out.println("value of instance variable num is : "+this.num);
      
      // Invoking the greet method of a class
      this.greet();     
   }
   
   public static void main(String[] args) {
      // Instantiating the class
      This_Example obj1 = new This_Example();
      
      // Invoking the print method
      obj1.print();
	  
      // Passing a new value to the num variable through parametrized constructor
      This_Example obj2 = new This_Example(30);
      
      // Invoking the print method again
      obj2.print(); 
   }
}

이것은 다음과 같은 결과를 생성합니다 -

출력

This is an example program on keyword this 
value of local variable num is : 20
value of instance variable num is : 10
Hi Welcome to Tutorialspoint
This is an example program on keyword this 
value of local variable num is : 20
value of instance variable num is : 30
Hi Welcome to Tutorialspoint

변수 인수(var-args)

JDK 1.5를 사용하면 동일한 유형의 다양한 인수를 메소드에 전달할 수 있습니다. 메소드의 매개변수는 다음과 같이 선언됩니다 -

typeName... parameterName

메소드 선언에서 유형 다음에 줄임표(...)를 지정합니다. 한 메서드에 하나의 가변 길이 매개변수만 지정할 수 있으며 이 매개변수는 마지막 매개변수여야 합니다. 모든 일반 매개변수가 그 앞에 와야 합니다.

라이브 데모
public class VarargsDemo {

   public static void main(String args[]) {
      // Call method with variable args  
	   printMax(34, 3, 3, 2, 56.5);
      printMax(new double[]{1, 2, 3});
   }

   public static void printMax( double... numbers) {
      if (numbers.length == 0) {
         System.out.println("No argument passed");
         return;
      }

      double result = numbers[0];

      for (int i = 1; i <  numbers.length; i++)
      if (numbers[i] >  result)
      result = numbers[i];
      System.out.println("The max value is " + result);
   }
}

이것은 다음과 같은 결과를 생성합니다 -

출력

The max value is 56.5
The max value is 3.0

finalize() 메소드

가비지 수집기에 의해 개체가 최종적으로 파괴되기 직전에 호출될 메서드를 정의할 수 있습니다. 이 메소드를 finalize( )라고 합니다. , 개체가 깔끔하게 종료되도록 하는 데 사용할 수 있습니다.

예를 들어 finalize()를 사용하여 해당 객체가 소유한 열린 파일이 닫혀 있는지 확인할 수 있습니다.

클래스에 종료자를 추가하려면 finalize() 메서드를 정의하기만 하면 됩니다. Java 런타임은 해당 클래스의 개체를 재활용하려고 할 때마다 해당 메서드를 호출합니다.

finalize() 메서드 내에서 객체가 소멸되기 전에 수행해야 하는 작업을 지정합니다.

finalize() 메서드는 다음과 같은 일반적인 형식을 갖습니다. -

protected void finalize( ) {
   // finalization code here
}

여기에서 protected 키워드는 클래스 외부에 정의된 코드에 의해 finalize()에 대한 액세스를 방지하는 지정자입니다.

이것은 finalize()가 언제 실행될지 또는 실행될지 알 수 없음을 의미합니다. 예를 들어 가비지 수집이 발생하기 전에 프로그램이 종료되면 finalize()가 실행되지 않습니다.


java

  1. 자바 연산자
  2. 자바 추상 ​​클래스와 추상 메소드
  3. 자바 주석 유형
  4. 예제가 있는 Java 문자열 charAt() 메서드
  5. 예제가 포함된 Java 문자열 endWith() 메서드
  6. Java 문자열 replace(), replaceAll() 및 replaceFirst() 메서드
  7. Java 문자열 toLowercase() 및 toUpperCase() 메서드
  8. 자바 - 재정의
  9. Java 9 - 컬렉션 팩토리 메소드
  10. Java 9 - 개인 인터페이스 메소드