Why is a String class?

If it can only be started with

String s = "Hello"; 

then why is it a class? Where are the parameters?

+6
source share
5 answers

Given that String is such a useful and frequently used class, it has special syntax (via string literal representation: the text inside "" ) to create instances of it, but semantically these two are equivalent:

 String s = "Hello"; // just syntactic sugar String s = new String("Hello"); 

Behind the hood, both forms are not 100% equivalent, since the syntax using "" tries to reuse the rows from the Java string pool, while explicit instantiation with new String("") will always create a new object.

But make no mistake, neither the syntax will give a reference to an instance of the object, nor strings are considered primitive types in Java and are instances of the class, like any other.

+10
source
 String s = "Hello"; 

- it's just syntactic sugar. It is actually implemented as a reference type. (This is an immutable reference type, so you cannot change it)

+12
source

From Β§4.3.3 of the Java specification :

String literals are references to instances of the String class.

And from Β§3.10.5 :

A string literal is a reference to an instance of the String class

+7
source
 String s = "Hello"; 

The JVM views it as:

String s = new String("Hello"); and puts it in the String pool as a String literal.

+2
source

The string that you have in the example creates a String object. In the traditional sense that you are thinking about, there are no parameters.

0
source

Source: https://habr.com/ru/post/926892/


All Articles