Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is String a class?

If it can be initiated with just

String s = "Hello";

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

like image 249
Luke Avatar asked Oct 03 '12 21:10

Luke


1 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.

like image 121
Óscar López Avatar answered Oct 07 '22 17:10

Óscar López