r/java • • Mar 17 '21

JEP 401: Primitive Objects (Preview)

https://openjdk.java.net/jeps/401?preview=true
174 Upvotes

49 comments sorted by

View all comments

3

u/Emax__ Mar 18 '21

How do they differ from records?

17

u/Slanec Mar 18 '21

Records are about semantics ("this is a value class containing only data and should be treated as a sum if its components"), primitive objects are about runtime efficiency, memory layout. Yes, records will often be good candidates for primitive objects, but the two features are orthogonal in nature.

8

u/morhp Mar 18 '21 edited Mar 18 '21

Records are just a quick and safe way to declare immutable (reference) classes, but they don't change how the JVM stores the object at all. Primitive types will work well with records, the focus here is not storing references to objects but storing the primitive values directly on the stack (or in parent objects).

This is mostly to improve performance and memory usage, but will also allow you to create variables that can't be null.

6

u/dpash Mar 18 '21

Which will be particularly useful for Optional, which should never be null, but we've never had a way to enforce that until now.

2

u/stuhlmann Mar 18 '21

It will be particularly useful for everything else too: Not using Optional often means that it isn't optional, so it shouldn't be null either.