This week's book giveaway is in the Cloud/Virtualization forum.
We're giving away four copies of Learning OpenStack Networking: Build a solid foundation in virtual networking technologies for OpenStack-based clouds and have James Denton on-line!
See this thread for details.
Win a copy of Learning OpenStack Networking: Build a solid foundation in virtual networking technologies for OpenStack-based clouds this week in the Cloud/Virtualization forum!
  • 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:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

String Initialization  RSS feed

 
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am just wondering which is the proper/recommended way to initialize a String variable.
String str = "" or
String str = null

Thanks in advance.
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String str = ""; // in this case str references a String instance, albeit an empty string instance.
String str = null; // str does not refer to a String instance.
In my opinion the former is more "correct" than the latter. But it all depends on the conventions agreed upon by the rest of your program.
-Barry
[ September 29, 2002: Message edited by: Barry Gaunt ]
 
Ranch Hand
Posts: 269
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In my opinion, it is useless to declare a String as
String str="";
What you are doing is allocating a useless String object. Strings are immutable objects. So what will happen next is that you will recreate another String while writing
str="Toto". The use of "" is however optimized since it belongs to the String pool.
If you need to know if your String has been allocated before then a simple test (str==null) is better than str.equals("") (the latter being worse worse than str.length()==0).
W.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So, James, take your pick. I do like my references pointing somewhere, though.
-Barry
 
Ranch Hand
Posts: 184
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I prefer to write it this way...
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!