Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practices : What to use, wrapper classes or primitive data types? [duplicate]

Tags:

java

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?

like image 753
Amar Avatar asked Dec 16 '12 14:12

Amar


2 Answers

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).

like image 152
JB Nizet Avatar answered Sep 23 '22 20:09

JB Nizet


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.

like image 39
Sawan Avatar answered Sep 23 '22 20:09

Sawan