• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

What's the difference

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the difference in the following lines of code?
String myString = new String() ;
and
String myString = "" ;
-Don
 
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nothing really, both lines give an empty line of text.
 
Ranch Hand
Posts: 193
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is one difference. Try running this:

S1 and S2 reference the same String object, S3 is a different String object.
 
High Plains Drifter
Posts: 7292
Netbeans IDE VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's no apparent difference to the user in sample output, but internally there are a couple of things worth noticing. Graeme is probably trying to get you thinking about those differences with his example; it's a simple illustration, but you read the results closely; you'll have some questions!
String is a rare class in Java. It's allowed to straddle the line between behaving as an object (using new() ) and behaving as a primitive (using direct assignment). The designers knew String objects would be promiment in almost any program. To conserve the run-time cost of creating them, they chose to allow static String assignments. Static assignments are "paid for" at compilation time, where they can be less of a burden.
When you allocate space for a String using new, that object goes to the heap and is garbage-collectible once it's fully dereferenced. A static String remains in program memory no matter what. Even if you completely dereference it, it's there and will get used again if you re-assign its value. Honest!
-----------------
Michael Ernest, co-author of: The Complete Java 2 Certification Study Guide
[This message has been edited by Michael Ernest (edited January 10, 2001).]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!