1

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.

trincot
  • 317,000
  • 35
  • 244
  • 286
Chamalee De Silva
  • 687
  • 1
  • 9
  • 28
  • If you're talking about Java, I believe that + operations in which both arguments are compile-time constants are resolved at compile time - so those concatenated Strings would end up in the String constant pool. In your example, the argument to the String constructor for c and the value for d will be the same constant in the constant pool. c, OTOH, will be a reference to a String allocated on the heap. – moilejter Sep 03 '18 at 06:52

1 Answers1

0

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:

  1. 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.
  2. 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!

Dhaval Simaria
  • 1,886
  • 3
  • 28
  • 36