Excuse me if this question is already asked or if its very old.
String is a Class. We are able to assign the value to String without creating new instance object.
like String someString = "Value";
How this is working without creating instance for String? Is it possible to create user defined class to assign values directly without creating new object?
See this interesting article:
String is Really Special
The designers of Java decided to retain primitive types in an object-oriented language, instead of making everything an object, so as to improve the performance of the language. Primitives are stored in the call stack, which require less storage spaces and are cheaper to manipulate. On the other hand, objects are stored in the program heap, which require complex memory management and more storage spaces. For performance reason, Java's String is designed to be in between a primitive and a class.
Also:
Java has provided a special mechanism for keeping the String literals - in a so-called string common pool..
When you do:
String myStr1 = "Hello";
String myStr2 = "Hello";
Then
myStr1 == myStr2 is true, because they're both stored in the pool (Read the article).
But if you construct a new String object:
String myStr1 = new String("Hello");
String myStr2 = new String("Hello");
Then the references are not equal.
I highly recommend to visit the JLS. It says that Strings are treated in a different way, just like that :)
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