I want to check whether an Array element is null.
I have initialized an array of String which has a size of 2. I looped through the array and check whether an array element is null. If it's null, I will add a String "a" to that position only.
My codes below will produce the following output:
1=a
2=a
Code:
public class CheckArrayElementIsNull {
public static void main(String[] args) {
String[] arr = new String[2];
for(int i = 0; i < arr.length; i++) {
if(arr[i] == null) {
arr[i] = "a";
}
System.out.println(i + "=" + arr[i]);
if(arr[i] == null) {
System.out.println(i + "= null");
}
}
}
}
I tried to add a break after my if condition but is not printing out anything.
public class CheckArrayElementIsNull {
public static void main(String[] args) {
String[] arr = new String[2];
for(int i = 0; i < arr.length; i++) {
if(arr[i] == null) {
arr[i] = "a";
break;
}
System.out.println(i + "=" + arr[i]);
if(arr[i] == null) {
System.out.println(i + "= null");
}
}
}
}
I expected this output:
1=a
2=null