Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

null values keep appearing

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading