Explain Codes LogoExplain Codes Logo

How to use null in switch

java
null-handling
pattern-matching
switch-expressions
Anton ShumikhinbyAnton ShumikhinยทNov 20, 2024
โšกTLDR

In Java, switch statements don't accept null. However, you can use Java 14's enhanced switch. You can also perform a pre-check:

var response = (variable == null) ? "Null case" : switch (variable) { case "A" -> "Option A"; default -> "Other case"; }; // After reading this line, even my compiler understood the code ๐Ÿค“ System.out.println(response);

This short but swift piece of code neatly handles a null input. It leverages the streamlined switch expression introduced from Java 14 for succinct and clear execution.

Null handling with pattern matching

Java's recent enhancement JEP 420 introduces pattern matching and thus, enables the mighty null to be directly accommodated in switch expressions. This is a game-changer in increasing code readability and minimizing errors:

String str = /* placeholder string */; switch (str) { //Null has finally graduated to get its own place in switch case! case null -> System.out.println("The string has mastered the art of invisibility"); case "Foo", "Bar" -> System.out.println("Foo or Bar is here"); default -> System.out.println("Some other string snuck in"); }

This seamless integration of pattern matching rejects bloated code and any attempts of code error conspiracy.

Default case as a rescue for null

Rescue your code from the infamous NullPointerException by assigning a default value to possible null variables. Here's how you do it:

String command = /* command that might play Hide-n-Seek */; String safeCommand = (command != null) ? command : "UNKNOWN"; // 'UNKNOWN' isn't as ominous as it sounds. // It's just a friendly neighborhood substitute in the game of switch switch (safeCommand) { case "COMMAND_A" -> System.out.println("Executing Command A"); case "COMMAND_B" -> System.out.println("Executing Command B"); case "UNKNOWN" -> System.out.println("Unknown command. Retreat! Retreat!"); default -> System.out.println("Default case"); }

Cue Mission: Impossible theme song, deploy "UNKNOWN" type, and dominate the battleground of null handling.

Optional - The null knight

One-up your null evasion strategy by using Java's Optional class. This offers a shell to encapsulate the ominous absence of null values and deliver 'absent' value without the treacherous NullPointerException:

Optional<String> optionalValue = /* Optional string that may play Hide-n-Seek */; optionalValue.ifPresentOrElse( value -> { switch (value) { case "VALUE_A" -> System.out.println("Value A"); default -> System.out.println("Other value"); } }, // Here be your trident that handles 'null'. No, it's not stolen from Poseidon. () -> System.out.println("Value is enjoying some me time") );

This method offers higher readability, readability that is as soothing as a lullaby, and safety from NullPointerException.

Shielding against the null invasion

Managing null in switch statements is like managing mischievous toddlers - you need to understand the risks, plan ahead, and treasure the value of safety measures. Here are a few tips to make sure your code plays safe:

Pre-validate your variables

Before you juggle your variables into a switch expression, check if they are non-null:

// It's like checking the weather before going out. // Null-check - the umbrella of your program! if (someVar != null) { switch (someVar) { // cases } } else { // null handling }

Avoid ambiguity

Considering null and default cases to be long-lost twins? Ignoring NullPointerException just to let it sneak into the default case? Hold your impulses! Treat null separately, avoid ambiguity, and let clarity prevail.

Document your assumptions

Think your method or variable is as free from null as a leaf in autumn? Document it. Clear assumptions make happy coders!

Null handling in context-specific situations

The essence of code lies in its context. Here are some relevant scenarios where dealing null handling with switch frequently comes into picture:

State machines

In state machines, null could be the metaphorical kid trying to sneak out - an uninitialized state. Include null in your switch, present it transparently, and hold the reins of your state management logic.

Command patterns

Mapping strings to commands? Stumble upon a null string? Sounds like an invalid command alert. Elegantly accommodate these glitches within your switch and square dance through your control flow.

API response handling

Hang in there, API coders! Handling null in API responses that signify a failed reception can be intimidating. A well-carved null case in your switch can help you turf through such situations with grace.