Comparison method | Contents |
---|---|
equals | Memory area comparison |
== | Value comparison |
public class MyApp {
public static void main(String[] args) {
String s1 = "ab"; //Store memory area
String s2 = "ab"; //Store memory area (same area as above)
if(s1.equals(s2)) { //Compare if the contents are the same
System.out.println("same1 equals");
}
if(s1 == s2) { //Comparison of basic data types
System.out.println("same2 ==");
}
//Generate string object (with equals method)
String ss1 = new String("ab"); //Storage of memory area
String ss2 = new String("ab"); //Storage of memory area (create another area from the above)
//Comparison of basic data types
if(ss1 == ss2) { //Since the memory area is being compared, it will be false and will not be executed.
System.out.println("same3 ==object");
}
//Comparison of data contents
if(ss1.equals(ss2)) {
System.out.println("same4 equals object"); //Executed because the memory area is different but the value is the same
}
}
}
same1 equals
same2 ==
same4 equals object
In the character string that is originally a reference type, the location of the memory area of the reference destination is stored in the variable.
And, in the example, the same character string ʻab` is assigned to s1 and s2, but the location of the memory area is entered in s1 and the same character string is assigned to s2, so the same memory It seems that the location of the area will be included. In other words
String s1 = "ab";
String s2 = s1;
Same meaning as? become.
When I try it
same1 equals
same2 ==
same4 equals object
String s1 = "ab";
String s2 = s1;
s2 = "cd";
What happens if you do ... Easy to understand
System.out.println("s1: " + s1);
System.out.println("s2: " + s2);
And run.
s1: ab
s2: cd
same4 equals object
Only s2 has been changed and is not reflected in s1.
Speaking of which, character strings behave in the same way as basic data types, and they behave in the same way as int types. .. ..
Does it mean that a new memory area is created when the value is updated with the same reference destination while the value is the same?
It's complicated, but I tried it and understood it again.
If it is an array, both values will be updated. Review Review!