• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

a question on creating string object.

 
Rahul Ba
Ranch Hand
Posts: 208
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 11096
13
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Search the forums. This question has been discussed before.
 
Sherif Shehab
Ranch Hand
Posts: 485
Android Eclipse IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maneesh Godbole wrote:Search the forums. This question has been discussed before.


Check THIS
 
Muhammad Khojaye
Ranch Hand
Posts: 449
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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("..")
 
Hunter McMillen
Ranch Hand
Posts: 492
Firefox Browser Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Spoor
Sheriff
Pie
Posts: 20613
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Hunter McMillen
Ranch Hand
Posts: 492
Firefox Browser Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic