Pattern Matching
Part of the Logic & Flow section of Coddy's Java journey — lesson 37 of 59.
Pattern matching in Java allows you to test if an object has a specific type and extract components from it. It simplifies type checking and casting operations.
Let's see how to use pattern matching with instanceof:
Object obj = "Hello";
if (obj instanceof String str) {
// str is automatically cast to String
System.out.println(str.toUpperCase());
}After executing the above code, the output is:
"HELLO"
You can also use pattern matching in switch expressions:
Object value = 42;
String result;
if (value instanceof Integer i) {
result = "Number: " + i;
} else if (value instanceof String s) {
result = "Text: " + s;
} else {
result = "Unknown";
}After executing the above code, result contains:
“Number: 42”
Challenge
EasyCreate a method named processValue that takes one argument:
- An Object (
value) that could be of different types
The method should use pattern matching with instanceof to process the value and return a string based on these rules:
- If it's an Integer: return "Number: " followed by the value doubled
- If it's a String: return "Text: " followed by the value in uppercase
- If it's a Boolean: return "Boolean: " followed by the opposite value (true becomes false and vice versa)
- For any other type: return "Unknown"
Cheat sheet
Pattern matching in Java allows you to test if an object has a specific type and extract components from it using instanceof:
Object obj = "Hello";
if (obj instanceof String str) {
// str is automatically cast to String
System.out.println(str.toUpperCase());
}You can chain multiple pattern matching checks:
Object value = 42;
String result;
if (value instanceof Integer i) {
result = "Number: " + i;
} else if (value instanceof String s) {
result = "Text: " + s;
} else {
result = "Unknown";
}Try it yourself
import java.util.Scanner;
public class Main {
public static String processValue(Object value) {
// TODO: Use pattern matching with instanceof to process the value
// If it's an Integer: return "Number: " + (value * 2)
// If it's a String: return "Text: " + value.toUpperCase()
// If it's a Boolean: return "Boolean: " + (!value)
// For any other type: return "Unknown"
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String type = scanner.nextLine();
String inputValue = scanner.nextLine();
Object value = switch(type) {
case "Integer" -> Integer.parseInt(inputValue);
case "String" -> inputValue;
case "Boolean" -> Boolean.parseBoolean(inputValue);
default -> inputValue;
};
System.out.println(processValue(value));
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap3HashMap Part 2
HashMap MethodsIterate with keySet()Iterate with entrySet()Nested HashMapRecap - Manage WarehouseRecap - HashMap Operations6Advanced Control Flow
Label StatementsSwitch ExpressionPattern MatchingGuard ClausesRecap - Control Flow