새소식

반응형
Language/Java

[Java] 자바 14 주요 변경점 살펴 보기

  • -
반응형

2023-11-08


사진: Unsplash 의 NEOM


1. swtich 패턴 개선

 

    @Test
    public void test1(){

        String today ="";
        int day = 1;
        switch (day) {
            case 1: today = "월";
            case 2: today = "화";
            case 3: today = "수";
            case 4: today = "목";
            case 5: today = "금";
            case 6: today = "토";
            case 7: today = "일";
        }
        System.out.println(today);

        // 변수에 매번 할당 하는 방식에서 case 에 따라 바로 변수에 할당할 수 있게 변경 되었다.

        String today2 ="";
        int day2 = 1;
        today2 = switch (day2) {
            case 1 -> "월";
            case 2 -> "화";
            case 3 -> "수";
            case 4 -> "목";
            case 5 -> "금";
            case 6 -> "토";
            case 7 -> "일";
            default -> throw new IllegalStateException("Unexpected value: " + day2);
        };
        System.out.println(today2);
    }

 

변수에 매번 할당하는 방식에서 case에 따라 바로 변수에 할당할 수 있게 변경되었다.


2. 문자열 멀티라인 변수 선언

 

    @Test
    public void test2(){
        String multiLine = """
                안녕하세요~ 
                이건은 여러줄로 
                문자열을 작성할 수 있어요!
                """;
        System.out.println(multiLine);
    }

 

실제 해당 문자열을 출력하면 줄 바꿈이 된 형태로 출력이 된다.


3.  instance of 패턴 개선

 

    @Test
    public void test3(){
        //인스턴스 체크 패턴 개선

        Object obj = "hi";

        if (obj instanceof String) {
            String str = (String) obj;
            int len = str.length();
            System.out.println(str);
        }


        if (obj instanceof String str) {
            int len = str.length();
            // ...
        }
    }

 

타입이 확인되면 해당 변수의 메서드를 바로 사용할 수 있게 변경되었다.


4. NullPointerException 명시적 변경

 

    @Test
    public void test4(){
        int[] arr = null;
        arr[0] = 1;

        //Exception in thread "main" java.lang.NullPointerException
        //at com.baeldung.MyClass.main(MyClass.java:...)

        //Cannot store to int array because "arr" is null
    }

 

NullPointerException에 대한 에러문구가 조금 더 명시적으로 변경되었다.


메인 이미지 출처 : 사진: UnsplashNEOM

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.