As we know the following String is saved in the String Constant Pool.
String a = "AB";
The String objects created as below will be saved in Heap.
String b = new String("AB");
String e = b.concat("C");
At this time, Can anyone explain where the following Strings getting saved?
String c = new String("A"+ "B");
String d = "A" + "B";
Appreciate if you can clearly explain with reasons.
Before proceeding to your target statements, one minor correction to your question.
String b = new String("AB");
String e = b.concat("C");
Above statements will create a String object in Heap as well as in String Pool for further references.
Now your first question statement:
String c = new String("A"+ "B");
Here, first two Strings, "A" and "B", are created in String Pool and are concatenated to form "AB" which is also stored in String Pool. --->Point-I
Then new String(dataString)
constructor is called with "AB" as the parameter. This will create one String in Heap and one in String Pool, both having value as "AB". --->Point-II
String "AB" created in String Pool at Point-I and II are equal
but not the same
.
Now your second question statement:
String d = "A" + "B";
Here there are two cases:
Hopefully this answers your question. Cheers!