Either works
As you noted, primitives require less memory. But objects have advantages, especially in some situations where objects will be expected rather than primitives. And in some situations, a primitive may be expected, though auto-boxing generally handles that. The compiler will certainly alert you when encountering these situations.
And Skliar makes a valid point about primitives having default values while objects do not. Either might be an advantage depending on the coding situation.
Keep in mind that, for most of your work, you should not worry about this. Such worries are an example of premature optimization. You almost certainly have more important things to worry about.
For many common business apps, the memory usage is inconsequential. My own default is to use objects, for the convenience and the features. From what I have noticed over the years, usage seems fairly split with some folks tending towards primitives and some towards objects.
The only situation where I think twice about primitive-versus-object is where auto-boxing may be invoked when dealing with loops through much data. In such a case, a mere declaration of int
versus Integer
might make a significant impact by avoiding pointless boxing. But, again, do not worry excessively about this, as relying on auto-boxing is perfectly acceptable and is usually the best policy.
record
Java 16+ now offers the records feature. A record is a brief way to write a class whose main purpose is to communicate data transparently and immutably. You simply declare the member field types and names. The compiler implicitly generates the constructor, getters, equals
& hashCode
, and toString
methods.
I mention records merely to say this handy new feature, likely to become very popular, supports both objects and primitives. So using records does not affect the object-versus-primitive decision.
Your example class would be:
public record Student( Long id , String name , Boolean isGraduated , Integer age ) {}
… or:
public record Student( long id , String name , boolean isGraduated , int age ) {}
Usage is the same as a conventional class.
Student alice = new Student( 101L , "Alice" , false , 33 ) ;
Blurring the difference
You should know that the Java team at Oracle, and related community, are interested in blurring the difference between primitives and objects. Of course, the trick is doing so while honoring the extreme backward-compatibility that is a hallmark of the Java platform.
Some of this work is being done as part of Project Valhalla, including the possible addition of value types to Java.
To learn more about possible future directions in this regard, see talks given by Brian Goetz of Oracle, and others. Use your favorite search engine to search for “Java JEP primitive”. You will find links to JEPs such as:
Boolean
. Thanks a lot, I will keep it in mind. – ScrabbleOptionalInt
and similar containers for optional values that are self documenting. – Coca