String is an Object. Why it is possible to initialize it the same way as primitive type: String str = "my string";
I was expecting to see initialization by using constructor only: new String("my string");
String is an Object. Why it is possible to initialize it the same way as primitive type: String str = "my string";
I was expecting to see initialization by using constructor only: new String("my string");
This is just a simplification provided by java. The other alternative would be enormous ugly. Your alternative solution has one simple logical mistake:
new String("my string");
Just aswell uses a string-literal as simply "my string"
. The real alternative would be
new String(new char[]{'m','y',' ',...,'n','g'});
Or just the same example using a byte[]
(deprecated), which would look even worse.
You can go to the javadocs:
Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.