-2

I know when we use String s = new String("abc"); JVM will create the object in heap and when we use String s = "abc"; the object gets created in String constant pool.

IMO, using String s = "abc"; serves our purpose. In which case we have to go for new String("abc");

chandu
  • 223
  • 1
  • 6
  • 13

1 Answers1

2

It is never necessary to create a new String object from a string literal - in fact, it is unnecessarily inefficient.

String objects are immutable, so you never have to make a defensive copy of a String object.

Jesper
  • 202,709
  • 46
  • 318
  • 350
  • I can think of a few odd corner cases where you do want different instances of the same string... – assylias Jul 07 '16 at 14:07
  • @assylias please expand :) – Andy Turner Jul 07 '16 at 14:08
  • @AndyTurner say you send a query to a rest WS and the query params need to be stored in a map because a badly written API forces you to, and you want to send a list (server/ws?abc=1&abc=2&abc=3), you can build an IdentityHashMap and `map.put(new String("abc"), 1); map.put(new String("abc"), 2); etc.`. I insist on the "odd" bit of my initial comment. And actually I don't have another case in mind... ;-) – assylias Jul 07 '16 at 14:11
  • @AndyTurner It was also useful on older JVM when using substring to avoid keeping reference to the original string. Not the case since Java 7u6. http://stackoverflow.com/questions/27632533/is-it-redundant-to-create-a-new-string-for-a-substring-of-another-string – assylias Jul 07 '16 at 14:24
  • @assylias but that isn't really relevant when creating `String` objects from a **literal**. – Jesper Jul 07 '16 at 14:25
  • @assylias thanks. I agree with the oddness caveat... – Andy Turner Jul 07 '16 at 14:29