Back to Java Course

Java Course

screenshot of the app

Arrays -> Random Access

An array is group of like typed variables and of fixed size.

An array is an index collection of fixed no of homogeneous data elements. The main advantage of array is we can represent multiple value by using single variable, so that readability of code will be improved.

For example,

int a[]= new int[10]; a[0]=1; System.out.println(Arrays.toString(a));

Output

[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]

By default 0 values are present in an int array.

Iterating an Array

int values[]={12,-2,3,10}; for(int i=0;i<values.length;i++){ System.out.println(values[i]); }
  • For comparing two arrays we can use Arrays.equals(a1,a2);
  • For comparing two arrays of arrays we can use Arrays.deepEquals(a1,a2);
  • To print an array we can use Arrays.toString(a);
  • To sort an array we can use Arrays.sort(a);
  • Binary search in an sorted array we can use Arrays.binarySearch(int[] a,int key) where key is the value being searched for; the method returns its index.
  • To copy an array we can use Arrays.copyOf(int[] original,int newLength)
  • To convert an array to List we can use Arrays.asList(a)

Limitation of Arrays

  • Need to know size in advance. Too small size cannot add more elements where as Too large size is waste of space.

  • We cannot insert/remove the elements infront of others except at the end.

  • some operations like search will be slow.

public boolean contains(int[] nums,int target){ for(int i=0;i<nums.length;i++){ if(nums[i]==target){ return true; } } return false; }

Array Programs

Write a java program to find duplicate element in an array

public class DuplicateInArray { public static void main(String[] args) { int[] array = {1,1,2,3,4,5,6,7,8,8}; Set<Integer> set = new HashSet<Integer>(); for(int i = 0; i<array.length ; i++) { //If same integer is already present then add method will return FALSE if(set.add(array[i]) == false) { System.out.println("Duplicate element found : " + array[i]); } } } }

Output

Duplicate element found : 1

Duplicate element found : 8

Write a java program to find second largest number in an array

public class SecondLargestInArrayExample{ public static int getSecondLargest(int[] a, int total){ int temp; for (int i = 0; i < total; i++) { for (int j = i + 1; j < total; j++) { if (a[i] > a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } } return a[total-2]; } public static void main(String args[]){ int a[]={1,2,5,6,3,2}; int b[]={44,66,99,77,33,22,55}; System.out.println("Second Largest: "+getSecondLargest(a,6)); System.out.println("Second Largest: "+getSecondLargest(b,7)); } }

Output

Second Largest: 5

Second Largest: 77

How to find missing number in the array

public class MissingNumber{ public static void main(String[] args){ int total_num; int[] numbers =new int[]{1,2,3,4,6,7}; total_num=7; int expected_num_sum=(total_num*(total_num+1))/2; int num_sum=0; for(int i: numbers){ num_sum+=i; } System.out.print(expected_num_sum-num_sum); System.out.print("\n"); } }

How to find number occuring odd number of times in an array

public class OddOccuringNumber { public static int findNumber(int [] A){ int x=0; for(int i=0;i<A.length;i++){ x= x^A[i]; } return x; } public static void main(String[] args) { int[] A = { 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7 }; System.out.println("Element appearing odd number of times: " + findNumber(A)); } }

Output

Element appearing odd number of times: 5

Write a java program to count occurrences of each element in an array

public class Count_Occurrence { public static void main(String[]args) { int n, x, count =0, i=0; Scanner s =new Scanner(System.in); System.out.print("Enter no. of elements you want in array:"); n =s.nextInt(); int a[]=new int[n]; System.out.println("Enter all the elements:"); for(i=0;i< n;i++){ a[i]=s.nextInt(); } System.out.print("Enter the element of which you want to count number of occurrences:"); x =s.nextInt(); for(i=0;i< n;i++){ if(a[i]== x){ count++; } } System.out.println("Number of Occurrence of the Element:"+count); } }

Output

$ javac Count_Occurrence.java

$ java Count_Occurrence

Enter no. of elements you want in array:5

Enter all the elements:

2

3

3

4

3

Enter the element of which you want to count number of occurrences:3

Number of Occurrence of the Element:3

How to find the missing element in integer array of 1 to 7

class GFG { static int search(int ar[],int size){ int a = 0, b = size - 1; int mid = 0; while((b - a) > 1) { mid = (a + b) / 2; if((ar[a] - a) != (ar[mid] - mid)) b = mid; else if((ar[b] - b) != (ar[mid] - mid)) a = mid; } return(ar[mid] + 1); } // Driver Code public static void main (String[] args) { int ar[] = { 1, 2, 3, 4, 5, 6, 8}; int size = ar.length; System.out.println("Missing number: "+ search(ar, size)); } }

Output

Missing number: 7

How to cut or remove an element from the array

public class RemoveElement{ public static void main(String[] args){ int[] my_array={25,14,56,15,36,56,77,18,29,49}; System.out.println("Original Array : "+Arrays.toString(my_array)); // Remove the second element (index->1, value->14) of the array int removeIndex=1; for(int i=removeIndex;i<my_array.length-1;i++){ my_array[i]=my_array[i+1]; } // We cannot alter the size of an array , after the removal, the last and second last element in the array will exist twice System.out.println("After removing the second element: "+Arrays.toString(my_array)); } }

Output

Original Array : [25, 14, 56, 15, 36, 56, 77, 18, 29, 49]

After removing the second element: [25, 56, 15, 36, 56, 77, 18, 29, 49, 49]

How to get largest and smallest number in an array

public class FindLargestSmallestNumber { public static void main(String[] args) { //array of 10 numbers int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23}; //assign first element of an array to largest and smallest int smallest = numbers[0]; int largetst = numbers[0]; for(int i=1; i<numbers.length; i++) { if(numbers[i] >largetst) largetst = numbers[i]; else if (numbers[i] < smallest) smallest = numbers[i]; } System.out.println("Largest Number is : " + largetst); System.out.println("Smallest Number is : " + smallest); } }

Output

Largest Number is : 98

Smallest Number is : 23