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 conclusion:

 20 20 

But I expect this:

 This my first out put 10 This my second out put 20 

Can someone explain to me why I get "20" as the output for both println calls?

+7
source share
4 answers

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

("This my first out put "+x)==null?y:z , which will never be true. Thus, it will display the value of z .

For example:

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

In the above scenario, the operation is performed from left to right .

As you said, you expect this:

 This my first output 10 

To do this, you need to slightly modify the code. try it

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

+9
source

Try

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

use the following code, this will solve your problem: the problem is that its adoption is

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

how

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)); } 
+2
source

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)); 
+1
source

All Articles