Can any body explain output to the following piece of code in decription | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Can any body explain output to the following piece of code in decription

if("String".toString() == "String") System.out.priqntln("Equal"); else System.out.println("Not Equal");

15th Mar 2017, 8:20 PM
Sagar Maharana
Sagar Maharana - avatar
2 Answers
+ 7
When talking about objects (which a String is) == compares the reference. If "String" has the same reference as "String" then output: Equal. else Not Equal. [toString does not change the reference]. Consider using .equals to compare strings, as it checks character by character to see if they're indeed the same. Lets say I had: String first = "String"; String second = new String("String"); if(first == second) System.out.println("Equal"); else System.out.println("Not Equal"); The output is: Not Equal. While if I had: if(first.equals(second)) The output would be: Equal.
15th Mar 2017, 10:46 PM
Rrestoring faith
Rrestoring faith - avatar
+ 1
you are giving a conditional statement: if the string value "String" is .toString-ed and is equal to "String", then output should be Equal. else it will output Not Equal.
15th Mar 2017, 9:22 PM
Yahaya Muhammed
Yahaya Muhammed - avatar