Arrays in Java

Introduction to Arrays

Passing Arrays to Methods and Returning Arrays

Arrays Class Methods in Java

Introduction to Arays in Java

Arrays in Java are data structures that can store a collection of elements of the same type. Arrays are fixed in size, which means that once you create an array, you cannot change its size.

To create an array, you need to specify the type of elements that the array will store and the size of the array. For example, the following code creates an array of 10 integers:


  int[] numbers = new int[10];
 

Once you have created an array, you can access the elements of the array using their index. The index of an element is a number that starts at 0 and goes up to one less than the size of the array. For example, the following code accesses the first element of the numbers array:


  int firstNumber = numbers[0];
 

You can also use a for loop to iterate over the elements of an array. For example, the following code prints all of the elements of the numbers array to the console:


  for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
  }
 

Arrays are a powerful data structure that can be used to store and manipulate collections of data. They are commonly used in Java programs for tasks such as:

  • Storing data for processing, such as the scores for a game or the prices of items in a store.
  • Passing data between methods and objects.
  • Implementing other data structures, such as linked lists and trees.
Here are some tips for using arrays effectively:
  • Use proper indentation and spacing to make your code easier to read and maintain.
  • Add comments to your code to explain what your arrays are doing.
  • Be careful not to access elements outside of the bounds of the array.

Exercises

Code for Writing and Reading values from an array


import java.util.*;
public class first 
{
  public static void main(String[] args) 
  {
    //Reading the number of lines from the user
    System.out.println("Enter three numbers");
    Scanner input = new Scanner(System.in);
    int a[] = new int[3];
      for(int i=0;i<3;i++)
      {
        a[i]=input.nextInt();
      }
      for(int i=0;i<3;i++)
      {
        System.out.println(a[i]);
      }
  }
  
} 

Sorting an Array of Integers using bubble sort


  package morningsession;
  import java.util.*;
  public class first 
  {
  public static void main(String[] args) 
  {
    //Reading the number of lines from the user
    System.out.println("Enter three numbers");
    Scanner input = new Scanner(System.in);
    int a[] = new int[5];
    int temp;
      for(int i=0;i<a.length;i++)
      {
        a[i]=input.nextInt();
      }
      for(int i=0;i<a.length;i++)
      {
        for(int j=0;j<a.length-1-i;j++)
        {
          if(a[j]>a[j+1])
          {
              temp=a[j];
              a[j]=a[j+1];
              a[j+1]=temp;
          }
        }
      }
      for(int i=0;i<a.length;i++)
      {
        System.out.println(a[i]);
      }
  }
  
  } 

Write a Java Program for Linear searching an array of Integers


  package morningsession;
  import java.util.*;
  public class first 
  {
    public static void main(String[] args) 
    {
      //Reading the number of lines from the user
      System.out.println("Enter three numbers");
      Scanner input = new Scanner(System.in);
      int a[] = new int[5];
      int temp;
      boolean found=false;
        for(int i=0;i<a.length;i++)
        {
          a[i]=input.nextInt();
        }
        System.out.println("Enter the search element");
        int search = input.nextInt();
        for(int i=0;i<a.length;i++)
        {
          if(a[i]==search)
          {
            System.out.println("Element found");
            found=true;
            break;
          }
        }
        if(found==false)
        {
          System.out.println("No such element exists");
        }
    }
    
  } 

Displaying only unique elements from an array


  package morningsession;
  import java.util.*;
  public class first 
  {
  public static void main(String[] args) 
  {
    //Reading the number of lines from the user
    System.out.println("Enter numbers");
    Scanner input = new Scanner(System.in);
    int a[] = new int[5];
    int j=0;
    for(int i=0;i<a.length;i++)
      {
        a[i]=input.nextInt();
      }
    for(int i=0;i<a.length-1;i++)
    {
      if(a[i]!=a[i+1])
      {
        j++;
        a[j]=a[i+1];
      }
    }
      for(int i=0;i<=j;i++)
      {
        System.out.println(a[i]);
      }
    
  }	
  } 

Program for Reversing the contents inside an array


  import java.util.*;
  public class first 
  {
    public static void main(String[] args) 
    {
      //Reading the number of lines from the user
      System.out.println("Enter numbers");
      Scanner input = new Scanner(System.in);
      int a[] = new int[5];
      int temp=0;
      for(int i=0;i<a.length;i++)
        {
          a[i]=input.nextInt();
        }
      for(int i=0;i<a.length/2;i++)
      {
        temp=a[i];
        a[i]=a[a.length-i-1];
        a[a.length-i-1]=temp;
      }
        for(int i=0;i<a.length;i++)
        {
          System.out.println(a[i]);
        }
      
    }	
  }  

Read 6 integers from an user and store that in an array. Get the index as input from the user. Display the elements in the array in the reverse by using the index.


package javaprogrammingdemo;
import java.util.Scanner;
public class javalabclass{
    public static void main(String args[]) 
    {
    	  Scanner sc = new Scanner(System.in);
          
          int arr[] = new int[6];
          
          System.out.println("Enter six elements :");
          for(int i=0;i<arr.length;i++)
          {
              arr[i] = sc.nextInt();
          }
          
          System.out.println("Enter the index : ");
          int reverseIndex = sc.nextInt();
          
          System.out.println("Reversed : ");
          for(int j=reverseIndex;j>=0;j--)
          {
              System.out.print(arr[j]+" ");
          }
    }
}

Output
Enter six elements :
1
2
3
4
5
6
Enter the index : 
2
Reversed : 
3 2 1  

Sum the numbers in an array by geting the number of elements in the array from the user


  package javaprogrammingdemo;
  import java.util.Scanner;
  public class javalabclass{
      public static void main(String args[]) 
      {
         Scanner sc = new Scanner(System.in);
           System.out.println("Enter the number of elements : ");
           int count = sc.nextInt();
           
           int Loan_Amount[] = new int[count];
           
           System.out.println("Enter the numbers :");
           for(int i=0;i<Loan_Amount.length;i++)
           {
               Loan_Amount[i] = sc.nextInt();
           }
           
           int sumArr = 0;
           for(int j=0;j<Loan_Amount.length;j++)
           {
               sumArr += Loan_Amount[j];
           }
           
           System.out.println("Final sum is :"+sumArr);
      }
  }
  
  output
  Enter the number of elements : 
  4
  Enter the numbers :
  1
  1
  1
  1
  Final sum is :4 

Read an array of characters from the user and store it a character array. Traverse the array and display the count of vowels.


  package javaprogrammingdemo;
  import java.util.Scanner;
  public class javalabclass{
      public static void main(String args[]) 
      {
         Scanner sc = new Scanner(System.in);
           System.out.println("Enter the number of elements :");
           int count = sc.nextInt();
           
           char arr[] = new char[count];
           
           System.out.println("Enter the elements : ");
           for(int i=0;i<arr.length;i++)
           {
               arr[i] = sc.next().charAt(0);
           }
           
           int vowelCount = 0;
           
           for(int j=0;j<arr.length;j++)
           {
               if(arr[j]=='A' || arr[j]=='E' || arr[j]=='I' || arr[j]=='O' || arr[j]=='U' || arr[j]=='a' || arr[j]=='e' || arr[j]=='i' || arr[j]=='o' || arr[j]=='u')
               {
                   vowelCount++;
               }
           }
           
           System.out.println("The final vowel count is : "+vowelCount);
      }
  }
  
  output
  Enter the number of elements :
  4
  Enter the elements : 
  a
  b
  e
  o
  The final vowel count is : 3 

Binary Search an array using Array Class Methods


  package testProject;
  import java.util.Arrays;
  public class testProject {
      
    public static void main(String[] args) {		
        
      int[] a = {3,4,5,1,2};
      System.out.println(Arrays.binarySearch(a, 4));
      
    }
  }
  
  output 
  1 
  
 //If the element is not present then returns a negative value  

Compare two arrays lexographically using compare(array 1, array 2)


//Both arrays are equal
package testProject;
import java.util.Arrays;
public class testProject {
    
	public static void main(String[] args) {		
      
		int a[] = {1,2,3,4};
		int b[] = {1,2,3,4};
        System.out.println(Arrays.compare(a, b));
	}
}

output
0 (both arrays are equal lexographically)

//Array1 is greater than Array2
package testProject;
import java.util.Arrays;
public class testProject {
    
	public static void main(String[] args) {		
      
		int a[] = {2,2,3,4};
		int b[] = {1,2,3,4};
        System.out.println(Arrays.compare(a, b));
	}
}

output
1

//Array1 is lesser than Array2
package testProject;
import java.util.Arrays;
public class testProject {
    
	public static void main(String[] args) {		
      
		int a[] = {1,2,3,4};
		int b[] = {2,2,3,4};
        System.out.println(Arrays.compare(a, b));
	}
}

output
-1 

Code for finding mismatch between two Arrays using Mismatch Function


  package testProject;
  import java.util.Arrays;
  public class testProject {
      
    public static void main(String[] args) {		
        
      int a[] = {1,2,3,4};
      int b[] = {2,2,3,4};
          System.out.println(Arrays.mismatch(a, b));
    }
  }
  
  Output (when both arrays mismatch in index 0)
  0 
  
  
  //When no mismatch is present
  package testProject;
  import java.util.Arrays;
  public class testProject {
      
    public static void main(String[] args) {		
        
      int a[] = {1,2,3,4};
      int b[] = {1,2,3,4};
          System.out.println(Arrays.mismatch(a, b));
    }
  }
  
  output (Negative Value returned)
  -1
   If there is no mismatch the output is -1  

Code for sorting an array using Array Class methods


package testProject;
import java.util.Arrays;
public class testProject {
    
	public static void main(String[] args) {		
      
		int a[] = {3,2,1,4};
		Arrays.sort(a);
		for(int i : a)
		{
			System.out.println(i);
		}
	}
} 

Code for sorting an array using from Index and to Index


  package testProject;
  import java.util.Arrays;
  public class testProject {
      
    public static void main(String[] args) {		
        
      int a[] = {1,2,3,6,4,5};
      Arrays.sort(a,3,a.length);
      for(int i : a)
      {
        System.out.println(i);
      }
    }
  } 

Code for Sorting an array in the reverse


package testProject;
import java.util.Arrays;
import java.util.Collections;
public class testProject {
    
	public static void main(String[] args) {		
      
	    Integer a[] = {1,2,3,6,4,5};
		Arrays.sort(a,Collections.reverseOrder());
		for(int i : a)
		{
			System.out.println(i);
		}
	}
}