First of all, This is not an answer, this is the way to get answer by your self or explanation of situation.
Concatenation of two strings is always creating a new object?of the string.
To conform this thing you can do one thing that how it managed in memory heap and pool.
1: Go to the NetBeans:
2: Write program like this:
public class StringTest {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
String str3 = new String("HelloWorld");
String str4 = str1 + str2;
String str5 = str1 + str2;
String str6 = str1.concat(str2);
String str7 = "HelloWorld";
String str8 = "HelloWorld";
System.out.println("");
}
}
3: Just put a break point at System.out.println("");
this line.
4: Now debug this code.
5: Goto the Variable window (Window->Debugging->Variables), which looks like:
6: Now Right Click on str8
and select Mark Object... and give some tag to that object like Same Object
.
Now you can see that same tag line is also appear on str7
like:
Which shows that both references str7' and
str8` are refer same object.
7: Now check this thing for str3-4-5-6
all references by marking them with a different tag lines like:
And for further more internal management of that object just look into Show Refereances
option by right clicking on the variable name in variables windows like:
Update:
- Concatenation creates objects in the heap.
- To make sure this statement look which says that pool can not contain multiple string with the same value
- And here str7-8
are referred object from the pool which is different from the str4-5-6
as depicted in the screenshot of point 7.
- And you also can confirm it by comparing str5
to str7
by using ==
operator if it returns true
, the concatenation creates objects in pool because
str7
refer to the pool and both are referred the same object, but it will returns false because both are not same.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…