简体   繁体   中英

pass value in Boolean Object

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?

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.

  • Boolean <=> boolean
  • Byte <=> byte
  • Character <=> char
  • Short <=> short
  • Integer <=> int
  • Long <=> long
  • Float <=> float
  • Double <=> double

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM