Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String

 
manish panchal
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello Sir

My question is "how many objects are made after String1 s="abc" and String2 s=new String("abc");"
I have also read kaithy seira but I couldnt understand...
I know When the
compiler encounters a String literal, it checks the pool to see if an identical String
already exists. If a match is found, the reference to the new literal is directed to the
existing String, and no new String literal object is created.
Is it for only literals or for both when using new keword
I mean if i made a String using literal and new keyword with same string than how many objects are created.


thanks
 
Ankit Dan
Ranch Hand
Posts: 47
Eclipse IDE Java MyEclipse IDE
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I ll keep it simple..
Using a constructor always creates a brand new object i.e. using a constructor does not intern the string


so..you have two distinct objects

there is an error in your declaration statement
it should be


i hope this was helpful!!
 
Harsha Ka
Ranch Hand
Posts: 45
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yup.. As mentioned in the above post, two distinct objects will exist. But its recommended not to create Strings with "new" constructor, as its better to reuse the "pool" of string if it exists so as to reduce the memory consumption.
 
Winston Gutkowski
Bartender
Pie
Posts: 10527
64
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Harsha Ka wrote:Yup.. As mentioned in the above post, two distinct objects will exist. But its recommended not to create Strings with "new" constructor, as its better to reuse the "pool" of string if it exists so as to reduce the memory consumption.

That's true, and my suggestion is to use String.valueOf(String). In fact, I'd suggest that you always use a static factory method to construct objects if one is available.

However, the chances of using new causing problems are probably exaggerated. You'd have to be creating many thousands of Strings before it's likely to become an issue; so it's far less likely to cause you problems than using str1 == str2 incorrectly even once.

Look out for my new page on this very subject in the near future.

Winston
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic