Solved

String Pool and Immutability

Posted on 2004-04-26
11
360 Views
Last Modified: 2010-03-31
Hi every1.

I am learning Java String. I have two questions. the question is relevant to following code.

Q1.
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");

Now when I do s1==s2 the result is true. That's fine as I expected as they are pointing to the same literals.

But if I do s1==s3 the result is false. Why? I tought that for string class if you have String s1=""; and using String s = new String(""); are same its just which style you prefer. But now I think they are different.

Can  someone please tell me what is going on here.

Q2.
As I read, String pool is not garbage collected. So I thought maybe I can make my system to run out of memory. So I wrote a small program which keeps generating distinct string at run time. So as I think all these strings must be stored in the pool and never get garbage collect. But my system never went out of memory. I am running this program for more than two hours now. Why is that? Is the pool garbage collected?

Thank you,
Dharmesh
0
Comment
Question by:dharmesh_amity
  • 4
  • 4
  • 2
  • +1
11 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 10920900
Q1
>>But now I think they are different

They are. Using new String allocates a new Stirng object on the heap. The reference will be different to the first one, hence the comparison failure.

Q2 Maybe you've got a lot of memory? ;-) Seriously it depends on how you're doing it. Use new as above and you should  run out of memory eventually

0
 
LVL 24

Expert Comment

by:sciuriware
ID: 10920956
Q2: tha garbage collector can not collect what is not garbage: what's in the pool is available for the rest
of your program and is not garbage!

;JOOP!
0
 
LVL 6

Author Comment

by:dharmesh_amity
ID: 10920990
I think I should not have so much memory for running the program for more have two hours. I have tried to create new object before and system will go out of memory after smetime usally in just a few minutes.

I also think that new is different, but I want to know what exactly is going under the hood.

Thank for your response.
Dharmesh
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 6

Author Comment

by:dharmesh_amity
ID: 10921011
To sciuriware,

But my program is pointing to only one string at any given time. But I have created many strings at runtime and string pool is not garbage collected. So does this mean if I create new strings at runtime they are not allocated in the string pool?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10921045
>>Use new as above and you should  run out of memory eventually

Actually if the VM is well tuned, it may well be difficult to bring this about even if you try as garbage collection may well keep up with you enough. Setting the thread priority to as high as possible should help though ;-)
0
 
LVL 6

Author Comment

by:dharmesh_amity
ID: 10921082
I understand that the garbage collector is keeping up. But my question is when I create new strings at runtime where is new string stored are they stored in string pool? and if it is stored in string pool then my system should run out of memory.

0
 
LVL 86

Accepted Solution

by:
CEHJ earned 125 total points
ID: 10921159
>>But my question is when I create new strings at runtime where is new string stored

I answered that above:

>>Using new String allocates a new String object on the heap

(correcting the typo). Then the gc comes along and gc's the heap

0
 
LVL 24

Expert Comment

by:sciuriware
ID: 10921204
The pool can't be garbage collected as those Strings (and other things) must remain available.

But now, why are you so worried? Those few Strings of you will not blow your computer.
SWING for example will need much more memory.

At the moment I run an application that uses 520 Mb and it's certainly not the Strings that make it up.

;JOOP!
0
 
LVL 6

Author Comment

by:dharmesh_amity
ID: 10921558
I am worried because I want to understand the concepts. My objective is not to blow my computer. But I want to know because if you know when your computer blows, you can write much efficient and less error prone programs.

And I really think that the computer should run out of memory when I am creating so many string.

Dharmesh
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10921606
8-)
0
 

Expert Comment

by:Omindra
ID: 11201270
class Comp
{
      public static void main(String[] args)
      {
            String s = "Hello";  
            String s2 = "Hello";

            if (s==s2)
            {  
                  System.out.println("Equal without new operator ==");  
            }  
                          if (s.equals(s2))
            {  
                  System.out.println("Equal without new operator equal method");  
            }  
                         
            String t = new String("Hello");  
            String u = new String("Hello");

            if (t==u)
            {  
                  System.out.println("Equal with new operator==");  
            }
                          if (t.equals(u))
            {  
                  System.out.println("Equal with new operator equal method");  
            }
                         
      }
}  
Answer:
      Equal without new operator ==
      Equal without new operator equal method
      Equal with new operator equal method

State:
1. Because of the way Java conserves resources by re-using identical strings that are created without the new             operator s and s2 have the same "address" and the code does output the string
2. The == operator  check object's contents, not reference.
3. The creation of two strings with the same sequence of letters without the use of the new keyword will create          references to the same String in the Java String pool. The String pool is Java's way of conserving resources.
0

Featured Post

Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Java exception bubble up 2 24
Java syntax, or is it Selenium 6 43
Java program running SQL query 5 50
running on tomcat not jboss eap 7.0 3 33
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question