0
String a = "Hello";
String b = new String("Hello World");

Can someone please tell me how many objects are created and elaborate.

Thank you.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
ea33162
  • 19
  • 2

1 Answers1

0

String greeting = "Hello world!";
In this case, "Hello world!" is a string literal—a series of characters in your code that is enclosed in double quotes. Whenever it encounters a string literal in your code, the compiler creates a String object with its value—in this case, Hello world!.

String a = "Hello"; // 1 object
String b = new String("Hello World"); 
// 1 object with new String(), 
// 1 object with "Hello World"

in total you created 3 objecs.

Salih Erikci
  • 5,076
  • 12
  • 39
  • 69
  • There are more than just 3 objects: String pool (1 object), `String.class` (1 object), the backing `char[]` for each `String` (since an array in Java is an object, 3 more objects), and on... – Luiggi Mendoza Dec 18 '14 at 22:14