Pattern matching for Switch java 17

Before Java 17, switch worked only with primitive types such as int, char etc, String, and enums. If we required to handle different object types, we had to use if-else with instanceof and explicit type casting. Let’s understand from the below example

package com.sks;

public class BeforeJava17SwitchExample {
	
	public static void main(String[] args) {
		processInput(14);
		processInput("Hi, dear");
		processInput(Boolean.valueOf(false));
	}

	public static void processInput(Object objType) {
		
		if (objType instanceof Integer) {
			Integer val = (Integer) objType; //Explicit casting
			System.out.println("Integer: " + (val * 2));
		} else if (objType instanceof String) {
			String val = (String) objType;
			System.out.println("String: " + val.toUpperCase());
		} else if (objType instanceof Boolean) {
			Boolean val = (Boolean) objType;
			System.out.println("Boolean: " + (val));
		} else {
			System.out.println("Unknown type!");
		}
	}
}

Same example with java 17 is as below. But since it is only a preview feature your eclipse will need to enable preview features option. Otherwise run the below program with java21.

package com.sks;

public class Java17Switch {

	public static void main(String[] args) {
		processInput(14);
		processInput("Hi, dear");
		processInput(Boolean.valueOf(false));
	}

	public static void processInput(Object objType) {
			switch (objType) {
			 case Integer val -> System.out.println("Integer: " + (val * 2));
			 case String val -> System.out.println("String: " + val.toUpperCase());
			 case Boolean val -> System.out.println("Boolean: " + (val));
			 default -> System.out.println("Unknown type!");
			}
		}
}

Output: