Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

New String

 
Srinivas Katta
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

What is the difference between String a="a" and String a=new("a")?

Can anybody explain thsi diagrammatically for better understanding

Thanks
Srinivas
 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


In both cases the literal value "a" is a compile-time constant that will end up in the String contant pool.
At runtime the former will always refer to the String object in the constant pool, so you don't end up with lots of String objects that represent the same value.
The latter will always create a new String object with value "a", which is not as efficient and nearly always unneccesary.
Unless you have a good reason to worry about the efficiency of sharing the backing - potentially huge - char[] array with String's returned by invocations of the substring() method.
But that's a rare case.
 
Ninad Kuchekar
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Srinivas,

I guess this might help you.

-Ninad
 
Hebert Coelho
Ranch Hand
Posts: 754
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Strings got their own pool. If you do String name = "a"; The JVM will look at the pool for someone just like that, and will point your name object to the "a" String in the pool.

If you do new String("A"); you will be creating a new object.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49782
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please search; this question is asked about once every two weeks.
 
Muhammad Khojaye
Ranch Hand
Posts: 449
IntelliJ IDE Java Scala
 
Ram Narayan.M
Ranch Hand
Posts: 247
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a very very very famous query being asked in this forum...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic