개발/java

자바 버전별 특징

방푸린 2024. 9. 23. 17:47
반응형

자바8

  • 람다
  • 스트림 / parallelStream() 병렬처리 가능
  • 옵셔널
  • interface의 default 함수 / static method
  • java.time.local~~

자바9

  • interface의 private 함수
  • 불변 객체 생성(컬랙션 팩토리 메서트) List.of, Map.of, Set.of

자바10

  • 로컬 변수 타입 추론(Local-variable Type Inference): var 키워드 도입.

자바11

  • 옵셔널 클래스 개선: optional.isEmpty
  • 스트링 클래스에 함수 추가: String.isBlank, strip(공백제거)
  • HTTP Client API: 비동기 HTTP 요청 지원.
  • 람다에서의 지역 변수 사용(var).
  • 여러 새로운 GC 개선 사항.

자바12

  • switch 표현식 변화 preview

자바14

  • switch 표현식 정식 도입; 값 반환 가능
      1. switch 표현식 도입: 기존의 **switch 문(statement)**와 달리 값을 반환하는 **switch 표현식(expression)**을 사용할 수 있습니다.
      2. yield 키워드 도입: switch 표현식에서 값을 반환할 때 break 대신 yield 키워드를 사용하여 값을 반환할 수 있습니다.
      3. 화살표(->) 구문: case 절에 화살표 구문을 사용해 더 간결하게 작성할 수 있습니다.
      4. 중첩 case 절: 여러 케이스를 쉼표로 구분하여 하나의 case 절로 묶을 수 있습니다.
public class Main {
    public static void main(String[] args) {
        int score = 85;

        String grade = switch (score / 10) {
            case 10, 9 -> "A";
            case 8 -> "B";
            case 7 -> "C";
            case 6 -> {
                System.out.println("Just passed!");
                yield "D";
            }
            default -> "F";
        };

        System.out.println(grade); // 출력: B
    }
}
  • NullPointerException 날 때 누가 널인지 알려줌

자바16

  • record 프리뷰
  • sealed 클래스 : Sealed Classes가 정식 기능으로 도입되어, 클래스의 상속을 제어할 수 있습니다. 특정 클래스만 서브클래스로 허용할 수 있습니다.

자바17

  • instanceof 패턴 매칭
  • record 정식(from 16) 도입
  • sealed 클래스 정식 도입(from 15): 클래스 상속을 제한하는 방법. 안전성: 상속을 제한함으로써 불필요한 클래스 확장을 방지
//before
if (obj instanceof String) {
    String str = (String) obj; // 명시적으로 캐스팅
    System.out.println(str.length());
}
//after
if (obj instanceof String s) { // s에 자동으로 캐스팅
    System.out.println(s.length());
}

sealed 클래스의 주요 특징

  1. 상속 제한: sealed 클래스를 정의하면, 그 클래스를 상속할 수 있는 하위 클래스를 명시적으로 지정해야 합니다. 이를 통해 상속 계층을 엄격하게 관리할 수 있습니다.
  2. 하위 클래스 유형:
    • permits: sealed 클래스가 어떤 하위 클래스를 상속할 수 있는지 지정합니다.
    • non-sealed: 상속 제한을 받지 않는 클래스로, 다른 클래스가 이 클래스를 자유롭게 상속할 수 있습니다.
    • final: 상속을 허용하지 않는 클래스입니다. 더 이상 상속할 수 없습니다.
public sealed class Shape permits Circle, Square, Rectangle {
    // Shape 클래스의 내용
}

public final class Circle extends Shape {
    public final int radius;
    public Circle(int radius) {
        this.radius = radius;
    }
}

public final class Square extends Shape {
    public final int side;
    public Square(int side) {
        this.side = side;
    }
}

public non-sealed class Rectangle extends Shape {
    public final int length;
    public final int width;
    public Rectangle(int length, int width) {
        this.length = length;
        this.width = width;
    }
}

public class ShapeProcessor {
    public static void processShape(Shape shape) {
        switch (shape) {
            case Circle c -> System.out.println("Circle with radius: " + c.radius);
            case Square s -> System.out.println("Square with side: " + s.side);
            case Rectangle r -> System.out.println("Rectangle with length: " + r.length + " and width: " + r.width);
        }
    }
}

 

자바21

  • virtual thread
    • Virtual Threads는 경량 스레드로, 기존의 OS 스레드에 비해 훨씬 가볍고 많은 수를 생성할 수 있습니다. 이를 통해 동시성 프로그래밍을 더 간단하고 효율적으로 구현할 수 있습니다.
      • 높은 동시성을 필요로 하는 애플리케이션(예: 서버)에서 기존의 스레드 풀 관리 복잡성을 줄이고 성능을 개선합니다.
      • 스레드가 블로킹 작업을 수행하더라도 리소스 소비를 줄일 수 있습니다.
  • Sequenced Collections (새 인터페이스)
    • 설명: SequencedCollection, SequencedSet, SequencedMap이라는 새로운 인터페이스가 추가되었습니다. 이 인터페이스들은 요소의 순서와 관련된 작업을 쉽게 할 수 있도록 도와줍니다.
    • first(), last()와 같은 메서드를 통해 첫 번째 및 마지막 요소에 쉽게 접근할 수 있습니다.
    • Reversed 메서드를 통해 컬렉션을 뒤집을 수 있습니다.
  • Pattern Matching for switch (정식 기능)
    • 설명: switch 문에서 패턴 매칭을 사용할 수 있게 되었습니다. 이는 더 간결하고 읽기 쉬운 코드 작성에 도움이 됩니다. 다양한 타입의 데이터를 안전하게 분기할 수 있습니다.
    • instanceof와 switch 문이 결합되어, 타입 검사와 변환을 쉽게 수행할 수 있습니다.
    • null 값 처리도 포함되어 있어 null 안정성을 높일 수 있습니다.
Object obj = 123;
switch (obj) {
    case Integer i -> System.out.println("Integer: " + i);
    case String s  -> System.out.println("String: " + s);
    case null     -> System.out.println("It's null!");
    default       -> System.out.println("Unknown type");
}
  • Record Patterns (정식 기능)
    • 설명: Record와 Pattern Matching을 결합하여 Record 타입의 데이터를 분해할 수 있습니다. 이를 통해 복잡한 Record 타입의 데이터를 쉽게 다룰 수 있습니다.
    • Record 타입의 인스턴스를 Pattern Matching으로 구성 요소를 추출할 수 있습니다.
    • switch, if-else와 같은 조건문에서 사용할 수 있습니다.
record Point(int x, int y) {}

Point point = new Point(3, 4);

if (point instanceof Point(int x, int y)) {
    System.out.println("x: " + x + ", y: " + y);
}
728x90
반응형