|
| 1 | +public class PatternMatchingDemo { |
| 2 | + |
| 3 | + public static void main(String[] args) { |
| 4 | + Object obj1 = "Hello Java 26"; |
| 5 | + Object obj2 = 100; |
| 6 | + Object obj3 = 3.14; |
| 7 | + |
| 8 | + checkType(obj1); |
| 9 | + checkType(obj2); |
| 10 | + checkType(obj3); |
| 11 | + |
| 12 | + System.out.println("\n--- Switch Pattern Matching ---"); |
| 13 | + printValue(obj1); |
| 14 | + printValue(obj2); |
| 15 | + printValue(obj3); |
| 16 | + } |
| 17 | + |
| 18 | + // instanceof pattern matching |
| 19 | + static void checkType(Object obj) { |
| 20 | + |
| 21 | + if (obj instanceof String s) { |
| 22 | + System.out.println("String value: " + s.toUpperCase()); |
| 23 | + } else if (obj instanceof Integer i) { |
| 24 | + System.out.println("Integer value: " + (i + 10)); |
| 25 | + } else { |
| 26 | + System.out.println("Other type: " + obj); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + // switch pattern matching |
| 31 | + static void printValue(Object obj) { |
| 32 | + |
| 33 | + switch (obj) { |
| 34 | + case String s -> System.out.println("String: " + s); |
| 35 | + case Integer i -> System.out.println("Integer: " + i); |
| 36 | + case Double d -> System.out.println("Double: " + d); |
| 37 | + default -> System.out.println("Unknown type"); |
| 38 | + } |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +/* |
| 43 | +What changed: Previous vs New |
| 44 | +
|
| 45 | +Previous Java style: |
| 46 | +- Manual type casting |
| 47 | +- instanceof + casting separately |
| 48 | +- More boilerplate code |
| 49 | +
|
| 50 | +Example: |
| 51 | +if (obj instanceof String) { |
| 52 | + String s = (String) obj; |
| 53 | +} |
| 54 | +
|
| 55 | +New Java 26 style: |
| 56 | +- Pattern matching in instanceof |
| 57 | +- Direct variable binding (String s) |
| 58 | +- Cleaner switch with type patterns |
| 59 | +
|
| 60 | +Why the new approach is better: |
| 61 | +- Less boilerplate |
| 62 | +- More readable |
| 63 | +- Safer (no casting errors) |
| 64 | +- Cleaner switch statements |
| 65 | +
|
| 66 | +Pros: |
| 67 | +1. Cleaner syntax |
| 68 | + - No explicit casting required |
| 69 | +
|
| 70 | +2. Safer code |
| 71 | + - Reduces ClassCastException |
| 72 | +
|
| 73 | +3. Better readability |
| 74 | + - Logic is more direct |
| 75 | +
|
| 76 | +4. Modern switch support |
| 77 | + - Works with multiple types easily |
| 78 | +
|
| 79 | +Cons: |
| 80 | +1. Preview feature (some parts) |
| 81 | + - Requires newer Java versions |
| 82 | +
|
| 83 | +2. Learning curve |
| 84 | + - Different from traditional style |
| 85 | +
|
| 86 | +Best use case: |
| 87 | +- Type checking logic |
| 88 | +- Processing mixed object types |
| 89 | +- Cleaner business logic |
| 90 | +
|
| 91 | +Compile and run: |
| 92 | +javac PatternMatchingDemo.java |
| 93 | +java PatternMatchingDemo |
| 94 | +*/ |
0 commit comments