Comparison of strings to strings https://www.javadrive.jp/start/string/index4.html
[Introduction to Java] How to compare strings ("==" and "equals") https://www.sejuku.net/blog/14621
int num = 10
if (num == 10) {
System.out.println("num is 10.");
} else {
System.out.println("num is not 10.");
}
In this formula, 10 is stored in the variable num, so the processing result is
num is 10.
String str1 = "hoge"
String str2 = "hoge"
if (str1 == str2) {
System.out.println("str1 and str2 are the same.");
} else {
System.out.println("str1 and str2 are different.");
}
In this formula, the variable str1 and the variable str2 store the same character string hoge, so I thought that the processing result would be "str1 and str2 are the same."
str1 and str2 are different.
.. .. .. !? Hoge !? Why !? I got stuck in a pot here and debugged about 300 times.
Even if you compare with "==", it will be treated as a different character string. This is called a Java reference
When the character string is generated, a place (area) for storing the character string is secured in the memory. Hoge holds the reserved "place"
In other words, the value is not stored in a variable, but the mechanism is such that when you remember the location and use hoge, you follow that location and pull out the value.
Since there is a mechanism called this reference, when comparing with "==", it is not whether the values of the strings are the same, but whether the locations where the strings are stored in the memory are the same.
Returns true
if stored in the same memory area, otherwise false
In the previous formula, str1 and str2 are stored in different memory areas, so they return false
.
String str1 = "hoge"
String str2 = "hoge"
if (str1.equals(str2)) {
System.out.println("str1 and str2 are the same.");
} else {
System.out.println("str1 and str2 are different.");
}
Processing result
str1 and str2 are the same.
The expected result is returned.
By the way, if you write in ruby, the same result will be returned even with "=="
str1 = "hoge"
str2 = "hoge"
if str1 == str2 then
puts "str1 and str2 are the same."
else
puts "str1 and str2 are different."
end
# =>str1 and str2 are the same.
When using ruby or JavaScript, both numeric type
and string type
can be compared using "==", so I wrote the program in Java without a doubt, but Java is different.
I checked if there were enough grammatical mistakes to make holes in the screen, but be careful because if you do not know "reference", it will take extra time for me.
Recommended Posts