r/java • • Aug 03 '25

Teach Me the Craziest, Most Useful Java Features — NOT the Basic Stuff

I want to know the WILD, INSANELY PRACTICAL, "how the hell did I not know this earlier?" kind of Java stuff that only real devs who've been through production hell know.

Like I didn't know about modules recently

393 Upvotes

279 comments sorted by

View all comments

94

u/ResponsibleLife Aug 03 '25

Record pattern matching and guard statements in switch expressions:

String result = switch (object) {
    case Location(var name, var ignored) when name.equals("Home") -> new Location("Test", new GPSPoint(1.0, 2.0)).getName();
    case Location(var name, var ignored) -> name;
    default -> "default";
};

39

u/__konrad Aug 03 '25

Java 22 allows _ as unused variables:

case Location(var name, _) -> name;

4

u/Jitir Aug 03 '25

And afaik it made its way to 22 without any change compared to 21, so it should be safe to enable in 21.

2

u/koflerdavid Aug 04 '25

This is a real boon. Once we upgrade I can eliminate all the variables named like ignored!

1

u/shinmai_rookie Aug 04 '25

Finally? I kept reading about it as pretty much official in all but name but wherever I try it it's still a beta feature (I can't recall the specific term in Java). Not that it changes much but still.

16

u/MrDilbert Aug 03 '25

As someone who got swept away from the Java world somewhere around version 6 - in which version was switch-case pattern matching introduced? So far I've only seen it in Scala, kind of.

26

u/Degerada Aug 03 '25

Java 21

1

u/True-Fortune-2667 Aug 13 '25

Actually in 17

1

u/Degerada Aug 13 '25

But not record pattern matching, which is what the upper example is about. See JEP 440, introduced in Java 21. https://openjdk.org/jeps/440

4

u/Alacho Aug 03 '25

So far I've only seen it in Scala

Not on topic, but this is an integral part of Rust. 

3

u/hojimbo Aug 03 '25

And Python since 3.10

1

u/josuf107 Aug 04 '25

And Haskell since version 98

1

u/Wyvernxx_ Aug 04 '25

As someone who has only used Java 8, 11, and 17 extensively, this doesn't look like java at all. I really do need to take a look at the newest versions!