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).
this article talks about wrapper classes, they said:
The wrapper classes in the Java API serve two primary purposes:
1- To provide a mechanism to “wrap” primitive values in an object so that the primitives can be included in activities reserved for objects, like as being added to Collections, or returned from a method with an object return value.
2- To provide an assortment of utility functions for primitives. Most of these functions are related to various conversions: converting primitives to and from String objects, and converting primitives and String objects to and from different bases (or radix), such as binary, octal, and hexadecimal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With