Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting boolean to Boolean in java

i have a code as

public class BooleanTest {
    public BooleanTest() {
        super();
    }


    public static void main(String args[]){
      BooleanTest bt = new BooleanTest();
      bt.doProcess();

    }

    private boolean method() {
        return false;
    }

    private void doProcess() {
      Boolean obj = (Boolean)method();
      System.out.println(obj.booleanValue());
    }
}

the question is can line System.out.println(obj.booleanValue()); throw NullPointerException in any situation?

like image 318
Vik Avatar asked Oct 20 '10 12:10

Vik


People also ask

Can we cast boolean in Java?

To convert String to Boolean, use the parseBoolean() method in Java. The parseBoolean() parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".

Can boolean be casted?

You cannot cast a BOOLEAN to a DECIMAL . You cannot cast a STRING value to BOOLEAN , although you can cast a BOOLEAN value to STRING , returning '1' for true values and '0' for false values. Although you can cast a TIMESTAMP to a BOOLEAN or a BOOLEAN to a TIMESTAMP , the results are unlikely to be useful.

How do you cast a boolean to an object?

To convert Boolean Primitive to Boolean object, use the valueOf() method in Java. Firstly, let us take a boolean primitive. boolean val = false; To convert it into an object, use the valueOf() method and set the argument as the boolean primitive.

Can you cast int to boolean?

You cannot cast an integer to boolean in java. int is primitive type which has value within the range -2,147,483,648 to 2,147,483,647 whereas boolean has either true or false. So casting a number to boolean (true or false) doesn't makes sense and is not allowed in java.


2 Answers

No, when you box a primitive value into its equivalent wrapper type, the result is never null.

like image 85
Jon Skeet Avatar answered Oct 22 '22 12:10

Jon Skeet


It will never throw a NPE and also if you are using java >= 1.5, you don't need to cast it. It is called autoboxing which is introduced from JDK 1.5.

like image 31
Teja Kantamneni Avatar answered Oct 22 '22 13:10

Teja Kantamneni