w3resource

Java: Find the duplicate values of an array of integer values


Write a Java program to find duplicate values in an array of integer values.

Pictorial Presentation:

Java Array Exercises: Find the duplicate values of an array of integer values

Sample Solution:

Java Code:

// Import the Arrays class from the java.util package.
import java.util.Arrays;

// Define a class named Exercise12.
public class Exercise12 {
    
    // The main method where the program execution starts.
    public static void main(String[] args) {
        // Declare and initialize an integer array 'my_array'.
        int[] my_array = {1, 2, 5, 5, 6, 6, 7, 2};
 
        // Iterate through the elements of the array.
        for (int i = 0; i < my_array.length-1; i++) {
            for (int j = i+1; j < my_array.length; j++) {
                // Check if two elements are equal and not the same element.
                if ((my_array[i] == my_array[j]) && (i != j)) {
                    // If a duplicate is found, print the duplicate element.
                    System.out.println("Duplicate Element : " + my_array[j]);
                }
            }
        }
    }    
}

Sample Output:

Duplicate Element : 2                                                                                         
Duplicate Element : 5                                                                                         
Duplicate Element : 6

Flowchart:

Flowchart: Java exercises: Find the duplicate values of an array of integer values

For more Practice: Solve these Related Problems:

  • Write a Java program to count the number of duplicate values in an integer array.
  • Write a Java program to remove all duplicate values from an integer array.
  • Write a Java program to find the most frequently occurring number in an array.
  • Write a Java program to return a list of unique numbers from an array by removing duplicates.

Java Code Editor:

Previous: Write a Java program to reverse an array of integer values.
Next: Write a Java program to find the duplicate values of an array of string values.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.