• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Strings in Java

 
Chris Wox
Ranch Hand
Posts: 34
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 133
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Chris Wox
Ranch Hand
Posts: 34
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2023
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String one = 'Hello World ! "; //Create in String Pool
String two = new String ('Hello World ! ") ; //Create in Heap.

Two String Objects.
 
Campbell Ritchie
Sheriff
Pie
Posts: 47300
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic