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

392 Upvotes

279 comments sorted by

View all comments

17

u/Azoraqua_ Aug 03 '25

Not exactly all that useful, but you can declare classes (presumably record’s too) inside methods:

void printJohnInAnOverlyComplexWay() {
  record Pair<T1, T2>(T1 one, T2 two) { }

  System.out.println(Pair(“John”, 47));
}

26

u/OddEstimate1627 Aug 03 '25

On a similar note, var exposes newly defined methods in anonymous classes, e.g.,

public int getNumber() {
    var obj = new Object() {
        int getNumber() {
            return 0;
        }
    };
    return obj.getNumber();
}

5

u/MasterTaticalWhale Aug 04 '25

Woah. This is the strangest info from this post, I can simultaneously imagine so many scenarios on where it would be useful but at the same time so many scenarios where doing so would be hella confusing for someone else/future me

1

u/OddEstimate1627 Aug 06 '25

I've never used it in production. The only use case I can think of is to get access to protected state without having to create an actual subclass.

6

u/joemwangi Aug 04 '25

And if the record doesn’t escape the method, it may not even be declared as a full class. The compiler is often smart enough to optimize it away and only generate the necessary component logic (like constructor and accessors), or scalarize it entirely.

6

u/vegan_antitheist Aug 05 '25

This is great when you need such a record to group some elements but never expose the classifier because you then just process that group in the same method. Example:

  record Pair(Foo foo, Bar bar) { }
  data.collect(Collectors.groupingBy(e -> new Pair(e.getFoo(), e.getBar())))).forEach(...)

2

u/nursestrangeglove Aug 08 '25

I love this monkey wrenched tuple so much I'm going to use it all the time now haha

1

u/Zardoz84 Aug 04 '25

Before lambdas, was we use to do build "Functors" objects.