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?
First off you need to understand the difference between the two types.
double
is a primitive type whereasDouble
is an Object.The code below shows an overloaded method, which I assume is similar to your lab code.
There are several ways you can call these methods:
These calls will result in:
Evidently, if you pass a
Double
object then Method A will be called; i.e. if you had something like:Further, if you pass a double literal you will call Method B. What's interesting is if you have something like
In this case Method B will also be called, because the type of
d
isdouble
; theDouble
object gets unboxed to adouble
. On the same note, if you had:then Method A would be called, because the type of
d
would beDouble
(thedouble
-literal gets autoboxed to aDouble
).What you have is an example of method overloading. The good part is that the compiler and the JVM will select the correct method automatically based on the type of the arguments that is used when you call the method.
Double is a wrapper class while double is a primitive type like c/c++. As pointed out above, Double is mostly used in generics but also is useful anywhere there is a need for both numerical value and proper object encapsulation. In most cases the Double and double can be used interchangeably.
Double
parameter can benull
whendouble
can't.Double
is reference type anddouble
is value type.As @Fess mentioned and because
Double
is reference type it can benull
.If you want you can explictly convert from
Double
todouble
with.doubleValue()
method and viceverrsa withnew Double(1.0)
.Also as @millimoose said: