Java Program to Check Idempotent Matrix

Java Program to Check Idempotent Matrix

In the previous article, we have seen Java Program to Find the Product of Middle Row and Middle Column of a Matrix

In this article we are going to see how we can write a program to check whether matrix is Idempotent Matrix or not.

Java Program to Check Idempotent Matrix

A 3*3 Matrix is having 3 rows and 3 columns where this 3*3 represents the dimension of the matrix. Means there are 3*3 i.e. total 9 elements in a 3*3 Matrix.

Let’s understand it in more simpler way.

                   | A00   A01   A02 |
Matrix A =  | A10   A11   A12 |
                   | A20   A21   A22 | 3*3
  • Matrix A represents a 3*3 matrix.
  • A‘ represents the matrix element
  • Aij‘ represents the matrix element at it’s matrix position/index.
  • i‘ represents the row index
  • j‘ represents the column index
  • Means A00=Aij  where i=0 and j=0,  A01=aij where i=0 and j=1 and like this.
  • Here we have started row value from 0 and column value from 0.

A matrix whose product of matrix to itself is equal to that matrix is called idempotent matrix .

Let’s see different ways to to check whether matrix is Idempotent Matrix or not.

Method-1: Java Program to Check Idempotent Matrix By Static Initialization of Array Elements

Approach :

  • Declare and initialize a matrix.
  • Calculate the product to itself .
  • Check the product of the matrix and the original matrix same or not .

Program :

import java.util.*;

public class Main 
{
   public static void main(String args[])
   {
       Scanner s = new Scanner(System.in);
        // Initializing the 3X3 matrix i.e. 2D array
        int mat[][]={{2,-2,-4},{-1,3,4},{1,-2,-3}};
        int res[][]=new int[3][3];;
        for (int i = 0; i < 3; i++) 
        { 
            for (int j = 0; j < 3; j++) 
            { 
                res[i][j] = 0; 
                for (int k = 0; k < 3; k++) 
                     res[i][j] += mat[i][k] * mat[k][j]; 
            } 
        } 
        for(int i = 0; i < 3; i++) 
            for (int j = 0; j < 3; j++)         
                if (mat[i][j] != res[i][j]) 
                    {
                        System.out.print("Entered matrix not an idempotent matrix .");
                        System.exit(0);
                    }
        System.out.println("Entered matrix is an idempotent matrix");
        
   }
}

Output:

Entered matrix is an idempotent matrix

Method-2: Java Program to Check Idempotent Matrix By Dynamic Initialization of Array Elements

  • Take input of a matrix from user.
  • Calculate the product to itself .
  • Check the product of the matrix and the original matrix same or not .
import java.util.*;
public class Main 
{
   public static void main(String args[])
   {
       Scanner s = new Scanner(System.in);
        // Initializing the 3X3 matrix i.e. 2D array
        int mat[][] = new int[3][3];
        int row, col ;
        // Taking matrix input
        System.out.println("\nEnter matrix elements");
        for(row=0;row<3;row++)
            for(col=0;col<3;col++)
                mat[row][col] = s.nextInt();
        int res[][]=new int[3][3];;
        for (int i = 0; i < 3; i++) 
            { 
                for (int j = 0; j < 3; j++) 
                    { 
                        res[i][j] = 0; 
                        for (int k = 0; k < 3; k++) 
                            res[i][j] += mat[i][k] * mat[k][j]; 
                    } 
            } 
        for(int i = 0; i < 3; i++) 
                for (int j = 0; j < 3; j++)         
                    if (mat[i][j] != res[i][j]) 
                        {
                            System.out.print("Entered matrix not an idempotent matrix .");
                            System.exit(0);
                        }
        System.out.println("Entered matrix is an idempotent matrix");
        
   }
}

Output:

Enter matrix elements
2 -2 -4
-1 3 4
1 -2 -3
Entered matrix is an idempotent matrix

Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

Related Java Programs:

Java Program to Find the Smallest Number in an Array

Java Program to Find the Smallest Number in an Array

In the previous article, we have seen Java Program to Find the Largest Number in an Array

In this article we are going to see how we can find the smallest element in an array.

Java Program to Find the Smallest Number in an Array

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways to find smallest element in the array.

Method-1: Java Program to Find the smallest Number in an Array By Comparing Array Elements

Approach:

  • Take an array with elements in it.
  • Print the array elements.
  • Create a variable and store the first element of the array in it.
  • Compare the variable with the whole array to find and store the largest element.
  • Print the largest element.

Program:

import java.util.Arrays;
import java.util.Scanner;

public class Main
{
    public static void main(String args[])
    {
        // Creating the array
        int arr[] = {12, 2, 34, 20, 54, 6};

        // Initializing the first element of the array to small
        int small=arr[0];        
        
        // Compares all the element to find out the smallest one
        for(int i:arr)
        {
            if(small>i)
                small=i;
        }

        // Prints the array elements
        System.out.println("The array elements are"+Arrays.toString(arr));
        
        // Prints the smallest element
        System.out.println("The smallest element of the array is: "+small);
    }
}


Output:

The array elements are[12, 2, 34, 20, 54, 6]
The smallest element of the array is: 2

Method-2: Java Program to Find the Smallest Number in an Array By Using Arrays.sort Method

Approach:

  • Take an array with elements in it.
  • Print the array elements.
  • Use Arrays.sort function to sort the array in ascending order.
  • Print the first element.

Program:

 import java.util.Arrays;
import java.util.Scanner;
public class Main
{
    public static void main(String args[])
    {
        // Creating the array
        int arr[] = {12, 2, 34, 20, 54, 6};
        
        // Sorts the array in ascending order
        Arrays.sort(arr);

        // Prints the array elements
        System.out.println("The array elements are"+Arrays.toString(arr));
        
        // Prints the largest element
        System.out.println("The smallest element of the array is: "+arr[0]);
    }
}

Output:

The array elements are[2, 6, 12, 20, 34, 54]
The smallest element of the array is: 2

Method-3: Java Program to Find the Smallest Number in an Array By Using array list and collections

Approach:

  • Take an array with elements in it.
  • Print the array elements.
  • Convert the array elements into a list.
  • Use the Collection.sort function to sort the list in ascending order.
  •  Print the first element.

Program:

import java.util.*;
import java.util.Scanner;
public class array{
    public static void main(String args[])
    {
        // Creating the array
        Integer arr[] = {12, 2, 34, 20, 54, 6};
        
        // Converts the array into a list
        List<Integer> list=Arrays.asList(arr);
        // Sorts the array in ascending order  
        Collections.sort(list);  

        // Prints the array elements
        System.out.println("The array elements are"+Arrays.toString(arr));
        
        // Prints the smallest element
        System.out.println("The smallest element of the array is: "+list.get(0));
    }
}

Output:

The array elements are[2, 6, 12, 20, 34, 54]
The largest element of the array is: 2

Method-4: Java Program to Find the Smallest Number in an Array By Using Stream API

Approach:

  • Take an array with elements in it.
  • Print the array elements.
  • Pass the array into the stream function mix( ) to find out the smallest element.
  • Print the element.

Program:

import java.util.*;
import java.util.Scanner;

public class Main
{
    public static void main(String args[])
    {
        // Creating the array
        int arr[] = {12, 2, 34, 20, 54, 6};
        
        // Using the stream API
        int small = Arrays.stream(arr).min().getAsInt();  

        // Prints the array elements
        System.out.println("The array elements are"+Arrays.toString(arr));
        
        // Prints the smallest element
        System.out.println("The smallest element of the array is: "+ small);
    }
}

Output:

The array elements are[12, 2, 34, 20, 54, 6]
The small element of the array is: 2

Enhancing programming skills is very important no matter what language you have chosen. So, practice frequently with these simple java programs examples and excel in coding the complex logic.

Related Java Programs:

Java Program to Replace Each Element of the Array with Product of All Other Elements of the Array

Java Program to Replace Each Element of the Array with Product of All Other Elements of the Array

In the previous article, we have seen Java Program to Find the Length of an Array

In this article we are going to see how we can replace the elements of an array with the product of all other elements using Java programming language.

Java Program to Replace Each Element of the Array with Product of All Other Elements of the Array

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Method-1: Java Program to Replace Each Element of the Array with Product of All Other Elements of the Array By Static Initialization of Array Elements

Approach:

  • Take an array with elements in it.
  • Print the array elements.
  • Find the product of all elements by iterating using a for loop.
  • Divide individual array elements by the product and store the resultant at that location.
  • Print the new array.

Program:

import java.util.Arrays;
public class array
{
    public static void main(String args[])
    {
        // Creating the array
        int arr[] = {1,2,3,4};

        // Prints the array elements
        System.out.println("The array elements are"+Arrays.toString(arr));
        // Stores the product of all elements in the array
        int product = 1;        
        for(int i:arr)
        {
            product*=i;
        }

        // Divides and replaces the array elements with the product of remaining elements
        for(int i=0;i<arr.length;i++)
        {
            arr[i] = product/arr[i];
        }

        System.out.println("The array elements after replacement"+Arrays.toString(arr));
    }
}

Output:

The array elements are[1, 2, 3, 4]
The array elements after replacement[24, 12, 8, 6]

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

Related Java Programs:

Java Program to Find the Length of an Array

Java Program to Find the Length of an Array

In the previous article, we have seen Java Program to Sort the Elements of an Array in Descending Order

In this article we are going to see how we can find length of an array in Java.

Java Program to Find the Length of an Array

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Method-1: Java Program to Find the Length of an Array By Using length function

Approach:

  • Take an array with elements in it.
  • Print out the array elements.
  • Pass the array to the length function and print the length of the array.

Program:

import java.util.Arrays;

public class array
{
    public static void main(String args[])
    {
        // Creating the array
        int arr[] = {12,2,34,54,6};

        // Prints the array elements
        System.out.println("The array elements are"+Arrays.toString(arr));
        // The length of the array using .length
        System.out.println("The length of the array is "+arr.length);
    }
}

Output:

The array elements are[12, 2, 34, 54, 6]
The length of the array is 5

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Related Java Programs:

Java Program to Find the Average of an Array

Java Program to Find the Average of an Array

In the previous article, we have seen Java Program to Find the Product of All the Elements of an Array

In this article we are going to see how we can find the average of elements in an array using Java programming language.

Java Program to Find the Average of an Array

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways to find the average of elements of the array.

Method-1: Java Program to Find the Average of an Array By Static Initialization of Array Elements

Approach:

  • Take an array with elements in it.
  • Print the array elements.
  • Find the sum of all elements by iterating using a for loop.
  • Find average by dividing the sum by the array length.
  • Print average.

Program:

import java.util.Arrays;
import java.util.Scanner;

public class Main
{
    public static void main(String args[])
    {
        // Creating the array
        int arr[] = {12, 2, 34, 20, 54, 6};

        int sum = 0,avg;        
        
        // Adds the sum of all elements
        for(int i=0;i<arr.length;i++)
        {
            sum+=arr[i];
        }

        avg=sum/arr.length;

        // Prints the array elements
        System.out.println("The array elements are"+Arrays.toString(arr));
        
        // Prints the average
        System.out.println("The average of the array is: "+avg);
    }
}
Output:

The array elements are[12, 2, 34, 20, 54, 6]
The average of the array is: 21

Method-2: Java Program to Find the Average of an Array By Dynamic Initialization of Array Elements

Approach:

  • Ask the user to enter the array size and store it.
  • Create an empty array of the specified size.
  • Ask the user to enter the elements.
  • Use a for loop to store the elements. Find the sum of all elements by iterating using a for loop.
  • Find average by dividing the sum by the array length.
  • Print the array elements.
  • Print the average.

Program:

import java.util.*;

public class Main
{
    public static void main(String args[])
    {
        Scanner scan = new Scanner(System.in);
        // Taking size as input from the user
        System.out.println("Enter the array size");
        int size = scan.nextInt();

        // Creating the array
        int arr[] = new int[size];

        // Entering the array elements
        System.out.println("Enter array elements");
        int sum = 0,avg;        
        for(int i=0;i<size;i++)
        {
            arr[i] = scan.nextInt();
            // Adds the sum of all elements
            sum+=arr[i];
        }

        avg=sum/arr.length;

        // Prints the array elements
        System.out.println("The array elements are"+Arrays.toString(arr));
        
        // Prints the average
        System.out.println("The average of the array is: "+avg);
    }
}

Output:

Enter the array size 5
Enter array elements 10 20 30 40 50
The array elements are[10, 20, 30, 40, 50]
The average of the array is: 30

Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.

Related Java Programs:

Java Program to Find the Second Largest Number in an Array

Java Program to Find the Second Largest Number in an Array

In the previous article, we have seen Java Program to Find Equilibrium Indices from a Given Array of Integers

In this article we are going to see how we can find the second largest element in an array using Java Programming language.

Java Program to Find the Second Largest Number in an Array

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways to find the second largest element in an array.

Method-1: Java Program to Find the Second Largest Number in an Array By Comparing Array Elements

Approach:

  • Take an array with elements in it.
  • Print the array elements.
  • Create a variable and store the first element of the array in it.
  • Compare the variable with the whole array to find and store the largest element.
  • Repeat the above step for the array elements except the largest element.
  • Print the second largest element.

Program:

import java.util.Arrays;
import java.util.Scanner;

public class Main
{
    public static void main(String args[])
    {
        // Creating the array
        int arr[] = {12, 2, 34, 20, 54, 6};

        // Initializing the first element of the array to large
        int large=arr[0];        
        
        // Compares all the element to find out the largest one
        for(int i:arr)
        {
            if(large<i)
                large=i;
        }

        // Initializing the first element of the array to secondLarge
        int secondLarge=arr[0];        
        
        // Compares all the element to find out the second largest one
        for(int i:arr)
        {
            if(secondLarge<i&&i!=large)
                secondLarge=i;
        }

        // Prints the array elements
        System.out.println("The array elements are : "+Arrays.toString(arr));
        
        // Prints the second largest element
        System.out.println("The second largest element of the array is : "+secondLarge);
    }
}



Output:

The array elements are : [12, 2, 34, 20, 54, 6]
The second largest element of the array is : 34

Method-2: Java Program to Find the Second Largest Number in an Array By Using Sorting (Array.sort())

Approach:

  • Take an array with elements in it.
  • Print the array elements.
  • Use a function Arrays.sort() to sort the array in ascending order.
  • Print the second last element.

Program:

import java.util.Arrays;
import java.util.Scanner;

public class Main
{
    public static void main(String args[])
    {
        // Creating the array
        int arr[] = {12, 2, 34, 20, 54, 6};
        
        // Sorts the array in ascending order
        Arrays.sort(arr);

        // Prints the array elements
        System.out.println("The array elements are : "+Arrays.toString(arr));
        
        // Prints the second largest element
        System.out.println("The second largest element of the array is : "+arr[arr.length-2]);
    }
}


Method-3: Java Program to Find the Second Largest Number in an Array By Using Array List and collections

Approach:

  • Take an array with elements in it.
  • Print the array elements.
  • Convert the array elements into a list.
  • Use the Collection.sort() function to sort the list in ascending order.
  •  Print the second last element.

Program:

import java.util.*;
import java.util.Scanner;

public class Main
{
    public static void main(String args[])
    {
        // Creating the array
        Integer arr[] = {12, 2, 34, 20, 54, 6};
        
        // Converts the array into a list
        List<Integer> list=Arrays.asList(arr);
        // Sorts the array in ascending order  
        Collections.sort(list);  

        // Prints the array elements
        System.out.println("The array elements are : "+Arrays.toString(arr));
        
        // Prints the second largest element
        System.out.println("The second largest element of the array is : "+list.get(arr.length-2));
    }
}
Output:

The array elements are : [2, 6, 12, 20, 34, 54]
The second largest element of the array is : 34

The best and excellent way to learn a java programming language is by practicing Simple Java Program Examples as it includes basic to advanced levels of concepts.

Related Java Programs:

Java Program to Print All the Unique Elements of an Array

Java Program to Print All the Unique Elements of an Array

In the previous article, we have seen Java Program to Find Total Number of Duplicate Numbers in an Array

In this article we will see how to print the unique elements of an array using Java programming language.

Java Program to Print All the Unique Elements of an Array

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways to print the unique elements of an array.

Method-1: Java Program to Print All the Unique Elements of an Array By Static Initialization of Array Elements

Approach:

  • Create an array with elements, and another blank array of same size called freq.
  • Set all the elements in the blank array to -1 using fill( ) library function.
  • Display the array elements to the user.
  • Pass both the arrays into an user function unique( ) that finds and stores the number of occurrence of elements.
  • Use a counter variable to count the number of times the element occurs inside the array.
  • Store it in the freq array at same location as the element.
  • Print the elements from the main array where the freq is only 1.

Program:

import java.util.*;
import java.util.Scanner;

public class Main
{
    public static void main(String args[])
    {
        // Creating the array
        int arr[] = {12, 22, 34, 22, 54, 6, 52, 8, 9, 34, 54, 68};
        int freq[] = new int[arr.length];
        // Sets all elements in the array to -1
        Arrays.fill(freq, -1);
        // Prints the array elements
        System.out.println("The array elements are "+Arrays.toString(arr));
        
        unique(arr,freq);

    }
    
    // Function that counts the frequency of elements 
    // and prints unique elements
    static void unique(int arr[], int freq[])
    {
        int count;

        for(int i = 0; i<arr.length; i++)
        {
            // Resets count to 1 after each element
            count=1;
            for(int j = i + 1; j<arr.length;j++)
            {
                // If another occurence of the current element is found 
                // in the array then increments the counter
                if(arr[i]==arr[j])
                {
                    count++;
                    freq[j] = 0;
                }
            }
            // Stores the frequency of each element
            if(freq[i]!=0)
            {
                freq[i] = count;
            }
        }
        
        // Prints the unique elements
        System.out.print("The unique elements in the array are: ");
        for(int i = 0; i<arr.length;i++)
        {
            if(freq[i]==1)
                System.out.print(arr[i]+" ");
        }
    }
}

Output:

The array elements are [12, 22, 34, 22, 54, 6, 52, 8, 9, 34, 54, 68]
The unique elements in the array are: 12 6 52 8 9 68

Method-2: Java Program to Print All the Unique Elements of an Array By Dynamic Initialization of Array Elements

Approach:

  • Take the array size input and array elements input from the user and create an array.
  • Create another blank array of same size called freq.
  • Set all the elements in the blank array to -1 using fill( ) library function.
  • Display the array elements to the user.
  • Pass both the arrays into an user function unique( ) that finds and stores the number of occurrence of elements.
  • Use a counter variable to count the number of times the element occurs inside the array.
  • Store it in the freq array at same location as the element.
  • Print the elements from the main array where the freq is only 1.

Program:

import java.util.*;
import java.util.Scanner;

public class Main
{
    public static void main(String args[])
    {
        Scanner scan = new Scanner(System.in);
        
        // Taking size as input from the user
        System.out.println("Enter the array size :");
        int size = scan.nextInt();
        
        // Creating the array
        int arr[] = new int[size];
        
        // Entering the array elements
        System.out.println("Enter array elements : ");
        for(int i=0;i<size;i++)
        {
            arr[i] = scan.nextInt();
        }
        
        int freq[] = new int[arr.length];
        
        // Sets all elements in the array to -1
        Arrays.fill(freq, -1);
        
        // Prints the array elements
        System.out.println("The array elements are "+Arrays.toString(arr));
        
        unique(arr,freq);

    }
    
    // Function that counts the frequency of elements 
    // and prints unique elements
    static void unique(int arr[], int freq[])
    {
        int count;

        for(int i = 0; i<arr.length; i++)
        {
            // Resets count to 1 after each element
            count=1;
            for(int j = i + 1; j<arr.length;j++)
            {
                // If another occurence of the current element is found 
                // in the array then increments the counter
                if(arr[i]==arr[j])
                {
                    count++;
                    freq[j] = 0;
                }
            }
            // Stores the frequency of each element
            if(freq[i]!=0)
            {
                freq[i] = count;
            }
        }
        
        // Prints the unique elements
        System.out.print("The unique elements in the array are: ");
        for(int i = 0; i<arr.length;i++)
        {
            if(freq[i]==1)
                System.out.print(arr[i]+" ");
        }
    }
}

Output:

Enter the array size : 5
Enter array elements :  2 2 3 1 4
The array elements are [2, 2, 3, 1, 4]
The unique elements in the array are: 3 1 4

Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples

Related Java Programs:

Java Program to Find Total Number of Duplicate Numbers in an Array

Java Program to Find Total Number of Duplicate Numbers in an Array

In the previous article, we have seen Java Program to Print an Array in Reverse Order

In this article we are going to find the duplicate numbers present inside an array in Java.

Java Program to Find Total Number of Duplicate Numbers in an Array

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways to print the duplicate elements of an array.

Method-1: Java Program to Print All the Duplicate Elements of an Array By Static Initialization of Array Elements

Approach:

  • Create an array with elements, and another blank array of same size called freq.
  • Set all the elements in the blank array to -1 using fill( ) library function.
  • Display the array elements to the user.
  • Pass both the arrays into an user function unique( ) that finds and stores the number of occurrence of elements.
  • Use a counter variable to count the number of times the element occurs inside the array.
  • Store it in the freq array at same location as the element.
  • Print the elements from the main array where the freq is greater 1.

Program:

import java.util.*;
import java.util.Scanner;

public class Main
{
    public static void main(String args[])
    {
        // Creating the array
        int arr[] = {12, 22, 34, 22, 54, 6, 52, 8, 9, 34, 54, 68};
        int freq[] = new int[arr.length];
        // Sets all elements in the array to -1
        Arrays.fill(freq, -1);
        // Prints the array elements
        System.out.println("The array elements are : "+Arrays.toString(arr));
        
        unique(arr,freq);

    }
    
    // Function that counts the frequency of elements 
    // and prints duplicate elements
    static void unique(int arr[], int freq[])
    {
        int count;

        for(int i = 0; i<arr.length; i++)
        {
            // Resets count to 1 after each element
            count=1;
            for(int j = i + 1; j<arr.length;j++)
            {
                // If another occurence of the current element is found 
                // in the array then increments the counter
                if(arr[i]==arr[j])
                {
                    count++;
                    freq[j] = 0;
                }
            }
            // Stores the frequency of each element
            if(freq[i]!=0)
            {
                freq[i] = count;
            }
        }
        // Prints the duplicate elements
        System.out.print("The duplicate elements in the array are : ");
        for(int i = 0; i<arr.length;i++)
        {
            if(freq[i]>1)
                System.out.print(arr[i]+" ");
        }
    }
}

Output:

The array elements are : [12, 22, 34, 22, 54, 6, 52, 8, 9, 34, 54, 68]
The duplicate elements in the array are : 22 34 54

Method-2: Java Program to Print All the Duplicate Elements of an Array By Dynamic Initialization of Array Elements

Approach:

  • Take the array size input and array elements input from the user and create an array.
  • Create another blank array of same size called freq.
  • Set all the elements in the blank array to -1 using fill( ) library function.
  • Display the array elements to the user.
  • Pass both the arrays into an user function unique( ) that finds and stores the number of occurrence of elements.
  • Use a counter variable to count the number of times the element occurs inside the array.
  • Store it in the freq array at same location as the element.
  • Print the elements from the main array where the freq is greater 1.

Program:

import java.util.*;
import java.util.Scanner;

public class Main
{
    public static void main(String args[])
    {
        Scanner scan = new Scanner(System.in);
        
        // Taking size as input from the user
        System.out.println("Enter the array size :");
        int size = scan.nextInt();
        
        // Creating the array
        int arr[] = new int[size];
        
        // Entering the array elements
        System.out.println("Enter array elements : ");
        for(int i=0;i<size;i++)
        {
            arr[i] = scan.nextInt();
        }
        
        int freq[] = new int[arr.length];
        
        // Sets all elements in the array to -1
        Arrays.fill(freq, -1);
        
        // Prints the array elements
        System.out.println("The array elements are : "+Arrays.toString(arr));
        
        unique(arr,freq);

    }
    
    // Function that counts the frequency of elements 
    // and prints duplicate elements
    static void unique(int arr[], int freq[])
    {
        int count;

        for(int i = 0; i<arr.length; i++)
        {
            // Resets count to 1 after each element
            count=1;
            for(int j = i + 1; j<arr.length;j++)
            {
                // If another occurence of the current element is found 
                // in the array then increments the counter
                if(arr[i]==arr[j])
                {
                    count++;
                    freq[j] = 0;
                }
            }
            // Stores the frequency of each element
            if(freq[i]!=0)
            {
                freq[i] = count;
            }
        }
        
        // Prints the duplicate elements
        System.out.print("The duplicate elements in the array are: ");
        for(int i = 0; i<arr.length;i++)
        {
            if(freq[i]>1)
                System.out.print(arr[i]+" ");
        }
    }
}
Output:

Enter the array size :
Enter array elements : 
The array elements are : [2, 2, 3, 1, 4]
The duplicate elements in the array are: 2

Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples

Related Java Programs:

Java Program to Print the Elements of an Array

Java Program to Print the Elements of an Array

In the previous article, we have seen Java Program to Reverse Array Elements

In this article we are going to see how we can print the elements of an array in various ways in Java.

Java Program to Print the Elements of an Array

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways to print an array.

Method-1: Print Array Elements Using For Loop

Approach:

  • Use a for loop to iterate the array index.
  • Print the array elements at those index.

Program:

public class array
{
    public static void main(String args[])
    {
        // Array with elements
        int arr[] = {10,15,1,30,50,7,1,0,0};
        int row;

        System.out.print("The array elements are : ");
        
        //Loop to print the elements
        for(row=0;row<arr.length;row++)
        {
                System.out.print(arr[row]+" ");
        }   
    }
}
Output:

The array elements are:10 15 1 30 50 7 1 0 0

Method-2: Print Array Elements Using For-each Loop

Approach:

  • Use a for-each loop to iterate the elements in the variable.
  • Print the variables.

Program:

public class array
{
    public static void main(String args[])
    {
        // Array with elements
        int arr[] = {10,15,1,30,50,7,1,0,0};    

        System.out.print("The array elements are : ");
        //For-each Loop to print the elements
        for(int iter:arr)
        {
                System.out.print(iter+" ");
        }   
    }
}
Output:

The array elements are : 10 15 1 30 50 7 1 0 0

Method-3: Print User Input Array Elements Using For Loop

Approach:

  • Ask the user for array length.
  • Store it in a variable.
  • Use a for loop to iterate the index and insert the elements.
  • Use a for loop to print all the elements.

Program:

import java.util.Scanner;
public class array
{
    public static void main(String args[])
    {
        Scanner scan = new Scanner(System.in);
        // Array with elements
        int arr[] = null;
        System.out.println("Enter the length of the array : ");
        int length = scan.nextInt();
        arr = new int[length];
        int iter;   

        // Entering the array elements
        System.out.println("Enter the array elements : ");
        for(iter=0;iter<arr.length;iter++)
            arr[iter]=scan.nextInt();

        System.out.println("The array elements are : ");
        //For Loop to print the elements
        for(iter=0;iter<arr.length;iter++)
        {
                System.out.print(arr[iter]+",");
        }   
    }
}
Output:

Enter the length of the array : 5
Enter the array elements : 1 2 3 4 5
The array elements are : 
1,2,3,4,5,

Method-4: Print Array Elements Using Arrays.toString()

Approach:

  • Take an array with elements in it.
  • Pass the array into the Arrays.toString( ) function.
  • Print the generated string.

Program:

import java.util.Arrays;
public class array
{
    public static void main(String args[])
    {
        // Array with elements
        int arr[] = {10,15,1,30,50,7,1,0,0};    
        //Printing using arrays.toString() library function
        System.out.print("The array elements are:"+Arrays.toString(arr));
    }
}
Output:

The array elements are:[10, 15, 1, 30, 50, 7, 1, 0, 0]

Method-5: Print String Array Elements Using Arrays.asList()

Approach:

  • Take a string array with elements in it.
  • Pass the array into the Arrays.asList( ) function.
  • Print the result.

Program:

import java.util.Arrays;
public class array
{
    public static void main(String args[])
    {
        // String Array with elements
        String arr[] = {"New York","Brooklyn","Paris"};    
        //Printing using arrays.asList() library function
        System.out.print("The array elements are:"+Arrays.asList(arr));
    }
}
Output:

The array elements are:[New York, Brooklyn, Paris]

Method-6: Print String Array Elements Using Java iterator interface

Approach:

  • Take a Double array with elements in it.
  • Create an iterator.
  • Convert the array into a list.
  • Use the iterator to iterate the list and print out the elements.

Program:

import java.util.Arrays;
import java.util.Iterator;
public class array
{
    public static void main(String args[])
    {
        // Double Array with elements
        Double arr[] = {10.3,20.5,35.3,50.5};
        System.out.print("The array elements are : ");
        // Creating the iterator
        Iterator<Double> iter = Arrays.asList(arr).iterator();
        // While loop that prints until there is no next element
        // The hasNext() checks whether there is a next element and returns a boolean value
        while(iter.hasNext())
        {  
            System.out.print(iter.next()+", ");  
        }  
    }
}

Output:

The array elements are : 10.3, 20.5, 35.3, 50.5,

Method-7: Print Array Elements Using Java Stream API

Approach:

  • Take an array with elements in it.
  • Pass the array into the stream() function and then use a for each loop with it to print out all the elements in it.

Program:

import java.util.Arrays;
public class array
{
    public static void main(String args[])
    {
        // Array with elements
        Double arr[] = {10.3,20.5,35.3,50.5};
        System.out.println("The array elements are");
        // Prints using the stream API
        Arrays.stream(arr).forEach(System.out::println);  
    }
}

Output:

The array elements are
10.3
20.5
35.3
50.5

Provided list of Simple Java Programs is specially designed for freshers and beginners to get familiarize with the concepts of Java programming language and become pro in coding.

Related Java Programs:

Java Program to Sort the Elements of an Array in Descending Order

Java Program to Sort the Elements of an Array in Descending Order

In the previous article, we have seen Java Program to Sort the Elements of an Array in Ascending Order

In this article we are going to see how we can sort an Array in descending order in Java.

Java Program to Sort the Elements of an Array in Descending Order

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways to Sort the Elements of an Array in Descending Order.

Method-1: Java Program to Sort an array in Decreasing order using an user-defined method

Approach:

  • Ask the user to input the size and store it.
  • Create an array of the specified size.
  • Print the array elements
  • Sort the elements using the user-defined function sortArr( ).
  • Print the sorted array elements

Program:

import java.util.Scanner;
import java.util.Arrays;

public class array
{
    public static void main(String args[])
    {
        Scanner scan = new Scanner(System.in);
        // Asking the user for array size
        System.out.println("Enter the array size : ");
        int size = scan.nextInt();

        // Creating the array
        int arr[] = new int[size];

        System.out.println("Enter the array elements : ");
        // Takes the elements as input from the user
        for(int i = 0;i<size;i++)
        {
            arr[i] = scan.nextInt();
        }

        // Prints the array before and after sorting
        System.out.println("The array elements are"+Arrays.toString(arr));
        sortArr(arr,size);
        System.out.println("The array elements after sorting in descending order are : "+Arrays.toString(arr));
    }
    
    // Method to sort the array
    static void sortArr(int arr[],int size)
    {
        int temp;
        // Uses Bubble Sort to sort the array
        for (int i = 0; i < size; i++) {
            // Compares and replaces the element with all the remaining elements in the array
            for (int j = i+1; j < size; j++) {     
                if(arr[i] < arr[j]) {    
                    temp = arr[i];    
                    arr[i] = arr[j];    
                    arr[j] = temp;    
                }     
            }     
        }    
    }
}

Output:

Enter the array size : 6
Enter the array elements : 6 1 5 3 4 2
The array elements are[6, 1, 5, 3, 4, 2]
The array elements after sorting in descending order are : [6, 5, 4, 3, 2, 1]

Method-2: Java Program to  Sort an Array In Decreasing Order Using Arrays.sort function

Approach:

  • Ask the user to input the size and store it.
  • Create an array of the specified size.
  • Print the array elements
  • Sort the elements using the Arrays.sort function.
  • Print the sorted array elements

Program:

import java.util.Scanner;
import java.util.Collections; 
import java.util.Arrays;

public class array
{
    public static void main(String args[])
    {
        Scanner scan = new Scanner(System.in);
        // Asking the user for array size
        System.out.println("Enter the array size : ");
        int size = scan.nextInt();

        // Creating the array
        Integer arr[] = new Integer[size];

        System.out.println("Enter the array elements : ");
        // Takes the elements as input from the user
        for(int i = 0;i<size;i++)
        {
            arr[i] = scan.nextInt();
        }

        // Prints the array before and after sorting
        System.out.println("The array elements are : "+Arrays.toString(arr));
        Arrays.sort(arr, Collections.reverseOrder());
        System.out.println("The array elements after sorting in ascending order are : "+Arrays.toString(arr));
    }
}

Output:

Enter the array size : 6
Enter the array elements : 6 1 5 3 4 2
The array elements are : [6, 1, 5, 3, 4, 2]
The array elements after sorting in ascending order are : [6, 5, 4, 3, 2, 1]

Interested in programming and want to excel in it by choosing the short ways. Then, practicing with the available Java Program list is mandatory.

Related Java Programs: