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

a question on creating string object.

Rahul Ba
Ranch Hand

Joined: Oct 01, 2008
Posts: 205

I read in the book that

String str = new String("abc");

creates two objects and one reference variable. My question is how is that two object..Can anybody explain me?

Thanks in advance,
Rahul
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10519
    
    9

Search the forums. This question has been discussed before.


[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Sherif Shehab
Ranch Hand

Joined: Mar 05, 2007
Posts: 483

Maneesh Godbole wrote:Search the forums. This question has been discussed before.


Check THIS


Thanks,
Sherif
Muhammad Khojaye
Ranch Hand

Joined: Apr 12, 2009
Posts: 449

Two string objects would be there, one in the pool, and one on the heap as well. Here you are explicitly creating a new String object that copies its contents from the string exist in the string pool.

bottom-line : never use new String("..")


http://muhammadkhojaye.blogspot.com/
Hunter McMillen
Ranch Hand

Joined: Mar 13, 2009
Posts: 492

bottom-line : never use new String("..")


I was always taught to use the new keyword to copy existing information into new objects, something called a deep copy. Is this a bad practice?

-Hunter


"If the facts don't fit the theory, get new facts" --Albert Einstein
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

String objects in Java are immutable (there's no way to change the contents of a String, by design) and therefore they never need to be copied.


[Jess in Action][AskingGoodQuestions]
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19760
    
  20

Normally not, but classes like String and the primitive wrappers (Integer, Boolean, etc) are immutable. That means that once created they can never change. It is therefore safe to share them among multiple objects, methods and threads without any problems.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Hunter McMillen
Ranch Hand

Joined: Mar 13, 2009
Posts: 492

Oh. Well thanks for clarifying that, this deep copy technique I was shown must be leftover from a language where they weren't immutable.

Thanks,
Hunter
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: a question on creating string object.