One-Dimensional Array Examples in Java

Example : Array examples in Java to store and display a static numeric value.

import java.io.*; 
class ODA
 {   
    public static void main(String args[]) throws IOException 
     { 
        int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 
        int i;   
        
        for (i = 0; i < arr.length; i++) 
         { 
           System.out.print(arr[i] + " "); 
         } 
     } 
 } 
Output : 1 2 3 4 5 6 7 8 9 10

/*  -------------------------------------------OR----------------------------------------*/

import java.io.*; 
class ODA
 {   
    public static void main(String args[]) throws IOException 
     { 
        int arr[]={ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };                 
        for (int i : arr) 
         {             
            System.out.print(i + " "); 
         } 
      } 
 }

Output : 1 2 3 4 5 6 7 8 9 10
NB : This is an example of 'for-each' loop where loop is used exclusively to loop through each element in arrays:

/*  -------------------------------------------OR----------------------------------------*/
import java.io.*; 
class ODA
 {   
    public static void main(String args[])
     {         
        int[] num;     // or int []num;
        num=new int[4];
      
        num[0]=14; 
        num[1]=20;
        num[2]=23; 
        num[3]=32; 
      
        for(int i=0; i<num.length;i++)
	  { 
           System.out.print(num[i]+ " ");      
          }
     } 
 }

Output : 14 20 23 32 

/*  ------OR------(Different way to declare array)-------------*/
import java.io.*; 
class ODA
 {   
    public static void main(String args[])
     {         
        int[] num=new int[4];    // int num[]=new int[4];	
      
        num[0]=14; 
        num[1]=20;
        num[2]=23; 
        num[3]=32; 
      
        for(int i=0; i<num.length;i++)
	  { 
           System.out.print(num[i]+ " ");      
          }
     } 
 }

Output : 14 20 23 32
 
NB: Without 'throws IOException' program can also be run but it is a  good practice to add it. 

Example : Array examples in Java to display one-dimensional array form in two-dimensional array form.

import java.io.*;
class ODA
{
	public static void main(String[] args) throws IOException
	{
		int arr[]={1,2,3,4,5,6,7,8,9,10,11};
		int i,j=0;		
		for(i=0;i<arr.length;i++)
		{			
			if(j==3||j==6||j==9)     // To break the row after 3 values
                           {
			      System.out.println();
                           }
			      System.out.print(arr[i] +"  ");			
			j++;
		}
	}
}
Output :
1  2  3
4  5  6
7  8  9
10 11

Example : A Java Program to display the total of user-accepted values.

import java.util.Scanner;
class ArraySum
{   
      Scanner sc = new Scanner(System.in);	  
      int[] Arr = new int[5];
	  int sum = 0;	  
	  void input()
	  {
		  System.out.println("Enter the elements:");
		  for (int i=0; i<5; i++)
		  {
		     Arr[i] = sc.nextInt();
		  }
	  }	  
	  void output()
	  {
		  for( int num : Arr) 
		  {
		     sum = sum+num;
		  }
		  System.out.println("Sum of Array elements is:"+sum);
	  }	  
	  public static void main(String args[])
		{
			ArraySum x= new ArraySum();
			x.input();
			x.output();
		}
}

Example : A Java Program to pass an array through a method (function) to process it.

import java.io.*; 
class ODA
 {   
    public static void main(String args[])
	{  
		int num[]={36,83,24,35,42};
		
		call(num); 
	}

	static void call(int arr[])
	{ 		 
	    for(int i=0;i<arr.length;i++)
              {			
	       System.out.print(arr[i]);
              }  
	}
 }	
Output : 36 83 24 35 42
/*  -------------------------------------------OR----------------------------------------*/

import java.io.*; 
class ODA
 {   
    public static void main(String args[])  
    { 
        int arr3[] = {45, 17, 29, 55,47};
       
        total(arr3);      
    } 
 
    public static void total(int[] arr3)  
      {         
        int total=0;          
        for (int i=0; i<arr3.length; i++)
	   { 
            	total=total+arr3[i];
	   }          
        System.out.println("Sum of array elements are = " + total); 
       } 
 }
Output : Sum of array elements are = 146

NB: Without public,'total' method can also be run.But without static it is not possible 
    because main method where it is called is also a static method.

Example : A Java program for an array to receive & display values (dynamic) given by the users.

import java.io.*;
import java.util.Scanner;
class ODA
{		
	public static void main(String[] args) 
	{		   
	   int[] num=new int[5]; 
	   Scanner y=new Scanner(System.in);		
		
	   System.out.print("Enter 5 array elements:");
           for(int i = 0; i <5; i++)
            {
                num[i] = y.nextInt();
	    }	   
		
	   for(int i=0;i<num.length;i++)
	   {			
	       System.out.print(num[i]+"  ");		    		
	   }		
        }
}

Example : An array program in Java to receive values (dynamic) from users and display its sum using different methods.

import java.io.*;
import java.util.Scanner;
class ODA
{	
	int x;	
	int num[]={};   //Global declaration of array

	void input()
	{			
		Scanner y=new Scanner(System.in);	
		System.out.print("Enter the user's array length= ");
		x = y.nextInt();
		num=new int[x];
		
		System.out.print("Enter " + x +" array elements:");
                for(int i = 0; i <num.length; i++)
                 {
                    num[i] = y.nextInt();
	         }		
	}
	
	void display()
	{ 	
		int sum=0;
		for(int i=0;i<num.length;i++)
		{			
		    System.out.println(num[i]);
		    sum=sum+num[i];			
		}
		System.out.println();   // For new line only
		System.out.println(sum);
	}
		
	public static void main(String[] args) 
		{
		   ODA z=new ODA();
		   z.input();
		   z.display();
		}
}
	
------------------- OR --------------------
import java.io.*;
import java.util.Scanner;
class ODA
{	
	void input()
	{
		int x;		
		Scanner y=new Scanner(System.in);	
		System.out.print("Enter array length= ");
		x = y.nextInt();
		int num[]=new int[x];		
		
		System.out.print("Enter " + x +" array elements:");
                for(int i = 0; i <num.length; i++)
                  {
                   num[i] = y.nextInt();
		  } 
		
		display(num); 
	}	
	void display(int arr[])
	{ 	
		int sum=0;
		for(int i=0;i<arr.length;i++)
		{			
		    System.out.println(arr[i]);
		    sum=sum+arr[i];			
		}
		System.out.println();
		System.out.println(sum);
	}
		
	public static void main(String[] args) 
		{
		   ODA z=new ODA();
		   z.input();		   
		}
}	

Example : A Java Program to return an array of values through a method (function) as an output.

import java.io.*; 
class ODA
 {   
	public static void main(String args[])
	{  
	    display(new int[]{120,28,12,64,05});  //Anonymous array  
	}
	
	static void display(int arr[])
	{  
	     for(int i=0;i<arr.length;i++)  
             System.out.println(arr[i]);  
	}
 }

Output:
120
28
12
64
05 	

/*  -------------------------------------OR------------------------------------*/

import java.io.*; 
class ODA
 {    
    public static void main(String args[])  
      { 
         int arr[]=num(); 
          
         for (int i=0;i<arr.length;i++)
	    { 
              System.out.print(arr[i]+",");
            }      
       }   
    public static int[] num()  
    { 
        return new int[]{42,21,57,35,65};   //Anonymous array
    } 
 }

Output : 42,21,57,35,65,

NB : Anonymous array - A feature of an array that doesn't need to declare the array while passing through a method.

Example : A Java program to reverse an array of elements through a function/method.

import java.io.*; 
class Array11
 {   
	public static void main(String[] args)
	{  	
		int[]arr={10,3,100,7,5,25,30}; 
		
		reverse(arr,arr.length); 
	}
    
	static void reverse(int x[],int n) 
	{ 
		int[]revarr = new int[n];
		
		int y = n;		
		for (int i=0;i<n;i++) 
		{ 
			revarr[y-1]=x[i]; 
			y=y-1; 
		}		
		System.out.println("The Output of Reversed array is: \n"); 
		for (int k=0;k<n;k++) 
		{ 
			System.out.print(revarr[k] + " "); 
		} 
	}	
 }

Output : 30 25 5 7 100 3 10	

Example : A Java Program to display the largest value of an array.

import java.util.Scanner;
class Largest 
{
    public static void main(String[] args) 
    {
        int n, max;
        Scanner s = new Scanner(System.in);
        System.out.print("Enter number of elements in the array:");
        n = s.nextInt();
		
        int a[] = new int[n];
        System.out.println("Enter " + n + " elements of array:");
        for(int i = 0; i < n; i++)
        {
            a[i] = s.nextInt();
        }

        max = a[0];
        for(int i = 0; i < n; i++)
        {
            if(max < a[i])
            {
                max = a[i];
            }
        }
        System.out.println("Largest value is ="+max);
    }
}

Example : An array program in Java to display the values in ascending order.

import java.util.Scanner;

class Ascending 
{
    public static void main(String[] args) 
    {
        int size, temp;
        Scanner Sc = new Scanner(System.in);
		
        System.out.print("Enter the size of an array: ");
        size = Sc.nextInt();
        int x[] = new int[size];
		
        System.out.println("Enter array elements:");
        for (int i = 0; i < size; i++) 
        {
            x[i] = Sc.nextInt();
        }
		
        for (int i = 0; i < size; i++) 
        {
            for (int j = i + 1; j < size; j++) 
            {
                if (x[i] > x[j]) 
                {
                    temp = x[i];
                    x[i] = x[j];
                    x[j] = temp;
                }
            }
        }		
        System.out.println("The sorted Ascending Order of an array is : ");
        for (int i = 0; i < size; i++) 
        {
            System.out.print(x[i] + " ");
        }        
    }
}

Example : A Java Program to convert an array into string form.

import java.util.Arrays;  
class Array5
{
    public static void main(String[] args) 
    {   
        int Arr[]={35,41,20,78};  
        System.out.println(Arrays.toString(Arr)); 
    } 
}

Output : [35, 41, 20, 78]

NB: To convert array elements as string 'Arrays.toString()' is used and is present inside 
    'java.util.Arrays'package. 

Example : A Java Program to compare two array elements.

import java.util.Arrays;  
class Array6
{
    public static void main(String[] args) 
    {   
        int Arr[]={35,41,20,78};  
        
        int Arr1[]={60,85,52,36}; 
  
        System.out.println("Both the array elements are similar : "+ 
        Arrays.equals(Arr,Arr1)); 
    } 
}
Output : Both the array elements are similar : false

NB: To compare two array elements 'Arrays.equals()' is used, present inside 'java.util.Arrays' 
    package. 

Two (Multi) Dimensional Array

Example : A Java program to store & display values in two-dimensional array.

import java.io.*; 
class TDA
 {   
	public static void main(String args[])
	{ 
		int arr[][]={{10,20,30},{40,50,60},{70,80,90}};  

			for(int i=0;i<3;i++)
			{  
				for(int j=0;j<3;j++)
				{  
				  System.out.print(arr[i][j] + " ");  
				}				
				System.out.println();  
			}  
	}
 }

Output : 
10 20 30
40 50 60
70 80 90

/* -------------------------------------OR------------------------------------*/

import java.io.*; 
class TDA
 {   
	public static void main(String args[])
	{  
		int[][] num=new int[3][3];
                //int [][]num=new int[3][3];
                //int num[][]=new int[3][3];
                //int []num[]=new int[3][3];

			num[0][0]=10;  
			num[0][1]=20;  
			num[0][2]=30;
  
			num[1][0]=40;  
			num[1][1]=50;  
			num[1][2]=60;
  
			num[2][0]=70;  
			num[2][1]=80;  
			num[2][2]=90; 

		for(int i=0;i<3;i++)
		{  
			for(int j=0;j<3;j++)
			{  
			    System.out.print(num[i][j] + " ");  
			}			
			System.out.println();  
		}  			
	}
 }

Output : 
10 20 30
40 50 60
70 80 90		

Example :  A Java program to add two matrices and display the result.

import java.io.*; 
class TDA
 {   
	public static void main(String[] args)
	{  	
		int x[][]={{12,43,41},{13,24,50}};  
		int y[][]={{20,80,40},{37,42,52}};
		int z[][]=new int[2][3];  

			for(int i=0;i<2;i++)
			{  
				for(int j=0;j<3;j++)
				{  
					z[i][j]=x[i][j]+y[i][j];  
					System.out.print(z[i][j]+" ");  
				}  
				System.out.println();
			}  
	 }  
	
 }	

Example :  A Java program to multiply two matrices and display the result.

import java.io.*; 
class TDA
 {   
	public static void main(String[] args)
	{  	
		int a[][]={{7,2,1},{6,5,2},{4,3,8}};    
		int b[][]={{4,3,2},{6,7,2},{1,9,7}};			
		  
		int c[][]=new int[3][3];			
		    
		for(int i=0;i<3;i++)
		{    
			for(int j=0;j<3;j++)
			{    
				c[i][j]=0; 
				
				for(int k=0;k<3;k++)      
				{      
				    c[i][j] = c[i][j] + a[i][k] * b[k][j];      
				}  
				System.out.print(c[i][j]+" ");  
			}
			System.out.println();  
		}
	}
 }

Output : 
41 44 25
56 71 36
42 105 70	

Example : An array program in Java to show values in Transpose form.

import java.util.Scanner;
class Transpose
{
    public static void main(String args[])  
    {
	int i, j;
	
	System.out.println("Enter similar value for rows and columns: ");
	Scanner Sc = new Scanner(System.in);
	int row = Sc.nextInt();
	int column = Sc.nextInt();
	
	int x[][] = new int[row][column];
	System.out.println("Enter the values for matrix:");
 	for(i = 0; i < row; i++)
  	{
   	    for(j = 0; j < column; j++) 
     	    {
        	  x[i][j] = Sc.nextInt();        	
            }
  	}
	
	System.out.println("The Output of matrix before Transpose is ");
  	for(i = 0; i < row; i++)
    	{
      	    for(j = 0; j < column; j++)
            {
          	  System.out.print(x[i][j]+" ");
            }
            System.out.println(" ");
        }

 	System.out.println("The Output of matrix after Transpose is = ");
  	for(i = 0; i < column; i++)
    	{
      	    for(j = 0; j < row; j++)
            {
                System.out.print(x[j][i]+" ");
            }
            System.out.println(" ");
        }
    }
}
Output :
Enter similar value for rows and columns:
3
3
Enter the values for matrix:
10
20
30
40
50
60
70
80
90

The Output of matrix before Transpose is
10 20 30
40 50 60
70 80 90

The Output of matrix after Transpose is =
10 40 70
20 50 80
30 60 90

Example : An Array program in Java to show whether Matrix is Sparse or Not.

import java.util.Scanner;
class SparseM
{
    public static void main(String args[])
    {
 	int i, j, countzero = 0, countnonzero = 0;
	
 	int x[][] = new int[5][5];
 	
 	Scanner Sc = new Scanner(System.in);	
	System.out.println("Enter 25 values : "); 	
        for(i = 0; i < 5; i++)
        {
            for(j = 0; j < 5; j++) 
    	     {
                 x[i][j] = Sc.nextInt();                 
    	     }
        }

        for(i = 0; i < 5; i++)
        {
 	    for(j = 0; j < 5; j++) 
  	    {
              if(x[i][j] == 0)
    	      {
        	    countzero++; 
    	      }
    	      else
              {
      	            countnonzero++;
    	      }
   	    }
         }
       if(countzero>countnonzero)
       {
           System.out.println("The matrix is Sparse Matrix");
       }
       else
       {
           System.out.println("The matrix is not a Sparse Matrix");
       }
    }
}

Example : An array program in Java to count the total number of odd and even values present in it.

import java.util.Scanner;
class OddEvenCount
{
    public static void main(String[] args) 
    {
        int rows, columns, counteven = 0, countodd = 0;
		
        Scanner Sc = new Scanner(System.in);
        System.out.print("Enter number of rows for matrix:");
        rows = Sc.nextInt();
		
        System.out.print("Enter number of columns for matrix:");
        columns = Sc.nextInt();
		
        int x[][] = new int[rows][columns];
		
        System.out.println("Enter Matrix Elements :");
        for (int i = 0; i < rows; i++) 
        {
            for (int j = 0; j < columns; j++) 
            {
                x[i][j] = Sc.nextInt();
            }
        }
		
        System.out.println("The elements of Matrix are :");
        for (int i = 0; i < rows; i++) 
        {
            for (int j = 0; j < columns; j++) 
            {
                System.out.print(x[i][j] + " ");
            }
            System.out.println();
        }
		
        for (int i = 0; i < rows; i++) 
        {
            for (int j = 0; j < columns; j++) 
            {
                if((x[i][j] % 2) == 0)
                {
                    counteven++;
                }
                else
                {
                    countodd++;
                }
            }
        }
        System.out.println("Total Even values in Matrix are :"+counteven);
        System.out.println("Total Odd values in Matrix are :"+countodd);
    }
}

Output :
Enter number of rows for matrix:3
Enter number of columns for matrix:3
Enter Matrix Elements :
1
2
5
6
3
9
40
50
80
The elements of Matrix are :
1 2 5
6 3 9
40 50 80
Total Even values in Matrix are :5
Total Odd values in Matrix are :4

Example : A matrix program in Java to interchange the diagonal values and display them.

import java.util.Scanner;
class DiagonalChange
{
    public static void main(String[] args) 
    {
        int rows, columns, temp = 0;
		
        Scanner Sc = new Scanner(System.in);
        System.out.print("Enter number of rows in matrix :");
        rows = Sc.nextInt();
		
        System.out.print("Enter number of columns in matrix :");		
        columns = Sc.nextInt();
		
        if (rows == columns) 
        {
            int a[][] = new int[rows][columns];
			
            System.out.println("Enter all the elements of matrix :");
            for (int i = 0; i < rows; i++) 
            {
                for (int j = 0; j < columns; j++) 
                {
                    a[i][j] = Sc.nextInt();
                }
            }
			
            System.out.println("The Entered elements in Matrix are :");
            for (int i = 0; i < rows; i++) 
            {
                for (int j = 0; j < columns; j++) 
                {
                    System.out.print(a[i][j] + " ");
                }
		    System.out.println();
             }
			 
            for(int j = 0; j < columns; j++)
            {
                temp = a[j][j];
                a[j][j] = a[j][columns-1-j];
                a[j][columns-1-j] = temp;
            }
			
            System.out.println("The elements after exchanging the diagonals are ");
            for (int i = 0; i < rows; i++) 
            {
                for (int j = 0; j < columns; j++) 
                {
                    System.out.print(a[i][j] + " ");
                } 
		    System.out.println();
            }
        } 
        else 
        {
            System.out.println("Number of Rows are not equal to number of columns");
        }
    }
}

Output :
Enter number of rows in matrix :3
Enter number of columns in matrix :3
Enter all the elements of matrix :
1
3
6
9
7
8
4
2
5
The Entered elements in Matrix are :
1 3 6
9 7 8
4 2 5
The elements after exchanging the diagonals are
6 3 1
9 7 8
5 2 4

Example : A Java program to show a Jagged Array Concept.

import java.io.*; 
class TDA
 {   
		public static void main(String[] args)
		{         
			int num[][] = new int[3][];   //Jagged Array Declaration
			
			num[0] = new int[3];  
			num[1] = new int[4];  
			num[2] = new int[2];  
        
			int count = 10;  
				for (int i=0; i<num.length; i++)
				{					
					for(int j=0; j<num[i].length; j++)
					{						
					  num[i][j] = count++;
					}
				}   
           
				for (int i=0; i<num.length; i++)
				{  
					for (int j=0; j<num[i].length; j++)
					{  
					   System.out.print(num[i][j] + " ");  
					}  
					System.out.println();  
				}  
		    }  
	
 }

Output : 
10 11 12
13 14 15 16
17 18

NB : Jagged Array - An Array having different number of columns in a row.

Loading

Categories: Java

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.