String [], initialized to zero?
Hi I ran into this problem when I initialized my String [] it seems there is a null in String [] before I do anything. How do I initialize String [] to be completely empty, i.e. without a zero at the beginning? Output for the following code:
nullABC
nullABC
nullABC
nullABC
nullABC
public static void main(String[] args){
String[] inputArr = new String[5];
for (int i = 0; i< inputArr.length; i++){
inputArr[i] += "ABC";
}
for (int i = 0; i< inputArr.length; i++){
System.out.println(inputArr[i]);
}
}
}
+2
a source to share
4 answers
A null reference is about as empty as a string array element. Note that there is a big difference between an empty string reference and a null reference. Just change your code to use simple assignment instead of + =.
for (int i = 0; i< inputArr.length; i++){
inputArr[i] = "ABC";
}
If you need to do conditional concatenation elsewhere, use something like this:
for (int i = 0; i< inputArr.length; i++) {
String current = inputArr[i];
String suffix = "ABC";
String replacement = current == null ? suffix : current + suffix;
inputArr[i] = replacement;
}
Alternatively, you can use something like this:
public static String emptyForNull(String x) {
return x == null ? "" : x;
}
and then:
for (int i = 0; i< inputArr.length; i++){
inputArr[i] = emptyForNull(inputArr[i]) + "ABC";
}
Or (yes, many options available):
public static String nullAwareConcat(String x, String y) {
return x == null && y == null ? ""
: x == null ? y
: y == null ? x
: x + y;
}
...
for (int i = 0; i< inputArr.length; i++){
inputArr[i] = nullAwareConcat(inputArr[i], "ABC");
}
+14
a source to share