: 메소드는 객체의 동작에 해당하는 중괄호 { } 블록을 말합니다. 중괄호 블록은 이름을 가지고 있는데, 이것이 메소드 이름입니다. 메소드를 호출하게 되면 중괄호 블록에 있는 모든 코드들이 일괄적으로 실행되며, 메소드는 객체 간의 데이터 전달의 수단으로 사용됩니다.


[메소드 선언]

리턴타입 메소드 이름 ([매개변수 선언, ...]) {

실행할 코드를 작성하는 곳                <- 메소드 실행블록

...

}


예시 )

int sumFunc( int num1, int num2) {

int result;

result = num1 + num2;

return result;

}


와 같이 작성할 수 있습니다.


[리턴 타입]

메소드가 실행 후 리턴하는 값의 타입을 말합니다. 각각의 메소드는 리턴값이 있을 수도 있고, 없을 수도 있습니다. 메소드가 실행 후 결과를 호출한 곳에 넘겨줄 경우에는 리턴값이 있어야 합니다.

아래 예시를 통해 참고하겠습니다.


public class Test1 {
public static void main(String[] args) {
int sum;
Scanner sc = new Scanner(System.in);

int num1 = sc.nextInt();
int num2 = sc.nextInt();
sum = sumFunc(num1, num2);

//sum = sumFunc(sc.nextInt(), sc.nextInt()); 로 위의 3줄을 대체될 수 있음
System.out.println("sum=" + sum);
sc.close();
}

public static int sumFunc(int num1, int num2) {
int result;
result = num1 + num2;
return result;
}
}

-> 사용자로부터 두 수를 입력받아 더한 값을 결과로 출력하는 단순한 코드입니다.


[리턴값이 없는 메소드]

void 로 선언된 리턴값이 없는 메소드에서도 return문을 사용할 수 있습니다. 다음과 같이 return문을 사용하면 메소드 실행을 강제 종료 시키게 됩니다.


다음은 gas값이 0보다 클 경우 계속해서 while문을 실행하고, 0일경우 return을 실행하여 run() 메소드를 즉시 종료합니다. 이 때, return문 대신 break문을 사용할 수도 있습니다.


[CarTest.java]

/**
* Created by 진우 on 2016-05-15.
*/
public class CarTest {
public static void main(String[] args) {
Car myCar = new Car();

myCar.setGas(5);

boolean gasState = myCar.isLeftGas();
if(gasState) {
System.out.println("출발합니다.");
myCar.run();
}

if(myCar.isLeftGas()) {
System.out.println("gas를 주입할 필요가 없습니다.");
} else {
System.out.println("gas를 주입하세요.");
}
}
}


[Car.java]

/**
* Created by 진우 on 2016-05-15.
*/
public class Car {
//필드
int gas;

//생성자


//메소드
void setGas(int gas) {
this.gas = gas;
}

boolean isLeftGas() {
if(gas == 0) {
System.out.println("gas가 없습니다.");
return false;
}
System.out.println("gas 가 있습니다.");
return true;
}

void run() {
while(true) {
if(gas > 0) {
System.out.println("달립니다. (gas 잔량:"+gas+")");
gas -= 1;
} else {
System.out.println("멈춥니다. (gas잔량:" + gas + ")");
return;
}
}
}
}


[결과 값] - CarTest의 main 실행화면


WRITTEN BY
SiriusJ

,