When storing a character string value in a Sting type variable, the judgment result differs between String.equals
and==
due to the difference in writing style. Note so don't forget.
--How to write using new
equals
-> true==
-> false
--Easy writingequals
-> true==
-> trueIn general, the same writing method as when creating an object
String str = new String("String");
This will compare the variables that store the values. (Is this the right way to use the word "store"?)
Main.java
//Create object
String cat1 = new String("Marble");
String cat2 = new String("Marble");
//Equivalence judgment and equal value judgment
System.out.println(cat1.equals(cat2));
System.out.println(cat1 == cat2);
Output result.
true
false
The same writing style as when storing a value in the basic data type
String str = "String";
This will compare the variables.
Main.java
//Store value in variable
String cat3 = "Mike";
String cat4 = "Mike";
//Equivalence judgment and equal value judgment
System.out.println(cat3.equals(cat4));
System.out.println(cat3 == cat4);
Output result.
true
true
After all, if you use the ==
operator to compare strings, the judgment result will be different, so be careful.
Recommended Posts