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


Edit:

inputArr[i] += "ABC";

      

To:



inputArr[i] = "ABC";

      

Or (like the one mentioned by Jon Skeet) you can use the conditional operator to initialize or concatenate strings:

inputArr[i] = inputArr[i] == null ? "ABC" : inputArr[i] + "ABC";

      

+4


a source


The zero in the array is not a string "null"

, but a value null

. If you want to initialize it with empty strings, follow these steps:

for (int i = 0; i < inputArr.length; i++) {
    inputArr[i] = "";
}

      

+1


a source


Others have given pretty good answers regarding the "empty" array operator and assignment. Just let me add another way to initialize an array:

String[] inputArr = new String[5];
java.util.Arrays.fill(inputArr, "ABC");

      

0


a source







All Articles