Solved

String Pool and Immutability

Posted on 2004-04-26
11
355 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 6

Author Comment

by:dharmesh_amity
Comment Utility
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
Comment Utility
>>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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 6

Author Comment

by:dharmesh_amity
Comment Utility
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
Comment Utility
>>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
Comment Utility
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
Comment Utility
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
Comment Utility
8-)
0
 

Expert Comment

by:Omindra
Comment Utility
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Fibonacci challenge 11 82
countAbc challenge 9 49
word0 challenge 4 52
wordmultiple challenge 12 89
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
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…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

743 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now