Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator in System.out

Tags:

java

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");
like image 570
user2771655 Avatar asked Dec 04 '25 13:12

user2771655


2 Answers

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.

like image 168
Grzegorz Oledzki Avatar answered Dec 10 '25 10:12

Grzegorz Oledzki


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

like image 24
Maroun Avatar answered Dec 10 '25 09:12

Maroun