Solved

String Pool and Immutability

Posted on 2004-04-26
11
361 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

 
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

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

705 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