| Author |
a question on creating string object.
|
Rahul Ba
Ranch Hand
Joined: Oct 01, 2008
Posts: 203
|
|
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: 8434
|
|
|
Search the forums. This question has been discussed before.
|
[Donate a pint, save a life!] [How to ask questions] [Onff-turn it on!]
|
 |
Sherif Shehab
Ranch Hand
Joined: Mar 05, 2007
Posts: 472
|
|
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: 341
|
|
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: 490
|
|
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: 24051
|
|
|
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: 19216
|
|
|
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
How To Ask Questions How To Answer Questions
|
 |
Hunter McMillen
Ranch Hand
Joined: Mar 13, 2009
Posts: 490
|
|
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
|
 |
 |
|
|
subject: a question on creating string object.
|
|
|