Reputation: 457
public class BuildStuff {
public static void main(String[] args) {
Boolean test = new Boolean(true);
Integer x = 343;
Integer y = new BuildStuff().go(test, x);
System.out.println(y);
}
int go(Boolean b, int i) {
if(b)
return (i/7);
return (i/49);
}
}
This is from SCJP , I understand that answer is "49", but I have a doubt. When we create an object and pass a value in that object. Let's say: Dog d = new Dog("tommy");
in this statement d is reference to object Dog and Dog has "name" instance variable set to "tommy". But it doesn't mean d = tommy
.
However, in case of Boolean, when we passed true in Boolean Object. It sets reference to true. Why it is in case of Boolean? Is there any other class too?
Upvotes: 1
Views: 965
Reputation: 178243
The passed-in Boolean
b
can be converted to a primitive boolean
with an unboxing conversion, resulting in the expression true
for the if
statement.
All primitive types have corresponding built-in wrapper classes for them, and Java will unbox/box as necessary.
(An unboxing conversion will fail with a NullPointerException
if the corresponding wrapper class instance is null
:
Boolean test = null;
// NPE
boolean b = test;
)
Here's Java's tutorial on boxing and unboxing.
Upvotes: 3
Reputation: 8336
From the javadoc: The Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field whose type is boolean.
If you have
Boolean a = new Boolean(true);
Boolean b = new Boolean(true);
a
and b
are different objects, but a.booleanValue()
and b.booleanValue()
return the same primitive. This can be verified by testing a == b
versus a.equals(b)
.
There are other classes like this, viz. Integer, Double, etc. As others have already mentioned, you should look into autoboxing and unboxing.
Upvotes: 1