+ 4

Why this codes outputs false?

String s = new String("Panda"); String a = "Panda"; System.out.print(s==a);

9th Jul 2017, 7:25 PM
Jatin Agarwal
Jatin Agarwal - avatar
6 Antworten
+ 7
the code is comparing 2 different objects and they have its own identity, you must use equals()
9th Jul 2017, 9:08 PM
Sergio Araya Villalobos
Sergio Araya Villalobos - avatar
+ 5
In Java == does not Check if a string is equal to another, but if the object is. to make the code work use System.out.println(s.equals(a)); .equals() checks if the content of two strings is the same :)
9th Jul 2017, 7:32 PM
Lukas Klose
Lukas Klose - avatar
+ 4
== does compare the reference, which is not the same as tue value which you want to compare.
9th Jul 2017, 7:35 PM
Lukas Klose
Lukas Klose - avatar
+ 3
/*This is what you want if you want to compare 2 strings or true/false*/ String s = "Panda"; String a = "Panda"; if(s == "Panda" || a == "Panda"){ System.out.println(s);} /*output panda*/ String s = "Panda"; String a = "Panda"; System.out.printlin(s==a); /*output true*/
10th Jul 2017, 12:01 AM
D_Stark
D_Stark - avatar
+ 3
public static void main(String[ ] args) { Animal a1 = new Animal("Robby"); Animal a2 = new Animal("Robby"); System.out.println(a1.equals(a2)); } //Outputs true
10th Jul 2017, 6:51 PM
Sergio Araya Villalobos
Sergio Araya Villalobos - avatar
+ 1
But I have instantiated both as "Panda".
9th Jul 2017, 7:34 PM
Jatin Agarwal
Jatin Agarwal - avatar