简体   繁体   中英

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?

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

尝试

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

use following code this will solve your problem: The probelm is because its taking -

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

As

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

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

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM