• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Initialization

 
James Gordon
Ranch Hand
Posts: 108
  • 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.
 
Barry Gaunt
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 ]
 
Wilfried LAURENT
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
 
Chris Stewart
Ranch Hand
Posts: 184
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I prefer to write it this way...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic