Java 8
The main changes of the Java 8 release were these:
· Lambda Expression and Stream API
Java 9
Java 9 introduced these main features:
· Diamond Syntax with Inner Anonymous Classes
var
Switch
expressions allowed us to omit break
calls
inside every case
block.
Using Switch Expressions
days = switch (month) {
case JANUARY, MARCH, MAY, JULY, AUGUST, OCTOBER, DECEMBER -> 31;
case FEBRUARY -> 28;
case APRIL, JUNE, SEPTEMBER, NOVEMBER -> 30;
default -> throw new IllegalStateException();
};
The yield Keyword
days = switch (month) {
case JANUARY, MARCH, MAY, JULY, AUGUST, OCTOBER, DECEMBER -> {
System.out.println(month);
yield 31;
}
defining variable Car c and Bicycle b
public class PatternMatching {
public static double price(Vehicle v) {
if (v instanceof Car c) {
return 10000 - c.kilomenters * 0.01 -
(Calendar.getInstance().get(Calendar.YEAR) -
c.year) * 100;
} else if (v instanceof Bicycle b) {
return 1000 + b.wheelSize * 10;
} else throw new IllegalArgumentException();
}
}
public record VehicleRecord(String code, String engineType) {}
we cannot extend a record class
public sealed class Vehicle permits Bicycle, Car {...}
The final modifier on a class doesn’t allow anyone to extend it
What about when we want to extend a class but only allow it for some classes?
public sealed class Vehicle permits Bicycle, Car {...}