Issue
As a beginner at Java, I am confused while choosing the variable types in entity or model classes. As mentioned on Java Primitives versus Objects, both of them have some pros and cons e.g. memory usage. However, I would like to know the general approach while creating entity or model classes. So, in this case, should I prefer Primitive or Object type for variables for long, boolean, int, etc. as shown below?
public class Student {
private Long id; // long ?
private String name;
private Boolean isGraduated; // boolean ?
private Integer age; // int ?
}
Solution
Default value of Long and Integer variable is null.
But default value of long and int is 0
Compare:
If you use Objects:
public class Student {
private Long id; // long ?
private String name;
private Boolean isGraduated; // boolean ?
private Integer age; // int ?
}
id => null
age => null
If you use primitives:
public class Student {
private long id; // long ?
private String name;
private Boolean isGraduated; // boolean ?
private int age; // int ?
}
id => 0
age => 0
In many scenarios having 0 as default value is confusing, so it makes sense to use Objects in this case. If object value is "null" you know for sure that the value was not initialized. But if primitive value is "0", then it is not clear: is it a default uninitialized value, or this value was initialized with "0".
I generally prefer using primitive types, unless I need explicit null-check
Answered By - Mykhailo Skliar
Answer Checked By - David Goodson (JavaFixing Volunteer)