In Java we have primitive data types and bunch of wrapper classes for them. My question is that when to use what? I know that when we need to create Collections, we will need to use the wrapper classes, but other than that are there other specific cases where one should use wrapper classes?
Also, is it that one should always use the primitive data types unless absolutely necessary?
For example if I am creating a Class having an integer and a boolean properties:
Class MyClass {
...
private Integer x;
private Boolean y;
...
}
OR
Class MyClass {
...
private int x;
private boolean y;
...
}
Which of them should be used more often? And in what scenarios the other one should be used?
Use the primitive type unless you have no other choice. The fact that it’s not nullable will prevent many bugs. And they’re also faster.
Besides collections, wrapper types are typically used to represent a nullable value (for example, coming from a database nullable column).