7

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?

Ravi
  • 30,829
  • 42
  • 119
  • 173
someone
  • 6,577
  • 7
  • 37
  • 60
  • Sumit Singh's answer explains why the output is like it is. The reason is operator precedence, see [this document](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html) – jlordo Dec 19 '12 at 07:35

3 Answers3

9

System.out.println("This my first out put "+x==null?y:z); will be executed like

("This my first out put "+x)==null?y:z which is never going to be true. So, it will display z value.

For example:

int x=10;
int y=20;
System.out.println(" "+x+y); //display 1020
System.out.println(x+y+" "); //display 30

For above scenario, operation performed left to right.

As, you said, you are expecting this:

This my first output 10

For this, you need little change in your code. Try this

System.out.println("This my first output " + ((x == null) ? y : z));

Ravi
  • 30,829
  • 42
  • 119
  • 173
  • 1
    evaluation of expressions in Java is NOT always left to right. It takes account of operator precedence! – Stephen C Dec 19 '12 at 07:40
  • @StephenC i know, but i was talking for this scenario only. Rather, it will increase more confusion, i removed ALWAYS from my statement. I believe, now it will be OK. :) – Ravi Dec 19 '12 at 07:48
4

Try

System.out.println("This my first out put "+ (x==null?y:z));
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • 2
    This will indeed generate the desired output, but does not answer OPs question: _Could someone explain me **why** I'm getting "20" as output for both println calls?_ – jlordo Dec 19 '12 at 07:32
1

you need to try:

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));
vishal_aim
  • 7,636
  • 1
  • 20
  • 23