1

how many String objects are created in the declaration String s="Sachin"+" Tendulkar"; ? This is my interview question

Nambi
  • 11,944
  • 3
  • 37
  • 49

3 Answers3

1
how many String objects are created in the above declaration? 
This is my interview question
  • "Sachin" -> String literal

  • "Tendulkar" -> String literal

only one String s is created from concatenation of the two literals

Nambi
  • 11,944
  • 3
  • 37
  • 49
1
Strings computed by constant expressions are computed at compile time and then
treated as if they were literals. 

Specs : here

String s="Sachin"+" Tendulkar";

So in the case you have specified only one String literal will be created(created at compile time itself) and that is "SachinTendulkar". So there will be only one interned String in the String pool.

In case you try to concatenate separate explicit literals then only you will have separate interned Objects in the String pool. Eg.

String s1 = "Sachin";
String s2 = "Tendulkar";
String s3 = s1 + s2;

In above case you will have 3 different interned Objects in String pool.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
  • Little clarification. In last case you will have only 2 different interned Objects(s1,s2) in String pool and 1 object in heap (s3) because concatenation of variables is executed using StringBuilder.append followed by StringBuider.toString that internally uses new String() – Sergey Kurtenko Jul 06 '14 at 01:13
1

Only One for String s=“Sachin”+“ Tendulkar”;

Kick
  • 4,823
  • 3
  • 22
  • 29