-2

I have been given the following condition?

String A="a";
String B="b";
String c="a"+"b";

My question is is the String c created newly or is assigned from the string pool the value "a" and "b" and total how many strings are formed according to above question?

Phalguni Mukherjee
  • 623
  • 3
  • 11
  • 29
  • 2
    -1 : There are already so many answers about string pool that I wonder how you can ask this one, unless you haven't searched at all on SO. – Julien Mar 06 '14 at 16:10
  • Here is a possible duplicate: [string pool behavior](http://stackoverflow.com/questions/14490043/string-pool-behavior) – Joel Mar 06 '14 at 16:33
  • I know its their and even I read it several times, but was bit confused while going through one article – Phalguni Mukherjee Mar 06 '14 at 16:36

2 Answers2

3

Yes c is created newly. Strings in Java are effectively immutable (i.e. once created, they never change). One of the consequences of this is that, whenever you do a manipulation that changes a string, you get back a new, different object.

So in your example, 3 strings are created.

Community
  • 1
  • 1
Graham Griffiths
  • 2,196
  • 1
  • 12
  • 15
0

Take these two String objects:

String a = "a";
String b = "b";
String c = "a" + "b";
String d = "ab";

The compiler creates and pools three String objects. A line by line explanation follows.

  • Line 1: One String object is pooled for "a"
  • Line 2: One String object is pooled for "b"
  • Line 3: "a" + "b" is computer at compile time and treated as a literal. Therefore, one String object is pooled for "ab"
  • Line 4: "ab" is already in the pool

Following the same guidelines, your example produces 3 String objects.

Rainbolt
  • 3,542
  • 1
  • 20
  • 44