I wanted to ask what is different:
String name = "Mike";
from
String name = new String() ;
or

 String name = new String("Вася"); 

In 1 case, we create a variable and assign Mike . In the second case, we create an object and assign Вася value there, are these 2 declarations the same and we can either do it this way or that?

  • The first option is called a literal and it will fall into the string pool, and the second option will be stored in the heap. - aleshka-batman
  • And what about StringBuilder? - Sergey Gornostaev
  • @SergeyGornostaev I apologize, corrected - Petrovchenko Ivan

1 answer 1

In the first case, you declare a reference variable of string type and assign it a reference to a literal in the pool of constants. In the second case, you call the String constructor, passing it a reference to the literal, the constructor creates an object, initializes the field containing the character array in it, and copies the characters from the literal into this array. The reference returned by the constructor is assigned to the name variable. In both cases, the variable name is a string reference, but in the second virtual machine you will have to perform more operations and use more memory, since one instance of the string will be stored in the pool of constants, and the second in the heap.

  • This may not be the case. HotSpot interns strings, so the reference to the literal and the reference to the object will point to one element of the string pool. - Sergey Gornostaev