This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revision | |||
| language:java [2026/09/01 05:28] – ledyx | language:java [2026/09/01 06:04] (current) – Pattern Matching ledyx | ||
|---|---|---|---|
| Line 49: | Line 49: | ||
| **여러 줄에 걸친 문자열**을 만들기 위한 새로운 문법 | **여러 줄에 걸친 문자열**을 만들기 위한 새로운 문법 | ||
| - | 12에서 preview였다가 15에서 정식 | + | 12에서 preview였다가 15에서 정식 |
| <sxh java> | <sxh java> | ||
| Line 59: | Line 59: | ||
| BC | BC | ||
| DEF""" | DEF""" | ||
| + | </ | ||
| + | |||
| + | === Switch Expression 개선 === | ||
| + | |||
| + | 12에서 preview였다가 14에서 정식 기능으로 승격 | ||
| + | |||
| + | <sxh java> | ||
| + | private String calculateTestGrade1(int score) { | ||
| + | return switch (score) { | ||
| + | case 5: | ||
| + | yield " | ||
| + | case 4, 3: | ||
| + | yield " | ||
| + | case 2: | ||
| + | yield " | ||
| + | default: | ||
| + | yield " | ||
| + | }; | ||
| + | } | ||
| + | | ||
| + | private String calculateTestGrade2(int score) { | ||
| + | return switch (score) { | ||
| + | case 5 -> " | ||
| + | case 4, 3 -> " | ||
| + | case 2 -> { | ||
| + | System.out.println(" | ||
| + | yield " | ||
| + | } | ||
| + | default -> " | ||
| + | }; | ||
| + | } | ||
| + | </ | ||
| + | |||
| + | ==== ' | ||
| + | |||
| + | 14에서 preivew였다가 16에서 정식 기능으로 승격 | ||
| + | |||
| + | <sxh java> | ||
| + | public String say(Animal animal) throws IllegalAccessException { | ||
| + | if (animal instanceof Dog dog) { | ||
| + | return dog.bark(); | ||
| + | } else if (animal instanceof Cat cat) { | ||
| + | return cat.purr(); | ||
| + | } | ||
| + | |||
| + | throw new IllegalAccessException(); | ||
| + | } | ||
| + | | ||
| + | // 아래처럼 부정인 경우 Scope가 괄호 밖까지 확장 가능 | ||
| + | public String sayIfDog(Animal animal) throws IllegalAccessException { | ||
| + | if (!(animal instanceof Dog dog)) { | ||
| + | throw new IllegalAccessException(); | ||
| + | } | ||
| + | |||
| + | return dog.bark(); | ||
| + | } | ||
| + | |||
| + | |||
| + | public interface Animal { | ||
| + | } | ||
| + | |||
| + | public static class Dog implements Animal { | ||
| + | public String bark() { | ||
| + | return "Dog barking..."; | ||
| + | } | ||
| + | } | ||
| + | |||
| + | public static class Cat implements Animal { | ||
| + | public String purr() { | ||
| + | return "Cat purring..."; | ||
| + | } | ||
| + | } | ||
| </ | </ | ||