If it can be initiated with just

String s = "Hello"; 

then why is it a class? Where's the parameters?

6

5 Answers

Given that String is such a useful and frequently used class, it has a special syntax (via a string literal representation: the text inside "") for creating its instances, 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, as the syntax using "" tries to reuse strings from Java's string pool, whereas the explicit instantiation with new String("") will always create a new object.

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

0
String s = "Hello"; 

is just syntactical sugar. It's actually implemented as a reference type. (It's an immutable reference type, so you can't change it)

From the §4.3.3 of the Java Specification:

String literals are references to instances of class String.

And from §3.10.5:

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

String s = "Hello"; 

JVM treats it as:

String s = new String("Hello"); and interns it to String pool as String literal.

7

The line you have in the example is creating a String object. There aren't any parameters in the traditional sense that you are thinking of.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy