Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

case labels in switch

case labels in switch: A case label selects a switch branch by constant, enum value, String, or type pattern; Java 21 can also handle null explicitly.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

case

A case label selects a switch branch by constant, enum value, String, or type pattern; Java 21 can also handle null explicitly.

Use case ... -> rules to avoid fall-through, guarded patterns with when to classify objects, and an exhaustive switch expression for a closed hierarchy.

A broader pattern cannot dominate a later narrower one, two labels cannot match the same constant, and default can hide an unhandled new variant.

Traditional colon case falls through without break, null needs an explicit case, and a switch expression must be exhaustive with every path producing a value.

Four case rules produce null, negative, integer:7, and text:4, showing null, a guarded pattern, Integer, and String cases.

Examples

public class Main {
  static String classify(Object value){return switch(value){case null->"null";case Integer i when i<0->"negative";case Integer i->"integer:"+i;case String s->"text:"+s.length();default->"other";};}
  public static void main(String[] args){System.out.println(classify(null));System.out.println(classify(-2));System.out.println(classify(7));System.out.println(classify("Java"));}
}

Result

null
negative
integer:7
text:4

Four case rules produce null, negative, integer:7, and text:4, showing null, a guarded pattern, Integer, and String cases.

Sources