aspose file tools*
The moose likes Beginning Java and the fly likes when to use string literal and String New Object ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "when to use string literal and String New Object ?" Watch "when to use string literal and String New Object ?" New topic
Author

when to use string literal and String New Object ?

Prabhat Ranjan
Ranch Hand

Joined: Oct 04, 2006
Posts: 391
Hi,

As we know string has 2 ways to create objects using literal.

using literals is better , as its creates only one ref variable and assigned it to the String pool.

String str1 = "Prabhat"; // 1 ref variable

String str1 = new String("Prabhat"); // 2 String Object and 1 reference variable

so which one the better to use and when & why ?


ashwin bhawsar
Ranch Hand

Joined: Mar 16, 2011
Posts: 62

Both have their own trade-offs:

If you create a string using String literals , the string stays in the string-pool forever. It is never garbage collected.
The down side of this is that the string-pool has a fixed size and it will get full at sometime.

With 'new' operator new strings objects are created out of the string-pool, and they are eligible for garbage-collection. So if you don't need them anymore you can make the eligible for garbage collection, but the down side of this is that with 'new' operator JVM will always have to create a new object and it is an overload for JVM.

So if i know that my application is going to use some fixed number of string values , i will use string literals for better performance. But if my application will need different string at different times i will use 'new' operator to create them.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14351
    
  22

There is never a good reason to use version #2 - create a new String explicitly with a string literal as the argument.

The constructor of class String that takes another String is useful in some special cases, but not when passing a string literal.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Jesper de Jong wrote:
The constructor of class String that takes another String is useful in some special cases

just curiosity , can you please tell me the special cases ?
Shanky Sohar
Ranch Hand

Joined: Mar 17, 2010
Posts: 1051

I have never seen in code where we are using version 2 to create a string object..


SCJP6.0,My blog Ranchers from Delhi
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14351
    
  22

Ok, here is an example. Note that this is a bit advanced - you have to know something about the inner workings of class String to understand this.

A String objects stores its data in a character array. When you take a substring of a string, by calling the substring() method, then the new String object that is created does not copy part of the data of the original string. Instead, it stores a reference to the underlying data of the original string, along with an offset and length to indicate what part of the old string the new String object represents.

When you have a very long string (for example you read the contents of a file into a String object) and you take a substring out of it, then the JVM will retain all the data of the original string in memory - even if you discard the original String object, because the String object created with substring() still holds a reference to the whole character array with all the data.

To prevent this memory inefficiency, you can explicitly create a new String object using the substring object. That second new String object will copy the data from the substring object, but just the part that you need.

If you want to see how exactly it works, then have a look at the source code of class String, which you can find in the file src.zip in your JDK installation directory.
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

the information you have given is really helpful. thank you Jesper
Prabhat Ranjan
Ranch Hand

Joined: Oct 04, 2006
Posts: 391
thanks everyone for your reply on this topic.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11480
    
  16

ashwin bhawsar wrote:With 'new' operator new strings objects are created out of the string-pool, and they are eligible for garbage-collection. So if you don't need them anymore you can make the eligible for garbage collection, but the down side of this is that with 'new' operator JVM will always have to create a new object and it is an overload for JVM.

The OP was asking about when to use this:

When you do it this way, you get BOTH the literal in the String pool AND the object created on the heap, so this is actually worse.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Abhishk Gupta
Greenhorn

Joined: Oct 08, 2008
Posts: 22
Jesper de Jong wrote:
When you have a very long string (for example you read the contents of a file into a String object) and you take a substring out of it, then the JVM will retain all the data of the original string in memory - even if you discard the original String object, because the String object created with substring() still holds a reference to the whole character array with all the data.


Nice explanation jasper. But I do have a doubt. Would not JVM retain all data once is invoked.
IMO, Above creates a new String instance but the older one will still resides in the memory.

Let me know if I got it wrong.


There are only 10 types of people in the world: those who understand ternary, those who don't, and those who mistake it for binary.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11480
    
  16

I think what was not stated in Jasper example was that largeString could then be set to null (or fall out of scope), and then could be reclaimed by the garbage collector.

if you do this:

String sub = largeString.substring(80, 100);

even if you then set largeString to null, the sub refers to a spot in that object, so the whole thing cannot be reclaimed.
Piyush Joshi
Ranch Hand

Joined: Jun 10, 2011
Posts: 207

Firstly thanks to all for an in-depth discussion.

Jesper de Jong wrote:
If you want to see how exactly it works, then have a look at the source code of class String, which you can find in the file src.zip in your JDK installation directory.

As suggested by Jesper I was going through the source code of String class.

I have some doubts:

1. Am I getting it right that a native method intern() is called when we use a literal to initialize a String reference.

2. Javadocs for intern() method says : A pool of strings, initially empty, is maintained privately by the class String.
What does "privately" mean here? Is this pool maintained in native code?


Piyush
Prabhat Ranjan
Ranch Hand

Joined: Oct 04, 2006
Posts: 391
As per my knowledge intern() is used when you want to force the JVM for String str = new String("xyz");

str.intern(); // in this statement JVM forces first to search any string literal is there in internal pool or not, if it there then it will point to that pool string literal and will not create new Object of String, if not found then it will create new Object of String.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3649
    
  17

Piyush Joshi wrote:1. Am I getting it right that a native method intern() is called when we use a literal to initialize a String reference.

This native method is called whenever a String literal is encountered.

2. Javadocs for intern() method says : A pool of strings, initially empty, is maintained privately by the class String.
What does "privately" mean here? Is this pool maintained in native code?

No, it really just means private. The String class keeps a private collection of Strings to keep track of which have been interned.
Piyush Joshi
Ranch Hand

Joined: Jun 10, 2011
Posts: 207

Stephan van Hulst wrote:
2. Javadocs for intern() method says : A pool of strings, initially empty, is maintained privately by the class String.
What does "privately" mean here? Is this pool maintained in native code?

No, it really just means private. The String class keeps a private collection of Strings to keep track of which have been interned.


I asked this question because I could not find any private field which keeps collection of Strings.

All the private fields of String class are :

value:char[]
offset:int
count:int
hash:int
serialVersionUID:long
serialPersistentFields: ObjectStreamField[]


Is there anything I am missing here?
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3649
    
  17

It's created natively, so the declaration would probably be in some C or C++ code.
Piyush Joshi
Ranch Hand

Joined: Jun 10, 2011
Posts: 207

Thanks Stephan for quick replies.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: when to use string literal and String New Object ?