aspose file tools*
The moose likes Beginning Java and the fly likes String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String" Watch "String" New topic
Author

String

manish panchal
Greenhorn

Joined: May 10, 2012
Posts: 2
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

Joined: Aug 31, 2012
Posts: 47

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

Joined: Mar 14, 2010
Posts: 45

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.


SCJP 1.6,Preparing (Tryin to prepare) for scwcd
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7795
    
  21

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


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: String