• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Strings in Java

 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ! ") ;
 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Marshal
Posts: 79239
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic