This is my code:
public static void main(String[] arg)
{
String x = null;
String y = "10";
String z = "20";
System.out.println("This my first out put "+x==null?y:z);
x = "15";
System.out.println("This my second out put "+x==null?y:z);
}
My output is:
20
20
But I’m expecting this:
This my first out put 10
This my second out put 20
Could someone explain me why I’m getting “20” as output for both println calls?
System.out.println("This my first out put "+x==null?y:z);will be executed like("This my first out put "+x)==null?y:zwhich is never going to be true. So, it will displayzvalue.For example:
For above scenario, operation performed left to right.
As, you said, you are expecting this:
For this, you need little change in your code. Try this
System.out.println("This my first output " + ((x == null) ? y : z));