+ 10

Why output is false?

public class Program { public static void main(String[] args) { String s1="hello"; String s2=new String ("hello"); if(s1==s2) System.out.println ("true"); else System.out.println("false"); } }

22nd Aug 2017, 9:33 AM
Naila Rubab
Naila Rubab - avatar
6 Answers
+ 8
Thank you Serena and others🙃
22nd Aug 2017, 9:47 AM
Naila Rubab
Naila Rubab - avatar
+ 4
cause they are different objects i updated your code please check the link to see https://code.sololearn.com/c3gQ5wPQ9wja/?ref=app
22nd Aug 2017, 9:35 AM
Melih Melik Sonmez
Melih Melik Sonmez - avatar
+ 2
On that code, you are actually comparing two different variables that is why you get that 'false'. Instead use the equals method. like the syntax below if(s1.equals(s2)) { System.out.println("true"); } else { System.out.println("false"); }
22nd Aug 2017, 10:15 AM
Emmanuel Julius Samson
Emmanuel Julius Samson - avatar
+ 2
Nice and clear Serena Yvonne thanks!
18th Dec 2018, 9:12 AM
Atila Sabo
Atila Sabo - avatar
+ 1
great explanation @Serena Yvonne 🖒
22nd Aug 2017, 9:44 AM
Melih Melik Sonmez
Melih Melik Sonmez - avatar