I want to merge 2 Stirng arrays
the first one is merged okay but the second one keeps having null values even though it isn’t empty
no errors just wrong values
what is the problem here?
public class Q4 {
public static void main(String[] args){
String array1[] = new String[]{"Ahmad", "Adam"};
String array2[] = new String[]{"Mick", "Ali"};
int n1 = array1.length;
int n2 = array2.length;
String []array3 = new String[n1+n2];
for(int i = 0; i < n1; i++)
array3[i] = array1[i];
for(int i = n1; i<n2; i++) {
int j = 0;
array3[i] = array2[j++];
}
for(int i = 0; i<array3.length; i++)
System.out.print(array3[i] + " ");
}
}
the output should be
Ahmad Adam Mick Ali
but this is what I get
Ahmad Adam null null
>Solution :
for(int i = n1; i<n2; i++) {
the condition inside the second for loop is wrong.
As it is now you are starting from size of first array (2) to size of second array (2)
what you want should be
for(int i = n1; i<n2+n1; i++) {
also you are declaring int j inside the for loop which means j is reset each loop, move its definition outside of the loop or better yet replace it with
i-n1