Notice
Recent Posts
Recent Comments
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

충분히 쌓여가는

return 문 (void => return 문 생략 가능) 본문

Java/객체지향

return 문 (void => return 문 생략 가능)

빌드이너프 2023. 5. 25. 15:20

return 문

현재 실행 중인 메서드를 종료하고 호출한 메서드로 되돌아감

 

반환타입 void인 경우

return문 생략 가능

컴파일러가 메서드 마지막에 자동으로 return;을 추가해줌 -> return; 생략 가능

void printGugudan(int dan) {
    for (int i = 1; i < 9; i++) {
        System.out.printf("%d * %d = %d", dan, i, dan*i);
    }
    // return; // return문 생략 가능
}

 

입력받은 구구단 출력

public class MyMathTest {
    public static void main(String[] args) {
        MyMath mm = new MyMath();
        mm.printGugudan(3); // 참조변수 mm, 입력값 3
    }

}

class MyMath {
    void printGugudan(int dan) {
        for (int i = 1; i <= 9; i++) {
            System.out.printf("%d * %d = %d%n", dan, i, dan * i);
        }
        // return; // return문 생략 가능
    }
}

3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27

 

입력받은 값이 2~9가 아니면 return문을 통해 printGugudan()을 실행하지 않고 빠져나옴

public class MyMathTest {
    public static void main(String[] args) {
        MyMath mm = new MyMath();
        mm.printGugudan(12); // 입력값 12
    }

}

class MyMath {
    void printGugudan(int dan) {
        if (!(2<=dan && dan <=9)){
            return; // 입력받은 값이 2~9가 아니면, 메서드 종료 후 돌아가기
        }


        for (int i = 1; i <= 9; i++) {
            System.out.printf("%d * %d = %d%n", dan, i, dan * i);
        }
        // return; // return문 생략 가능
    }
}

출력값 없음

 

*조건문 주의

조건이 참과 거짓일 때 둘 다 return 문 작성 꼭 해주기

(만약 else 구문이 수행되어야 하는데 없으면 에러 발생)

 

에러 발생

public class MyMathTest {
    public static void main(String[] args) {
        MyMath mm = new MyMath();
    }

}

class MyMath {
    long max(long a, long b) {
        if(a > b)
            return a;
    } // 에러 발생
}

 

else 문 추가

public class MyMathTest {
    public static void main(String[] args) {
        MyMath mm = new MyMath();
        int result = mm.max(5, 3);

        System.out.println(result);
    }

}

class MyMath {
    int max(int a, int b) {
        if(a > b)
            return a;
        else
            return b;
    }
}

5