What is the best practice to use string variable in java? Does it have to be declared and initialized before use/manipulating it.
eg:
String thisString; // is this best practice
String thatString =""; // or is this best practice
What is the best practice to use string variable in java? Does it have to be declared and initialized before use/manipulating it.
eg:
String thisString; // is this best practice
String thatString =""; // or is this best practice
Afaik there is no strong convention here. I would prefer to initialize a string variable on declaration if I already knew the assignment, like:
String name = generateName();
If it's a static value it should be declared as final static variable:
private final static DEFAULT_NAME = "John Doe";
If you need the variable before the assignment:
String name;
if(useLongNames) {
name = firstame;
}
else {
name = title + " " + fistname + " " + lastname;
}
// some code which uses name
In addition you could think about making all varible declarations final which you want only assign once. This would prevent you from some kind of errors which could then already be detected by the IDE.
If it's a field, you'd typically declare it without initialization, and assign it a value in the constructor.
If it's a local variable, best practice is to declare it where you know its intended value, so you can initialize it with a meaningful value:
String myString = "Result = " + xyz;
Introducing a variable not having a meaningful value is (in most cases) bad style. (Why would you intrduce a name (= variable) for something that you haven't yet decided upon?)
In situations like
String myString;
if (someCondition) {
myString = "A";
} else {
myString = "B";
}
System.out.println(myString);
where it's hard to use the same statement for declaring and assigning the string, it's best to declare the variable without initialization. Then the compiler checks that in all execution pathes you assign a value to the variable before you use it and never end up with some forgotten assignment.