File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Strings in Java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Strings in Java" Watch "Strings in Java" New topic
Author

Strings in Java

Chris Wox
Ranch Hand

Joined: May 25, 2006
Posts: 34
String one = 'Hello World ! ";
String two = 'Hello World ! ";

Can someone plz explain how many string objects will Java create in the above exampple.
Jaime M. Tovar
Ranch Hand

Joined: Mar 28, 2005
Posts: 133
In a standalone local application there will only be one �Hello world �� in the VM (at least in a Sun VM, other implementations may vary). Both objects will be referencing the same memory space, as a way of work saving mechanism.

To verify this you can run a
If (one == two)
Test. This will give you true because they point to the same reference.

The string will be immutable. If you create a new String that varies even by a space in the middle a new string will be created in memory.


She will remember your heart when men are fairy tales in books written by rabbits.<br /> As long as there is duct tape... there is also hope.
Chris Wox
Ranch Hand

Joined: May 25, 2006
Posts: 34
thanks.
and how many strings will be created if i change to this ?

String one = 'Hello World ! ";
String two = new String ('Hello World ! ") ;
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
String one = 'Hello World ! "; //Create in String Pool
String two = new String ('Hello World ! ") ; //Create in Heap.

Two String Objects.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40034
    
  28
You should be testing this sort of thing rather than asking about it.
String one = 'Hello World ! ";
String two = 'Hello World ! ";
OR
String one = 'Hello World ! ";
String two = new String ('Hello World ! ") ;



Apart from the fact that your code will only compile if you change the ' to ", you will see for yourself. You learn so much more by trying out code for yourself. Even apparently trivial little bits of code which run in three lines teach you something.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Strings in Java