Two features shorten the Java considerably. There are the records, which turn a class of the data fields into a single line of the declaration, and there is the switch expression form, which turns a multi-line switch statement into an expression with a value. Neither is revolutionary on its own, but together they remove a lot of the boilerplate from the everyday code that carries the data around.
The previous lesson in this module covered "How Do Collectors Shape Stream Output Into Lists, Maps and Groups?", and the next lesson in this module is about "What Are Pattern Matching and Sealed Classes?".
What does a record give you?
A record is a class that is declared with record instead of class. You list the fields, and the compiler generates the constructor, the accessors, the equals, the hashCode and the toString for you. What you write is the shape of the data, and the rest is the bookkeeping.
public class RecordBasics {
record Point(int x, int y) {
Point {
if (x < 0 || y < 0) {
throw new IllegalArgumentException("coordinates must not be negative");
}
}
}
public static void main(String[] args) {
Point p = new Point(3, 4);
System.out.println("accessors : " + p.x() + "," + p.y());
System.out.println("toString : " + p);
System.out.println("equals : " + p.equals(new Point(3, 4)));
System.out.println("hash : " + (p.hashCode() == new Point(3, 4).hashCode()));
try {
new Point(-1, 2);
} catch (IllegalArgumentException e) {
System.out.println("compact constructor : " + e.getMessage());
}
}
}The output is this.
accessors : 3,4
toString : Point[x=3, y=4]
equals : true
hash : true
compact constructor : coordinates must not be negativeThere are three things to notice. The accessors are named x() and y(), and not getX(). The records do not use the getter convention. The generated equals compares the field values, so two points with the same coordinates are equal, and the generated hashCode is consistent with it. And the compact constructor, which is the one with no parameter list, is where you validate the data, because the compiler runs it as a part of every constructor call.
What is a record not?
A record is immutable. Its fields are final, there are no setters, and you cannot extend a record. That is a feature. A value that cannot change after the creation can be shared freely, it can be used as a map key, and it can be passed between the threads without any ceremony. It is also a limit, so a record is the right shape for a value like a point, a price or a date, and the wrong shape for anything with the behaviour or the identity.
A record can still have the behaviour. You can add the static factory methods, the instance methods, and the nested types.
public class RecordFeatures {
record Money(long amount, String currency) {
Money {
if (currency == null || currency.isBlank()) {
throw new IllegalArgumentException("currency required");
}
}
static Money zero(String currency) {
return new Money(0, currency);
}
Money withAmount(long newAmount) {
return new Money(newAmount, currency);
}
}
public static void main(String[] args) {
Money price = new Money(1250, "EUR");
System.out.println("price : " + price.amount() + " " + price.currency());
System.out.println("zero : " + Money.zero("EUR"));
System.out.println("copy : " + price.withAmount(999));
System.out.println("no setters : fields are final");
}
}The output is this.
price : 1250 EUR
zero : Money[amount=0, currency=EUR]
copy : Money[amount=999, currency=EUR]
no setters : fields are finalThe method withAmount shows the pattern that replaces a mutating setter in the immutable code. It returns a new instance with one field changed. The zero factory shows why the static factories are useful on the records. The call new Money(0, "EUR") is fine, but a named factory documents the intent at the call site.
How does the switch expression form work?
A switch expression is a switch that produces a value. You write switch (value) { ... } in an expression position, and each branch ends with an arrow and an expression. No break is needed, because a branch cannot fall through.
public class SwitchExpression {
enum Plan { FREE, PRO, TEAM }
static String price(Plan plan) {
return switch (plan) {
case FREE -> "0.00";
case PRO -> "9.99";
case TEAM -> "29.99";
};
}
static String describe(String day) {
return switch (day) {
case "sat", "sun" -> "weekend";
case "mon", "tue", "wed", "thu", "fri" -> "weekday";
default -> "unknown day";
};
}
public static void main(String[] args) {
for (Plan plan : Plan.values()) {
System.out.println(plan + " -> " + price(plan));
}
System.out.println(describe("sat"));
System.out.println(describe("mon"));
System.out.println(describe("funday"));
int days = switch (2) {
case 1, 7 -> 1;
case 2, 3, 4, 5, 6 -> 5;
default -> 0;
};
System.out.println("weekdays in the value : " + days);
}
}The output is this.
FREE -> 0.00
PRO -> 9.99
TEAM -> 29.99
weekend
weekday
unknown day
weekdays in the value : 5Two features make the switch expressions worth using. First, several labels can share one branch, so case "sat", "sun" handles the weekend in a single line. Second, the whole thing is an expression, so you can put it straight into a return, into a string concatenation, or into a variable assignment without a temporary. A switch over a string works because the compiler checks that the labels cover the cases that you handle, and the default branch catches everything else.
When do you need yield?
You need it when a branch needs more than one statement. You wrap it in the braces and you use yield to produce the value. Without the yield the block would be a plain statement block with no value to contribute.
public class SwitchYield {
static int score(int points) {
int result = switch (points) {
case 0 -> 0;
default -> {
int bonus = points / 10;
yield points + bonus;
}
};
return result;
}
public static void main(String[] args) {
System.out.println("score of 0 : " + score(0));
System.out.println("score of 50 : " + score(50));
System.out.println("old style still works : " + legacy(2));
}
static String legacy(int value) {
String label;
switch (value) {
case 1:
label = "one";
break;
case 2:
label = "two";
break;
default:
label = "many";
}
return label;
}
}The output is this.
score of 0 : 0
score of 50 : 55
old style still works : twoThe last part of that program is worth keeping in view. The old switch statement still compiles and it still works. The new form is not a replacement that you have to adopt everywhere. It is a better tool for the cases where a value comes out of a switch, and you can mix the two styles in the same codebase.
What are the rules for the new switch?
- Every branch must produce a value, or the whole expression does not compile.
- There is no fall-through, so the break is unnecessary and forbidden in the arrow form.
- The multiple labels per branch are written
case a, b ->. - You use yield inside a block branch to supply the value.
- A default branch is required for the types that could take the other values, such as the strings.
- The expression form works over the enums, the strings, the numbers and any other type.
When do the records and the switch expressions combine?
They combine in exactly the place that you would expect. It is a switch over the type of a record, where each branch pulls the fields that it needs out of the pattern. That is the subject of the next lesson, which covers the pattern matching and the sealed types. For now, the pairing to remember is simple. You use a record when the data is the point, and you use a switch expression when a decision produces a value.
The habits worth keeping
- Reach for a record when a class is just the data with a constructor and the accessors.
- Validate inside a compact constructor, so that the bad instances cannot exist.
- Use the static factories for the values that have a meaningful name.
- Return a new instance instead of adding a setter to an immutable type.
- Use a switch expression whenever the switch produces a value.
- Group the labels with the commas instead of stacking the empty cases.
Try it yourself: define a record Order with an id, a customer, a list of the line items and a total, and validate in the compact constructor that the id is not blank and the total is not negative. Then write a switch expression over an enum of the order states that returns the text that a customer should see, and add a withTotal method that returns a corrected copy.