Frage

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?

War es hilfreich?

Lösung

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.

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top