What are Java Patterns

Updated: 2024-04-04

Java is evolving fast and introducing a lot of [some name] Pattern, here you can find a quick recap.

Type patterns

They allow us to check if a variable is of a specific type and use it:

if (animal instanceof Cat cat) { 
    cat.meow(); // <- the 'cat' is automatically assigned and usable 
} 

In the past we had to convert a in cat before to use it. With type pattern Java knows that cat is of type Animal and it can use its properties.

Similarly, we can use this pattern with switch:

switch (animal) { 
    case Cat cat -> cat.meow();  
} 

Guarded patterns

You can add boolean conditions to the switch hand have a guarded pattern

class Animal { } 
 
class Cat extends Animal { 
  public String meow() { 
    System.out.println("jerry speaks italian"); 
    return "miao"; 
  } 
} 

In our Java code we check the case that the instance is of type Cat and with when that a boolean condition is true to return the correct value.

 
Animal jerry = new Cat(); 
 
switch (jerry) { 
  case Cat jerryTheCat when jerryTheCat.meow().equals("miao") -> "correct"; 
  case Cat jerryTheCat when jerryTheCat.meow().equals("meow") -> "error"; 
  default -> "default - error"; 
} 

If I execute the code in JShell I will get the result:

switch (jerry) { 
    case Cat jerryTheCat when jerryTheCat.meow().equals("miao") -> "correct"; 
    case Cat jerryTheCat when jerryTheCat.meow().equals("meow") -> "error"; 
    default -> "default - error"; 
} = "correct" 
jerry speaks italian 

Record patterns

Records in Java are final and the state doesn't change, for this reason the runtime has more options to work with the object and we can deconstruct them:

public record Dog (String name) { 
    public String bark() {return "Wof!";} 
} 
 
Dog snoopy = new Dog("Snoopy"); 
 
void doSomething(Object obj) { 
 if (obj instanceof Dog(String name)) { 
   System.out.println("name: " + name); 
  } 
} 

If you try in JShell:

jshell> doSomething(snoopy) 
name: Snoopy 

WebApp built by Marco using SpringBoot 3.2.4 and Java 21, in a Server in Switzerland without 'Cloud'.