멍발자의 개발

기본 문법 복습 (4) 본문

STUDY/Java

기본 문법 복습 (4)

개발하는 멍발자 2022. 4. 14. 20:28

요즘 Switch문은 람다식을 관련해서 쓰는 경우가 많다.

인텔리제이를 이용하는 사람이라면 if문을 switch으로 바꾸기를 통하여 그 결과값을 확인할 수 있다.

 

<Switch문 예시>

 

public class SwitchSample {
    public static void main(String[] args) {
        var a = 5;

        switch (a) {
            case 1, 2 -> System.out.println("1, 2");
            case 3 -> System.out.println("3");
            case 4 -> System.out.println("4");
            case 5 -> System.out.println("5");
        }
    }
}

//결과
5

만약 선언된 변수가 없을 경우를 대비하여 dafault값은 넣어주도록 하자.

public class SwitchSample {
    public static void main(String[] args) {
        var a = 6;

        switch (a) {
            case 1, 2 -> System.out.println("1, 2");
            case 3 -> System.out.println("3");
            case 4 -> System.out.println("4");
            case 5 -> System.out.println("5");
            default -> System.out.println("기타");
        }
    }
}
//결과
기타

** 주의할 점은 default 값은 가장 나중에 써야 오류나지 않는다.

 

<Switch식 예시>

삼항 연산자대신 사용 가능하다. default문은 필수가 아니다.

오래된 형식에는 yield문을 쓸 때가 있다.

System.out.println(switch (a) {
 case 1, 2 -> "1, 2";
 case 3 -> "3";
 case 4 -> "4";
 default -> "기타";
}

<데이터 구조> **중요

값을 정리해서 취급하는 구조다.

List = 동일한 자료형의 값을 처리한다.

ex. List.of

 

<배열>

구조 = new 형[요소수]

ex. var scores = new int[3]

Comments