Many people think Java is a verbose language. I've heard a joke that if your employer pays you by lines of code, then Java is the way to go.
With updates to Java, modern Java isn't so verbose anymore, so check it out.
If you're starting a new project, use modern Java today.
1. Use record
instead of lombok
✅ Use record
public record User(String id, String name) {}
🙅 Instead of lombok annotations
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String id;
private String name;
}
🙅 And instead of getter, setter, equals()
, hashCode()
, toString()
, and etc.
public class User {
private String id;
private String name;
public User(String id, String name) {
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
// equals(), hashCode(), toString() and etc. are omitted below.
}
2. Use var
instead of class name
✅ Use var
var user = new User("1", "Tom");
🙅 Instead of duplicated class name
User user = new User("1", "Tom");
3. Use STR."\{}"
instead of +
between strings
✅ Use STR."\{}"
var firstName = "Thomas";
var lastName = "Cat";
var fullName = STR."His name is \{firstName} \{lastName}.";
🙅 Instead of +
and " "
var firstName = "Thomas";
var lastName = "Cat";
var fullName = "His name is " + firstName + " " + lastName + ".";
🙅 And instead of new StringBuilder()
and append()
var firstName = "Thomas";
var lastName = "Cat";
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("His name is ").append(firstName).append(" ").append(lastName).append(".");
var fullName = stringBuilder.toString();
4. Use """
instead of "\n"+
between multiline strings
✅ Use """
var html = """
<html>
<body>
<p>Hello World!</p>
</body>
</html>
""";
🙅 Instead of "\n"
and +
var html =
"<html>\n" +
"<body>\n"+
" <p>Hello World!</p>\n"+
"</body>\n"+
"</html>\n";
5. Use .of()
instead of .add()
when to init a list
✅ Use List.of()
var list = List.of(1, 2, 3);
🙅 Instead of Stream
var list = Collections.unmodifiableList(Stream.of(1, 2, 3).collect(toList()));
🙅 And instead of new ArrayList<>()
and .add()
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list = Collections.unmodifiableList(list);
Conclusion
I've listed the 5 modern Java features I use most often. And using them gives me the joy of Java programming. 🍹
The official names of these features are:
- JEP 395: Records
- JEP 286: Local-Variable Type Inference
- JEP 430: String Templates (Preview)
- JEP 378: Text Blocks
- JEP 269: Convenience Factory Methods for Collections
By the way, the examples above are based on JDK 21, the latest LTS version.
What are your favorite modern Java features?
Top comments (1)
Great guide on modern Java features! It's clear and helpful for beginners. To improve, consider adding a section on how these updates impact performance. Keep up the great work! 🚀