Last active
April 17, 2025 04:54
-
-
Save joshlong/fcca98b7bbe0a09bd9927d138e970feb to your computer and use it in GitHub Desktop.
a simple Java 23 program demonstrating some of the things showing how nice modern Java can be, based on the C# equivalent shown in https://youtu.be/1I3mWSiWNsI?feature=shared&t=374
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// sdk install java 23.0.1-librca && sdk use java 23.0.1-librca | |
// java --enable-preview Main.java | |
record Point(int x, int y) {} | |
sealed interface Shape permits Rectangle, Circle {} | |
record Rectangle(int width, int height) implements Shape {} | |
record Circle(int radius) implements Shape {} | |
void main() { | |
var point = new Point(1, 2); | |
println(describePoint(point)); | |
var shape = new Circle(5); | |
var area = calculateArea(shape); | |
println("Area of the shape: %s !%n".formatted( area)); | |
} | |
String describePoint(Point point) { | |
return switch (point) { | |
case Point(int x, int y) when x == 0 && y == 0 -> "Origin"; | |
case Point(int x, int y) when x == 1 && y == 2 -> "1,2"; | |
default -> throw new IllegalStateException("Unexpected value: " + point); | |
}; | |
} | |
double calculateArea(Shape shape) { | |
return switch (shape) {//exhaustive checking | |
case Rectangle(var height, var width) -> height * width; | |
case Circle(var radius) -> Math.PI * radius * radius; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
here is for reference the original C# code against which i was comparing