Java Program to Move All the 0’s (zero elements) to the End of the Array

In this article we will see how we can take all the zeros present in array to the last of the array using Java programming language.

Java Program to Move All the 0’s (zero elements) to the End 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

Let’s see different ways to move all the 0’s (zero elements) to the end of the array.

Method-1: Java Program to Move All the 0’s (zero elements) to the End of the Array By Static Initialization of Array Elements

Approach:

  1. Declare and initialize an array.
  2. Initialize two pointers, start = 0 and end = arr.length–1.
  3. While start <= end, if element at end is 0, end--.
  4. If element at start is not 0, start++,
  5. Otherwise(arr[start] != 0) swap arr[start] and arr[end].
  6. start++, end-- and repeat till while loop satisfies.

Program:

public class Main 
{
    public static void main(String[] args) 
    {
        // initialize the array
        int[] nums = { 0, 1, 0, 3, 12, 2 };
        System.out.println("The original array is : ");
        printArray(nums);
        // calling the moveZeros() method
        moveZeros(nums);
        
        System.out.println("\nAfter taking all the zeros to last : ");
        printArray(nums);
   
    }

    //moveZeros() method to take all zeros tolast of array
    static void moveZeros(int[] arr) 
    {
        // declaring start and end pointers
        int start = 0;
        int end = arr.length - 1;
        while (start <= end) {
            // if element at end is 0, end--
            if (arr[end] == 0) {
                end--;
            }
            // if element at start is not 0, start++
            if (arr[start] != 0) {
                start++;
            } else {
                // otherwise, swap the elements
                swap(arr, start, end);
                start++;
                end--;
            }

        }
    }

    //swap() method to swap the elements
    static void swap(int[] arr, int i, int j) 
    {
        // logic to swap
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    
    //printArray() method to print the array
    static void printArray(int[] arr)
    {
        // printing array
        for (int i=0; i<arr.length; i++) 
        {
            System.out.print(arr[i] + " ");
        }
    }
}


Output:

The original array is : 
0 1 0 3 12 2 
After taking all the zeros to last : 
2 1 12 3 0 0

Method-2: Java Program to Move All the 0’s (zero elements) to the End of the Array By Dynamic Initialization of Array Elements

Approach:

  1. Take the input of array size from the user.
  2. Take the input of array elements from the user.
  3. Initialize two pointers, start = 0 and end = arr.length–1.
  4. While start <= end, if element at end is 0, end--.
  5. If element at start is not 0, start++,
  6. Otherwise(arr[start] != 0) swap arr[start] and arr[end].
  7. start++, end-- and repeat till while loop satisfies.

Program:

import java.util.*;

public class Main 
{
    public static void main(String[] args) 
    {
        // creating scanner class object
        Scanner sc = new Scanner(System.in);
        
        // taking input from user for size of array
        System.out.println("Enter number of elements in the array: ");
        int n = sc.nextInt();
        // initializing array with given size
        int[] nums = new int[n];
        System.out.println("Enter array elements: ");
        // taking input from user for array elements
        for (int i = 0; i < n; i++) {
            nums[i] = sc.nextInt();
        }
        System.out.println("The original array is : ");
        printArray(nums);
        
        // calling the moveZeros() method
        moveZeros(nums);
        
        System.out.println("\nAfter taking all the zeros to last : ");
        printArray(nums);
   
    }

    //moveZeros() method to take all zeros tolast of array
    static void moveZeros(int[] arr) 
    {
        // declaring start and end pointers
        int start = 0;
        int end = arr.length - 1;
        while (start <= end) {
            // if element at end is 0, end--
            if (arr[end] == 0) {
                end--;
            }
            // if element at start is not 0, start++
            if (arr[start] != 0) {
                start++;
            } else {
                // otherwise, swap the elements
                swap(arr, start, end);
                start++;
                end--;
            }

        }
    }

    //swap() method to swap the elements
    static void swap(int[] arr, int i, int j) 
    {
        // logic to swap
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    
    //printArray() method to print the array
    static void printArray(int[] arr)
    {
        // printing array
        for (int i=0; i<arr.length; i++) 
        {
            System.out.print(arr[i] + " ");
        }
    }
}


Output:

Enter number of elements in the array: 5
Enter array elements: 2 0 1 0 4 
The original array is : 
2 0 1 0 4 
After taking all the zeros to last : 
2 4 1 0 0

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.

Leave a Comment