-4

In this class how many objects will be created of the string?

public class B {

    public static void main(String[] args) {
        String string = new String("abc");
        String s = "def";
        s = s + "fgh";
    }
}
GameDroids
  • 5,584
  • 6
  • 40
  • 59
Darwin
  • 3
  • 6

1 Answers1

0

If you are asking about how many String objects are created, then the answer is 5 String objects.

String string = new String("abc"); // 2 Strings with value "abc" , one on heao and another in String constants pool
String s = "def"; // String "def" on String constants pool
s = s + "fgh"; // String "deffgh" on heap and "fgh" on String pool

Many objects are created internally, like StringBuilder, arrays etc you should not consider those now.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104