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:
- If the second statement is executed after the first statement, no new String is created in String Pool as "A", "B" and "AB" are already present in the String Pool and can be reused using Interning.
- If the second statement is executed individually, then initially two Strings "A" and "B" are created in String Pool and then they are concatenated to form "AB" which is also stored in String Pool.
Hopefully this answers your question. Cheers!