Java null pointer exception after checking if null - java

Can anybody explain how is it possible that I am getting null pointer exception thrown from this line of code:
if (data != null && data.isActive()) {
Body of method isActive() is just:
public Boolean isActive()
{
return active;
}
Thanks in advance.

In java, there's a thing called autoboxing, when primitive values are wrapped by object types and vice versa.
So, in your code there is a method:
public Boolean isActive()
{
return active;
}
note, that you are returning Boolean (object type), not boolean (primitive type).
and return value is going to be used in your if statement.
if (data != null && data.isActive()) {
when java meets data.isActive() in your if statement, it tries to convert Boolean value to primitive boolean value, to apply it for your logical operation.
But your active variable inside of your isActive() method is null, so java is unable to unbox this variable to boolean primitive value, and you get Null pointer exception.

Related

How to compare object type with boolean

import java.util.HashMap;
public class file{
public static void main(String args[]){
Object a;
a = true;
if (a == true){
System.out.println("Yes");
}
}
}
I get the error error: incomparable types: Object and boolean
I was to compare object a which stores a boolean value with an actual boolean type. How do I do that?
This happens because boolean primitive true is boxed for conversion to Object. You need to compare it to another boxed object, like this
if (a == Boolean.TRUE) {
...
}
or like this
if (a.equals(true)) {
...
}
You are comparing an Object reference to a primitive boolean - the types are not compatible for the equality operator (==). You should generally avoid using == with objects unless you really want to check if it is the same reference.
Prefer the equals method to compare objects.
if (Boolean.TRUE.equals(a)) { ... do stuff ... }
Note that we are invoking the method on a statically defined instance and passing the variable to be tested as the argument. The method will handle null arguments and incorrect type arguments (it will return false) so you don't have to.
Try this -
if (Boolean.TRUE.equals(a)) { ... }

incomparable types boolean and nulltype

When I compile my code this way, I get the mentioned error:
public class SymTree{
public static boolean isSym(BT bt)
{
return(IsMirror(bt.left, bt.right));
}
private static boolean IsMirror(BT lr,BT rr)
{
if(lr==rr==null) (((ERROR HERE)))
return true;
.....
However when I compile like this
private static boolean IsMirror(BT lr,BT rr)
{
if(lr==rr)&&(lr==null))
return true;
.......
I get no error. The error is uncomparable types with nulltype and boolean, however non of my compared objects are boolean- they are both objects from a BT(Binary Tree) class, which has been defined elsewhere.
Thank you!
Examine (lr==rr==null). lr==rr is a boolean. It is primitive and can not be compared to null.
The reason it's giving you that error is because when you write this:
if (lr==rr==null)
The compiler interprets it similar to one of the following:
if ((lr==rr) == null)
if (lr == (rr==null))
Basically, you're comparing a boolean condition (either lr==rr or rr==null) to a nullable type, which doesn't make sense since booleans are value types and can never be null.
It is because in if(lr==rr==null), lr==rr is a boolean comparison which you are comparing with a null by doing ==null.
For Example, if suppose lr is equal to rr then lr==rr will return true next you are comparing whether true==null. Here you get error because boolean and null are not comparable.

Can Boolean.valueOf(String) return null?

Can Boolean.valueOf(String) ever return null? From what I can see in the java docs, the docs only specify when it returns true. Is false always returned otherwise, or can null be returned? I have not been able to get it to return null in the tests I have done, but I would like to be sure.
Essentially, I want to know if the following code is safe from a NullPointerException:
boolean b = Boolean.valueOf(...);
The docs pretty much answer it: no. It'll return a Boolean representing a true or false.
The code is also available:
public static Boolean valueOf(String s) {
return toBoolean(s) ? TRUE : FALSE;
}
No, this is impossible. See the source code of the class Boolean:
public static Boolean valueOf(String s) {
return toBoolean(s) ? TRUE : FALSE;
}
.. and then:
private static boolean toBoolean(String name) {
return ((name != null) && name.equalsIgnoreCase("true"));
}
Actually it could cause NPE but can not return null. Try this:
Boolean bNull = null;
System.print(Boolean.valueOf(bNull)); // -> NPE!
This happens cuz Boolean.valueOf() accepts String or boolean values. Since bNull is of type Boolean java tries to unbox bNull value to pass it as boolean which causes NPE. Its funny but stupid actually... Also there is no Boolean.valueOf() for Number.
No it will not. If null is placed within the argument or if a string is set to null it will return a boolean value of false. You can see expected inputs and outputs in the Java docs: http://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html#booleanValue()

No Exception while type casting with a null in java

String x = (String) null;
Why there is no exception in this statement?
String x = null;
System.out.println(x);
It prints null. But .toString() method should throw a null pointer exception.
You can cast null to any reference type without getting any exception.
The println method does not throw null pointer because it first checks whether the object is null or not. If null then it simply prints the string "null". Otherwise it will call the toString method of that object.
Adding more details: Internally print methods call String.valueOf(object) method on the input object. And in valueOf method, this check helps to avoid null pointer exception:
return (obj == null) ? "null" : obj.toString();
For rest of your confusion, calling any method on a null object should throw a null pointer exception, if not a special case.
You can cast null to any reference type. You can also call methods which handle a null as an argument, e.g. System.out.println(Object) does, but you cannot reference a null value and call a method on it.
BTW There is a tricky situation where it appears you can call static methods on null values.
Thread t = null;
t.yield(); // Calls static method Thread.yield() so this runs fine.
This is by design. You can cast null to any reference type. Otherwise you wouldn't be able to assign it to reference variables.
Casting null values is required for following construct where a method is overloaded and if null is passed to these overloaded methods then the compiler does not know how to clear up the ambiguity hence we need to typecast null in these cases:
class A {
public void foo(Long l) {
// do something with l
}
public void foo(String s) {
// do something with s
}
}
new A().foo((String)null);
new A().foo((Long)null);
Otherwise you couldn't call the method you need.
Println(Object) uses String.valueOf()
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
Print(String) does null check.
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
Many answers here already mention
You can cast null to any reference type
and
If the argument is null, then a string equal to "null"
I wondered where that is specified and looked it up the Java Specification:
The null reference can always be assigned or cast to any reference type (§5.2, §5.3, §5.5).
If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).
As others have written, you can cast null to everything.
Normally, you wouldn't need that, you can write:
String nullString = null;
without putting the cast there.
But there are occasions where such casts make sense:
a) if you want to make sure that a specific method is called, like:
void foo(String bar) { ... }
void foo(Object bar) { ... }
then it would make a difference if you type
foo((String) null) vs. foo(null)
b) if you intend to use your IDE to generate code; for example I am typically writing unit tests like:
#Test(expected=NullPointerException.class)
public testCtorWithNullWhatever() {
new MyClassUnderTest((Whatever) null);
}
I am doing TDD; this means that the class "MyClassUnderTest" probably doesn't exist yet. By writing down that code, I can then use my IDE to first generate the new class; and to then generate a constructor accepting a "Whatever" argument "out of the box" - the IDE can figure from my test that the constructor should take exactly one argument of type Whatever.
This language feature is convenient in this situation.
public String getName() {
return (String) memberHashMap.get("Name");
}
If memberHashMap.get("Name") returns null, you'd still want the method above to return null without throwing an exception. No matter what the class is, null is null.
Print:
Print an object. The string produced by the String.valueOf(Object) method is translated into bytes
ValueOf:
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
It wil simply return a string with value "null" when the object is null.
This is very handy when using a method that would otherwise be ambiguous. For example: JDialog has constructors with the following signatures:
JDialog(Frame, String, boolean, GraphicsConfiguration)
JDialog(Dialog, String, boolean, GraphicsConfiguration)
I need to use this constructor, because I want to set the GraphicsConfiguration, but I have no parent for this dialog, so the first argument should be null. Using
JDialog(null, String, boolean, Graphicsconfiguration)
is ambiguous, so in this case I can narrow the call by casting null to one of the supported types:
JDialog((Frame) null, String, boolean, GraphicsConfiguration)

android-java: check boolean value checking for null

I am trying for null check like below
if (isTrue == null)
compile error says : "The operator == is undefined for the argument type(s) boolean"
Please help, how to do null check.
Thanks
You can't do null check on primitive types. boolean is a primitive type.
If you absolutely need to represent a null value with a boolean variable, you need to use the wrapper class java.lang.Boolean.
So, your example would be:
Boolean isTrue;
isTrue = null; // valid
isTrue = true; // valid
isTrue = false; // valid
if (isTrue == null) {
// valid!
}
Here's the WIKIPEDIA entry for primitive wrapper classes.
The right way is
boolean isTrue;
if(!isTrue)
or
if(isTrue)
You can not check if the boolean is null or not.boolean must be true or false.
A boolean is a primative type and cannot be null.
A boolean cannot be null in java.
A Boolean, however, can be null.

Categories