If it can be initiated with just
String s = "Hello";
then why is it a class? Where's the parameters?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With