Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

println does not print the expected value

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?

like image 458
someone Avatar asked Dec 19 '12 07:12

someone


2 Answers

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));

like image 56
Ravi Avatar answered Sep 22 '22 23:09

Ravi


Try

System.out.println("This my first out put "+ (x==null?y:z));
like image 37
Evgeniy Dorofeev Avatar answered Sep 19 '22 23:09

Evgeniy Dorofeev