For Java beginners, instead of looking at the meaning of the equality operator (==) for String, "whether they are the same value" I think one of the points of learning is to see "whether the references are the same".
Test1.java
public static void main(String[] args) {
String str1 = "100";// ⓵
String str2 = new String("100"); // ⓶
System.out.println(str1 == str2); //Become False.
}
}
I understand that it will be false at this time. But String can be initialized with either ⓵ or ⓶. When will the references be the same? For example:
Test2.java
public static void main(String[] args) {
String str1 = "100";
String str2 = "100";
System.out.println(str1 == str2); //Become True.
}
}
In the above example, it will be True. Well, I thought that it would be false because I made two different reference type variables. It seems that str1 and str2 are looking at the same reference at this time because the equality operator is looking at "whether the reference is the same".
I was wondering what this meant. After going around, the following came out. Reference: Learn the impact on performance when using String # intern ()
The point is, in String, if there is an Intern () method, and if you use that, there is a String object with the same string, It seems that all the references are available. This will reduce wasted memory. It is inefficient to create objects one by one even though they have the same value.
Isn't this happening in Test2.java? That is, the Intern () method is automatically applied when initializing. That way, you won't waste memory. What happens in the following cases?
Test3.java
public static void main(String[] args) {
String str1 = new String("100");
String str2 = new String("100");
System.out.println(str1 == str2);
}
}
In this case it seems to be false. The thing is that when initializing with new ~~, the Intern () method is not applied and it is just called new, so it seems that you are creating a new object.
Summary, -If str1 = "100" and str2 = "100", the reference destination will be the same. -When initializing with new String ("100"), a new object is created, so the reference destination is different.
By the way, I also executed the following to find out whether this event occurs in the reference type or whether the String is special.
Test4.java
public static void main(String[] args) {
Integer int1 = 100;
Integer int2 = 100;
System.out.println(str1 == str2);
}
}
It was True. In the case of reference type, unless you write new, you can say that you are basically looking at the same reference point.
Recommended Posts