-2

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");

1
  • This may also be useful. Commented Oct 5, 2015 at 22:57

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, so basically compiler converts that "my string" to char sequence for us?
@WildGoat There's no conversion required, a String literally IS a CharSequence in Java, since that's one of the interfaces the String class implements.
0

You can go to the javadocs:

Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.