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

jruizaranguren
  • 12,679
  • 7
  • 55
  • 73
Wild Goat
  • 3,509
  • 12
  • 46
  • 87

2 Answers2

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.

  • Thanks, so basically compiler converts that "my string" to char sequence for us? – Wild Goat Oct 05 '15 at 22:54
  • @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. – azurefrog Oct 05 '15 at 23:01
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.

Francisco Romero
  • 12,787
  • 22
  • 92
  • 167