Search code examples
javaarraysloopsnested-loops

How is the output generated for this java program?


Can someone explain the logic of this code? How it works? The output gets printed as 2 3 4 but I don't understand how.. I'm writing these extra lines cause unfortunately stack overflow doesn't let me post the question if there isn't enough explanation about it, which is annoying cause I have come here only to get an explanation for this code. Hope it allows me to post my question now!

import java.util.Arrays;

public class Javaexcercise {
    public static void main(String[] args)

    {

        int[] my_array = {1, 2, 3, 4, 5, 6, 7, 2, 3, 4};
        

        for (int i = 0; i < my_array.length-1; i++)

        {

            for (int j = i+1; j < my_array.length; j++)

            {

                if ((my_array[i] == my_array[j]) && (i != j))

                {

                    System.out.println(my_array[j]);

                }

            }

        }

    }   

}

Output :

2
3
4

Solution

  • Your program will compare the values for every pair in the array and print only the matches.

    enter image description here