In this tutorial, we will write java programs to print the duplicate elements of an array. For example, if an array is {1, 2, 3, 2, 3, 5}
then the program should print the elements {2, 3}
as these elements appeared in the array more than once.
Program to print duplicate elements of the given int array
In this program, we are running a nested for loop, in such a way that each element of the given array is compared with all other elements of the same array and if there is a match found, print that element.
To compare the elements we are using equal to ==
operator as the given array is an int
type array. If you want to find out the duplicate elements in a String array, refer the next program.
public class JavaExample { public static void main(String[] args) { //Initializing an int array int [] numbers = new int [] {2, 4, 6, 8, 4, 6, 10, 10}; System.out.println("Duplicate elements in given array are: "); //Comparing each element of the array with all other elements for(int i = 0; i < numbers.length; i++) { for(int j = i + 1; j < numbers.length; j++) { if(numbers[i] == numbers[j]) { //printing duplicate elements System.out.println(numbers[j]); } } } } }
Output:
Duplicate elements in given array are: 4 6 10
Program to print duplicate elements of the String array
Here, we are displaying the duplicate elements of a String array. In the following example, we have an array that contains strings as elements. The logic we are using to print the duplicate elements is same as the above example, except that here we are using equals() method to compare elements as the elements are Strings.
public class JavaExample { public static void main(String[] args) { //Initializing an int array String [] names = new String [] {"Tom", "Steve", "Rick", "Steve", "Rick"}; System.out.println("Duplicate elements in the given array: "); //Comparing each element of the array with all other elements for(int i = 0; i < names.length; i++) { for(int j = i + 1; j < names.length; j++) { if(names[i].equals(names[j])){ //printing duplicate elements System.out.println(names[j]); } } } } }
Output:
Duplicate elements in the given array: Steve Rick
Leave a Reply