Java
Record
Java 14+ record classes.
By EZ4Code Team
recorddata-class
Code
// Define record
public record Point(int x, int y) {}
// Usage
Point p = new Point(3, 4);
System.out.println(p.x()); // 3
System.out.println(p.y()); // 4
System.out.println(p); // Point[x=3, y=4]
// Compact constructor
public record Range(int start, int end) {
public Range {
if (start > end) {
throw new IllegalArgumentException("start > end");
}
}
}
// Custom method
public record Circle(double radius) {
public double area() {
return Math.PI * radius * radius;
}
}Explanation
Record is an immutable data carrier, auto-generating constructor, accessors, equals, hashCode, and toString.
More Java Snippets
String Operations and StringBuilder
Manipulate strings with split, join, substring, and StringBuilder in Java.
Stream API
Process collections using the Stream API.
Lambda Expressions
Simplify code with Lambda expressions.
Optional
Handle null values elegantly.
Collection Operations
Common operations on List, Set, and Map.
Exception Handling
try-catch-finally and custom exceptions.