I found below sysout in our project and it is always printing 'Not Null'. Even I have initialize the Val variable or not, it is printing 'Not Null'.
Also why it is not printing the "mylog" in front? Can someone explain?
String Val = null;
System.out.println("mylog : " + Val!=null ? "Not Null" :"Is Null");
Use paranthesis:
System.out.println("mylog : " + (Val!=null ? "Not Null" :"Is Null"));
Otherwise it gets interpreted as:
whatToCheck = "mylog: " + val
System.out.println(whatToCheck !=null ? "Not Null" : "Is Null"
which evaluates to something like "mylog: null" or "mylog: abc". And that is always a non-null String.
"mylog : " + Val!=null
will be evaluated to
"mylog : null"
which is not null.
Parenthesis for the rescue.
Why is null converted to the String "null"? See the JLS - 15.18.1.1 String Conversion:
... If the reference is
null, it is converted to the string"null"
Also it's very important to understand that this is happening because of Java operator precedence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With