Click here to Skip to main content
15,897,187 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Java
String literal1 = "java"; 
String object = new String("java"); 
String literal2 = "java";

System.out.println("result 1 = " + (literal1 == object) ); 
System.out.println("result 2 = " + literal1.equals(object)); 
System.out.println("result 3 = " + literal1 == object); 
System.out.println("result 4 = " + literal1.equals(object));
System.out.println("result 5 = " + literal1 == literal2); 
System.out.println("result 6 = " + literal1.equals(literal2));


Expected output
result 1 = false
result 2 = true
result 3 = false
result 4 = true
result 5 = false
result 6 = true

output obtained
result 1 = false
result 2 = true
false
result 4 = true
false
result 6 = true

What I have tried:

Java
When this line
System.out.println("result 5 = " + literal1 == literal2);
is changed to
System.out.println("result 5 = " + (literal1 == literal2));


Output
result 5 = true
Could anyone please explain why this is happening?
Posted
Updated 14-Jul-18 13:16pm

The addition is happening first, so the result of the two strings concatenated (added together) is compared to the last value. The result printed will be false since the strings do not match. Adding the parentheses means that the equality test will be performed before its result is added to the literal string. Look up operator precedence in the Java documentation for full details.
 
Share this answer
 
)
System.out.println("result 1 = " + (literal1 == object) ); //adding paranthesis here basically forces Java to first execute literal1==object, which is true/false

System.out.println("result 2 = " + literal1.equals(object)); //it has pretty much the same effect as above, so literal.equals(object) gets executed first 

System.out.println("result 3 = " + literal1 == object); //in this case the String "result 3 =" is added with literal1 then an equality is made with "object", so obviously the output is slightly different

System.out.println("result 4 = " + literal1.equals(object)); // it`s the case of line 2, so self explanatory

System.out.println("result 5 = " + literal1 == literal2);  //it`s the case of line 3 of code

System.out.println("result 6 = " + literal1.equals(literal2)); //it`s the case of line 2 of code


The bottom line is:
1. If you have some function being called in JAVA, like literal1.equals(object), it will get executed first;
2. If you have a paranthesis expression like (expr), you will first execute that expression, then the rest;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900