aspose file tools*
The moose likes Java in General and the fly likes New String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "New String" Watch "New String" New topic
Author

New String

Srinivas Katta
Ranch Hand

Joined: Feb 01, 2007
Posts: 76
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

Joined: Mar 10, 2008
Posts: 1836
    
    7



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.

Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Ninad Kuchekar
Ranch Hand

Joined: Jan 05, 2010
Posts: 64
Hi Srinivas,

I guess this might help you.

-Ninad


Don't walk as if you rule the world, walk as if you don't care who rules it...
Hebert Coelho
Ranch Hand

Joined: Jul 14, 2010
Posts: 754

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.


[uaiHebert.com] [Full WebApplication JSF EJB JPA JAAS with source code to download] One Table Per SubClass [Web/JSF]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40061
    
  28
Please search; this question is asked about once every two weeks.
Muhammad Khojaye
Ranch Hand

Joined: Apr 12, 2009
Posts: 449

Strings Literally


http://muhammadkhojaye.blogspot.com/
Ram Narayan.M
Ranch Hand

Joined: Jul 11, 2010
Posts: 247

This is a very very very famous query being asked in this forum...


SCJP 6 [SCJP - Old is Gold]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: New String