+ 4
Why this codes outputs false?
String s = new String("Panda"); String a = "Panda"; System.out.print(s==a);
6 Antworten
+ 7
the code is comparing 2 different objects and they have its own identity, you must use equals()
+ 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 :)
+ 4
== does compare the reference, which is not the same as tue value which you want to compare.
+ 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*/
+ 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
+ 1
But I have instantiated both as "Panda".