Reputation:
I learned from looking at other references & SO that the Double
has a lot of disadvantages.
Double disadvantages compared to double primitive data type:
Now, I know there are some manipulation what we can do With Double. JavaDoc but most (85%) of these methods are static there fore it not a huge advantage. Another thing I know that double cannot be null.
Double doubleClass = null; // Is valid
double doubleType = null; // Results in NPE
After all these disadvantages I cannot understand why we would use Double and not double in real life scenario. Can some give a real world example and explain.
Thanks
Upvotes: 3
Views: 1583
Reputation: 6816
There are many main reasons that you should use Double
The Collections API that need to use the class and not primitive type
Some cases you know that double can have varying precision if the come from different data source. You can use the class .equals note most of the cases
double d1,d2; // Initalized to some value
d1==d2; // will return true but some(very few will return false)
You can read about this on .equals method
As you have mentioned that Double can be null and double cannot be. Think of a scenario where a value of some object may or may exist if it doesn't then we want it as null in the database on retrieving it will throw an NPE with double but with Double it won't.
You should use the primitive type whenever possible and not Double.
Upvotes: 3
Reputation: 36304
Double
is a wrapper class over the primitive double. The Java Collection framework has containers like List, Set etc. The problem with those containers is that they cannot accept primitives. So, double is implicitly converted to Double and inserted into the collections (Autoboxing).
Double doubleClass = null; // Is valid --> Double is not a primitive. So, you can get NPE if you do doubleClass.someInstanceLevelFieldOrMethod.
double doubleType = 5.5; //is a primitive
.
Also, Double will be slower than double because there is some book-keeping / overhead for Classes unlike primitives.
PS : Double provides many APi / methods to do things. example - Double.parseDouble(TypeX value)
Creates a new double from value of TypeX
Upvotes: 3
Reputation: 49734
There are two main reasons as far as I can see.
Double
is a reference type and therefore can be null
. Sometimes that information is important. (Imagine a scenario when a user can fill in various fields in a form, some are optional and you want to find out whether a field was filled in. A null
value is a reasonably good indicator that a form field was left empty.)But in general you're right, whenever possible, you should use the primitive type.
Upvotes: 4