wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes String Initialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String Initialization" Watch "String Initialization" New topic
Author

String Initialization

James Gordon
Ranch Hand

Joined: Aug 09, 2002
Posts: 106
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

Joined: Aug 03, 2002
Posts: 7729
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 ]

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Wilfried LAURENT
Ranch Hand

Joined: Jul 13, 2001
Posts: 269
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

Joined: Aug 03, 2002
Posts: 7729
So, James, take your pick. I do like my references pointing somewhere, though.
-Barry
Chris Stewart
Ranch Hand

Joined: Sep 14, 2002
Posts: 184
I prefer to write it this way...
 
wood burning stoves
 
subject: String Initialization