亲嘴有什么好处| 88年五行属什么| 什么是姑息治疗| 骨密度低吃什么药最快| q是什么意思| 内心独白什么意思| 臀纹不对称有什么影响| 什么的温度| 高抬腿运动有什么好处| 常喝柠檬水有什么好处和坏处| 感冒吃什么好得快| 匿名是什么意思| 羞涩是什么意思| 琋字五行属什么| 布病是什么症状| 什么是太岁| 环移位了会出现什么症状| 长结节是什么原因造成的| 琼花是什么意思| 不二法门是什么意思| 硫酸铜什么颜色| 病毒性扁桃体发炎吃什么药| 孕妇适合吃什么鱼| 子痫前期是什么意思| 超市理货员是做什么的| 为什么熊猫是国宝| 肠胃蠕动慢吃什么药| 三多一少指的是什么| 为什么会流鼻血什么原因引起的| 桥本甲状腺炎吃什么药| 身上肉疼是什么原因| 疣是什么病毒| 跛行是什么意思| fic是什么意思| 什么是眼底病| 纯粹是什么意思| food什么意思| 双侧肾盂分离是什么意思| 发财树为什么叫发财树| 刘备字什么| 兰精莫代尔是什么面料| 牙齿挂什么科| hcg稀释是什么意思| 女人腰疼是什么原因引起的| 木变石是什么| 照见五蕴皆空什么意思| 什么是五常大米| 67年属什么生肖| 结石吃什么食物好| 空调一匹是什么意思| 浑身没劲吃什么药| 什么球不能踢| 狮子座后面是什么星座| 什么方法避孕最安全有效| 不想要孩子用什么办法最好| 为什么一直流鼻涕| 眼底检查主要查什么| 一个王一个番读什么| 为什么叫买东西不叫买南北| 蛋白尿是什么| 粘液丝高是什么原因| 红五行属性是什么| 很轴是什么意思| 目前除皱最好的方法是什么| 意境是什么意思| 银杯子喝水有什么好处| 诸是什么意思| 什么叫静息心率| ldpe是什么材料| 小李子为什么叫小李子| 检查痛风挂什么科| 肋骨属于什么骨| 2018年属什么| 小脑梗塞会出现什么症状| 早上九点半是什么时辰| 尿多是什么问题| 血压低吃什么| 卡其色裙子配什么颜色上衣好看| 什么可以去湿气| 尿检蛋白质弱阳性是什么意思| 孕期吃什么补铁| 糗事是什么意思| 麻婆豆腐是什么菜系| 巨蟹是什么象星座| 双重所有格是什么意思| 我看见了什么| 哪吒属什么生肖| 可乐饼为什么叫可乐饼| 牛鞭是什么部位| 失眠多梦吃什么药| 水瓶座是什么象星座| 姓陆的女孩取什么名字好| 血红蛋白低吃什么| 4月14日是什么星座| 什么直跳| 宝宝发烧拉肚子是什么原因| 总胆固醇低是什么原因| 塞保妇康为什么会出血| 脉滑是什么意思| 经常想吐恶心是什么原因| 为什么呀| 身体年龄是什么意思| kenzo是什么牌子| 脸上长痘痘去医院挂什么科| 窦性心律早期复极是什么意思| 吃什么能润肠通便| 野鸡大学是什么意思| 碳酸氢根偏低什么意思| 去痛片又叫什么名| 朔望月是什么意思| 水果的英文是什么| 鹿角粉有什么功效和作用| 老师家访需要准备什么| 雅诗兰黛是什么档次| 膝盖背面叫什么| 南瓜不能和什么食物一起吃| 5月20日什么星座| 精神病吃什么药| 属马的人佩戴什么招财| 梦见买衣服是什么预兆| fomo是什么意思| 口吐白沫是什么病| 滴虫性阴道炎吃什么药| 十月一日是什么节| 芒硝是什么| 肿瘤指标偏高什么意思| 男人是什么动物| 井底之蛙的寓意是什么| 虚岁24岁属什么生肖| 缺钾吃什么食物| 新斯的明是什么药| 11月9日什么星座| iod什么意思| 感冒吃什么水果好| 手足口是什么引起的| 黄体酮吃多了有什么副作用| 诗韵是什么意思| 舌头中间疼是什么原因| 甲状腺结节挂什么科室| 洁身自好什么意思| 头热手脚冰凉什么原因| 抽完血吃什么| 灰水是什么| 楠字五行属什么| 梦见抽血是什么预兆| 甲状腺结节有什么感觉| 哮喘病有什么症状| 你什么都可以| 玉米热量高为什么还减肥| 院感是什么意思| 睛可以组什么词| 舌苔厚黄吃什么药最好| 手脚冰凉吃什么好| 鬼一般找什么人压床| 睾丸痒是什么原因| 肩周炎是什么原因造成的| 维生素d补什么| 中午12点是什么时辰| 带状疱疹不能吃什么食物| 承五行属什么| 一什么而入| 心脏疼痛吃什么药| 风寒感冒用什么药| 下嘴唇溃疡是什么原因| 别有洞天是什么生肖| 退工单是什么| 干咳吃什么药| 私奔是什么意思| 朱顶红什么时候开花| 尿酸高喝什么水最好| 着床出血是什么样的| 呕吐是什么原因引起的| 肠胃炎吃什么消炎药| 日加立念什么| 清明是什么季节| 女人白带多是什么原因| 发烧吃什么退烧药| 拉屎是绿色的是什么原因| 粉盒和硒鼓有什么区别| 股骨头坏死挂什么科| 男人吃逍遥丸治什么病| 喜闻乐见什么意思| 尿道口红肿用什么药| roma是什么牌子| 内分泌失调吃什么食物好| 鼻子上长脓包型痘痘是什么原因| 8月12日是什么星座| 座驾是什么意思| 突然停经是什么原因| 围度什么意思| 打鼾是什么意思| 乌鸡白凤丸男性吃治疗什么| 月经期喝红糖水有什么好处| 西楚霸王是什么生肖| 狗是什么生肖| 什么样的房子不能住人脑筋急转弯| 东窗事发是什么意思| 慢工出细活什么意思| imao什么意思| 龟头有点痒擦什么药| mbti测试是什么| 荸荠是什么| 木加鬼念什么| 眼睛淤青用什么方法能快点消除| 形而下是什么意思| 狗狗咳嗽吃什么药好得快| 小鸭子吃什么食物| 天空像什么的比喻句| 火奥念什么| 什么是畸胎瘤| 钱丢了预示着什么| 食铁兽是什么动物| 羊水少了对宝宝有什么影响| 什么是脑死亡| doro什么意思| 心电图异常q波什么意思| 1968年属什么生肖| 两情相悦什么意思| 陆地上最大的动物是什么| 9像什么| 什么龙什么凤| 线下培训是什么意思| 溥仪为什么没有生育能力| 吃鱼油有什么好处| 回奶什么意思| 奡是什么意思| 来姨妈为什么是黑色的血| 面筋是什么| 不典型增生是什么意思| 梦到挖坟墓是什么意思| dunk是什么牌子| 不10是什么意思| bbs是什么意思| 原发性和继发性是什么意思| 木耳吃多了有什么坏处| 三手烟是什么意思| 早上7点到9点是什么时辰| 米酒和黄酒有什么区别| 药物流产后吃什么好| 亲情是什么意思| RH是什么| 什么是基础医学| 亲亲抱抱举高高什么意思| 甲状腺有什么症状| 凌字五行属什么| 耳根子软是什么意思| 将军代表什么生肖| 杰五行属什么| 大便发绿色是什么原因| 可乐煮姜有什么作用| 绀是什么意思| 花生为什么叫落花生| ppap是什么| 木加一笔变成什么字| 脂肪肝吃什么药| 黄精有什么功效| 心口疼是什么原因| pd999是什么金| 红细胞减少是什么原因| 满目苍夷是什么意思| 手脚发麻是什么原因| 营养不良会导致身体出现什么症状| 恩客是什么意思| 动脉ct主要检查什么| 百度
Rafael del Nero
Contributing Writer

Learn how to use pattern-matching features in your Java programs, including pattern matching with switch statements, when clauses, sealed classes, and a preview of primitive type pattern matching in Java 23.

百度 但与此同时,由指尖文化消费带来的纠纷也日益增多,许多消费者权益受损却又无可奈何。

Abstract cardboard design with geometric shapes in orange, light orange, and white.
Credit: Anastasiia Guseva / Shutterstock

Pattern matching is a way to simplify your code by checking if a value fits a certain structure or type, without having to write messy, repetitive checks. Instead of using multiple if statements and manual type casting, you can simply let Java do the heavy lifting.

Developers use pattern matching to reduce unnecessary work in their code. For example, you can use pattern matching to find out if a Java Object is a String. Here are some advantages of pattern matching:

  • Less boilerplate code: No more writing extra instanceof checks followed by casting. Pattern matching results in code that is shorter and cleaner.
  • More readable code: The code’s logic is easier to follow because the pattern performs type checking and variable binding in one step.
  • Fewer bugs: Since Java handles the type casting automatically, you avoid mistakes like ClassCastExceptions.

In short, pattern matching makes your Java code simpler, safer, and easier to read. If you’re using Java 16 or later, you should start using it today.

Pattern matching basics

Pattern matching simplifies your Java code by allowing you to check an object’s type and use it in one clean step. No more messy type checking and casting; Java does it for you automatically. Remember how bad class casting looks in your code? Pattern matching solves this problem gracefully.

Instead of writing:


if (object instanceof String) {
    String s = (String) object;
    System.out.println(s.length());
}

You can just write:


if (object instanceof String s) {
    System.out.println(s.length());
}

The difference is clear:

  • No redundant casting: The variable s is ready to use as a String.
  • Cleaner logic: Combines type-checking and assignment in one line.
  • Fewer bugs: Removes the risk of a ClassCastException from manual casting. The cast is created, and then you declare the variable with the desired type in the same line of code.

Pattern matching for switch (Java 21+)

In older Java versions, switch statements could only compare simple values, such as numbers or enums. But with pattern matching, switch can check an object’s type directly, making your code cleaner and more powerful. Let’s take a look.

Type checking without pattern matching requires verbose code:


if (obj instanceof String) {
    String s = (String) obj;
    System.out.println("It's a String: " + s);
} else if (obj instanceof Integer) {
    Integer i = (Integer) obj;
    System.out.println("It's an Integer: " + i);
} else {
    System.out.println("Unknown type");
}

With switch and pattern matching, you can match types and extract variables in one step:


switch (obj) {  
    case String s  -> System.out.println("It's a String: " + s);  
    case Integer i -> System.out.println("It's an Integer: " + i);  
    default            -> System.out.println("Unknown type");  
}

This is a significant improvement over the old way, where switch could only match constants:


switch (number) {
    case 1 -> System.out.println("One");  // Old: only constants
    case 2 -> System.out.println("Two");
}

Some key takeaways from this example:

  • Pattern matching works with any object type: This means no more long, if-else chains for type checks.
  • It supports auto-casting: Variables (s, i) are ready to use with the correct type.
  • The logic is clearer: With pattern matching, the structure of the code is flat and easy to read.

Advanced features of pattern matching

Java 16 introduced basic pattern matching with instanceof, but more advanced capabilities arrived in Java 21. This section shows you how to use record patterns, nested record patterns, and guarded patterns in Java programs.

Record patterns

Record patterns allow you to directly access the components of a record in one concise operation. This feature introduces powerful deconstruction capabilities to Java, similar to those found in functional programming languages.

Record patterns also let you deconstruct records (Java’s immutable data classes) directly within pattern-matching contexts like instanceof checks and switch statements. Instead of retrieving each field separately, you can extract all the components in one step.

Here’s an example of using a record pattern with instanceof:


record Point(int x, int y) {}

// Without record patterns
if (p instanceof Point) {
    Point point = (Point) p;
    int x = point.x();
    int y = point.y();
    System.out.println(x + ", " + y);
}

// With record patterns
if (p instanceof Point(int x, int y)) {
    System.out.println(x + ", " + y);  // x and y are directly available
}

Record patterns shine even more when used in switch statements:


Object obj = new Point(10, 20);

switch (obj) {
    case Point(int x, int y) when x > 0 && y > 0 -> 
        System.out.println("Point in first quadrant: " + x + ", " + y);
    case Point(int x, int y) -> 
        System.out.println("Point elsewhere: " + x + ", " + y);
    default -> 
        System.out.println("Not a point");
}

Nested record patterns

Nested record patterns let you look inside records that contain other records, all in one step. This makes working with complex data much simpler.

You can use nested patterns to match and extract values from multiple levels of data structures at once. Instead of navigating through each level separately, you can directly access the inner components:


// Define two simple records
record Address(String city, String country) {}
record Person(String name, Address address) {}

// Create a person with an address
Person person = new Person("Rafael", new Address("Sao Paulo", "Brazil"));

For contrast, here’s an example of matching and extracting values without nested patterns:


// Multiple steps required
if (person instanceof Person) {
    String name = person.name();
    Address address = person.address();
    String city = address.city();
    String country = address.country();
    
    System.out.println(name + " lives in " + city + ", " + country);
}

And here’s the same code with nested patterns:


// One clean pattern
if (person instanceof Person(String name, Address(String city, String country))) {
    // All variables are immediately available
    System.out.println(name + " lives in " + city + ", " + country);
}

Like regular record patterns, nested record patterns can be used in switch statements. In the first case clause of the following code, we have the String “Ireland”, which stipulates that the condition will be met only if the person’s country is Ireland; if not, the other condition will be met:


switch (person) {
    case Person(String name, Address(String city, "Ireland")) ->
        System.out.println(name + " lives in " + city + ", Ireland");
    case Person(String name, Address(String city, String country)) ->
        System.out.println(name + " lives in " + city + ", " + country);
}

Once again, the benefits are clear:

  • Less boilerplate: Nested record patterns let you extract all the components in a single operation.
  • Improved readability: The pattern clearly shows what you are extracting.
  • Type safety: The compiler ensures correct types for extracted variables.
  • Nested deconstruction: The pattern seamlessly handles complex data structures.

Nested patterns make your code more readable and maintainable, especially when working with complex data structures like configuration objects, domain models, or API responses.

Guarded patterns (when clauses)

Guarded patterns enhance pattern matching by letting you add specific conditions using the when keyword. This feature allows you to match not just by type or structure, but also by the values contained within the matched object.

As shown here, a guarded pattern combines a regular pattern with a Boolean condition:


switch (obj) {
    case String s when s.length() > 5 -> 
        System.out.println("Long string: " + s);
    case String s -> 
        System.out.println("Short string: " + s);
    default -> 
        System.out.println("Not a string");
}

Here’s how this code works:

  1. Java checks if the object matches the pattern (e.g., is it a String?).
  2. If it matches, Java binds the variable (s).
  3. Java evaluates the condition after when.
  4. If the condition is true, the case is selected.

Let’s look at a couple of practical examples.

In this first example, we use a guarded pattern for testing String content:


switch (input) {
    case String s when s.startsWith("http://") -> 
        System.out.println("HTTP URL");
    case String s when s.startsWith("http://") -> 
        System.out.println("Secure HTTPS URL");
    case String s ->     
        System.out.println("Not a URL");
}

And here, we’re using the pattern with numbers:


switch (num) {
    case Integer i when i < 0 -> System.out.println("Negative");
    case Integer i when i == 0 -> System.out.println("Zero");
    case Integer i when i > 0 -> System.out.println("Positive");
    default -> System.out.println("Not an integer");
}

The benefits of guarded patterns are:

  • More precise matching: Target specific value conditions.
  • Reduced code: Combine type checking and value testing in one step.
  • Better readability: Clear, concise expression of complex conditions.

Pattern matching with sealed classes

Combining sealed classes with pattern matching is a powerful way to bring compile-time safety to your code. Examples in this section will show you why this combination is a game-changer.

What are sealed classes?

Introduced in Java 17, sealed classes are classes that explicitly define which other classes can extend or implement them. Think of a sealed class as creating a “closed club” of related types:


sealed interface JavaMascot permits Duke, Juggy { }
record Duke(String color, int yearIntroduced) implements JavaMascot { }
record Juggy(String color, boolean isFlying) implements JavaMascot { }

At first glance, this code doesn’t seem to help much, but the real benefit starts when we try something like the following:


record Moby(String color, double tentacleLength) implements JavaMascot { } // Compilation error here

Because the sealed interface JavaMascot only permits Duke and Juggy to implement it, the code above won’t compile! By restricting the code in that way, we avoid using a class we shouldn’t to implement the JavaMascot interface. This decreases the chances of bugs in our code. Remember, the more you restrict the code, the less likely you are to create bugs!

Using sealed classes with switch

When you combine sealed classes with switch in pattern matching, the compiler gains complete knowledge of all possible types. There are two major benefits to the compiler having such knowledge: (1) The compiler verifies you’ve handled all possible subtypes; (2) since all possibilities are known, you don’t need a default case.

Do you see how sealed classes and switch work together in the following code?


String describeMascot(JavaMascot mascot) {
    return switch (mascot) {
        case Duke(String color, int yearIntroduced) -> 
            "Duke (" + color + ") from " + yearIntroduced;
        case Juggy(String color, boolean isFlying) -> 
            "Juggy (" + color + ")" + (isFlying ? " flying high" : "");
        // No default needed! The compiler knows these are all possibilities
    };
}

Primitive type pattern matching in Java 23+

Java’s newer versions introduced a powerful preview feature that lets us check compatibility between primitive types using pattern matching. We can explore this feature with a few examples. Just remember that, since primitive type pattern matching is still a preview feature, it could be changed or removed in a future release. To execute the following examples, you need to turn on enable preview:


java --enable-preview YourClassNameHere

What is primitive type pattern matching?

This feature enables us to determine if a value of one primitive type can be accurately represented in another primitive type, binding the value to a new variable if the test is successful. We can see this feature at work in the following integer compatibility example:


int count = 98;
if (count instanceof byte smallCount) {
    // This executes only if count fits in a byte's range
    System.out.println("Small enough: " + smallCount);
} else {
    System.out.println("Number too large for byte storage");
}

Here, we’re checking if 98 can be stored in a byte. Since it’s between -128 and 127, the condition succeeds.

Consider another example, this one evaluating decimal precision:


double measurement = 17.5;
if (measurement instanceof float simpleMeasurement) {
    System.out.println("No precision loss: " + simpleMeasurement);
} else {
    System.out.println("Requires double precision");
}

This verifies if the double value can be represented as a float without precision loss.

Here’s an example using primitive type pattern matching with text characters:


int codePoint = 90;
if (codePoint instanceof char symbol) {
    System.out.println("This represents: '" + symbol + "'");
} else {
    System.out.println("Not a valid character code");
}

The output from this code would be: This represents: ‘Z’, because 90 is the ASCII/Unicode value for Z.

Finally, here’s a demonstration showing multiple type compatibility checks:


void examineNumber(long input) {
    System.out.println("Examining: " + input);
    
    if (input instanceof byte b)
        System.out.println("Fits in a byte variable: " + b);    
    if (input instanceof short s)
        System.out.println("Fits in a short variable: " + s);
    if (input >= 0 && input <= 65535 && input instanceof char c)
        System.out.println("Represents character: '" + c + "'");
    if (input instanceof int i)
        System.out.println("Fits in an int variable: " + i);
}

When called with examineNumber(77), this code would output all four messages, including that 77 represents the character ‘M’.

When to use primitive type pattern matching

Primitive type pattern matching is particularly valuable for the following uses:

  • Validating user input against acceptable ranges.
  • Converting between numeric formats while avoiding data loss.
  • Working with character encoding in text processing.
  • Making numeric type conversions more readable and safe.

Conclusion

Pattern matching represents a significant evolution in Java’s syntax, bringing more expressive and concise ways to work with data. By combining type checking, casting, and data extraction into unified operations, it reduces boilerplate and makes code more readable and maintainable.

Java developers can now write cleaner code when working with polymorphic data, nested structures, and conditional processing. Basic pattern matching features (like enhanced instanceof) are available from Java 16 onward, while more advanced capabilities (like record patterns and guarded patterns) came up in Java 21.

As this feature continues to mature in future releases, it will further strengthen Java’s position as a language that balances performance, safety, and expressiveness. If you haven’t played with pattern matching yet, create some code and run a few tests to absorb the knowledge. The best way to acquire a skill is to put it into practice.

眉心长痘是什么原因 宝宝睡觉流口水是什么原因 梦见黑蛇是什么意思 体制内是什么意思 月经刚完同房为什么痛
天蝎后面是什么星座 药流用什么药 时柱将星是什么意思 522是什么意思 为什么屁多是什么原因
吕字五行属什么 七个月宝宝可以吃什么辅食 心肌炎查什么能查出来 渣男之首是什么星座 咽喉老有痰是什么原因
膝盖咔咔响吃什么药 2008年什么年 手指尖疼是什么原因 左手发麻是什么病征兆 女真人是什么民族
母亲节送妈妈什么礼物好hcv9jop6ns9r.cn 呕吐是什么原因bjhyzcsm.com lf是什么牌子naasee.com 胸前长痘痘是什么原因hcv7jop5ns6r.cn 橄榄菜长什么样子图片hcv8jop7ns6r.cn
人工降雨的原理是什么hcv7jop9ns1r.cn 喝什么降火hcv9jop5ns9r.cn diff是什么意思1949doufunao.com 早上起床眼睛浮肿是什么原因hcv8jop0ns2r.cn 例假量多是什么原因hcv8jop4ns2r.cn
绯色是什么颜色hcv9jop2ns1r.cn 三点水的字大多与什么有关hcv8jop2ns0r.cn 女性膀胱炎是什么症状hcv8jop4ns1r.cn 三高指什么hcv8jop1ns1r.cn belle什么意思hcv8jop9ns4r.cn
槐花什么时候开花hcv8jop6ns2r.cn 农历六月十四是什么日子hcv9jop2ns2r.cn 郑中基为什么叫太子基chuanglingweilai.com 精湛是什么意思zsyouku.com 心脏传导阻滞吃什么药hcv8jop1ns5r.cn
Rafael del Nero
Contributing Writer

Rafael del Nero is a Java Champion and Oracle Ace, creator of the Java Challengers initiative, and a quiz master in the Oracle Dev Gym. Rafael is the author of "Java Challengers" and "Golden Lessons." He believes there are many techniques involved in creating high-quality software that developers are often unaware of. His purpose is to help Java developers use better programming practices to code quality software for stress-free projects with fewer bugs.

More from this author

百度