Possible Duplicate:
Java : different double and Double in comparison
In a sample java program for one of my labs, I have two different methods taking Double and double parameters respectively.
How do I differentiate between them when passing arguments to them?
Double is a class. double is a key word used to store integer or floating point number. double is primitive and Double is wrapper class.
Double is an object and double is a primitive data type. See this answer for more details. The Double class wraps a value of the primitive type double in an object.
doubles are not exact. It is because there are infinite possible real numbers and only finite number of bits to represent these numbers.
Java double is used to represent floating-point numbers. It uses 64 bits to store a variable value and has a range greater than float type. Syntax: // square root variable is declared with a double type.
Double
parameter can be null
when double
can't.
First off you need to understand the difference between the two types.
double
is a primitive type whereas Double
is an Object.
The code below shows an overloaded method, which I assume is similar to your lab code.
void doStuff(Double d){ System.out.println("Object call"); }
void doStuff(double d){ System.out.println("Primitive call"); }
There are several ways you can call these methods:
doStuff(100);
doStuff(200d);
doStuff(new Double(100));
These calls will result in:
"Primitive call"
"Primitive call"
"Object call"
- double
is a primitive type, where as Double
is a wrapper object.
- One of the most common use of Wrapper objects is with Collection
.
Eg:
List<Double> d = new ArrayList<Double>();
- In Java 5 a mechanism called Autoboxing
has been introduced to convert between the two directly.
Eg:
double d = 10.41;
Double wrapper = d;
Double
is reference type and double
is value type.
The
Double
class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double." link
As @Fess mentioned and because Double
is reference type it can be null
.
If you want you can explictly convert from Double
to double
with .doubleValue()
method and viceverrsa with new Double(1.0)
.
Also as @millimoose said:
You should use
X.valueOf()
instead ofnew X()
. ThevalueOf
methods are allowed to cache the boxing types to reduce memory use. (Not sure this is done forDouble
s but it's a good habit to get into.)"
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