0
0
JavaProgramBeginner · 2 min read

Java Program to Move Zeros to End of Array

Use a loop to shift all non-zero elements forward and then fill the rest of the array with zeros; in Java, this can be done by iterating with an index and swapping zeros to the end.
📋

Examples

Input[0, 1, 0, 3, 12]
Output[1, 3, 12, 0, 0]
Input[1, 2, 3, 4]
Output[1, 2, 3, 4]
Input[0, 0, 0, 0]
Output[0, 0, 0, 0]
🧠

How to Think About It

Think of moving through the array and picking out all the numbers that are not zero, placing them at the front in order. After that, fill the remaining positions with zeros. This keeps the order of non-zero numbers and pushes all zeros to the end.
📐

Algorithm

1
Start with a pointer at the beginning of the array to track the position for non-zero elements.
2
Loop through each element in the array.
3
If the current element is not zero, place it at the pointer's position and move the pointer forward.
4
After the loop, fill all remaining positions from the pointer to the end of the array with zeros.
5
Return or print the modified array.
💻

Code

java
public class MoveZeros {
    public static void moveZerosToEnd(int[] arr) {
        int index = 0; // position for next non-zero
        for (int num : arr) {
            if (num != 0) {
                arr[index++] = num;
            }
        }
        while (index < arr.length) {
            arr[index++] = 0;
        }
    }

    public static void main(String[] args) {
        int[] arr = {0, 1, 0, 3, 12};
        moveZerosToEnd(arr);
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}
Output
1 3 12 0 0
🔍

Dry Run

Let's trace the array [0, 1, 0, 3, 12] through the code

1

Initialize index

index = 0

2

Check first element (0)

0 is zero, do nothing, index stays 0

3

Check second element (1)

1 is not zero, place at arr[0], index becomes 1, array now [1, 1, 0, 3, 12]

4

Check third element (0)

0 is zero, do nothing, index stays 1

5

Check fourth element (3)

3 is not zero, place at arr[1], index becomes 2, array now [1, 3, 0, 3, 12]

6

Check fifth element (12)

12 is not zero, place at arr[2], index becomes 3, array now [1, 3, 12, 3, 12]

7

Fill remaining with zeros

arr[3] = 0, arr[4] = 0, final array [1, 3, 12, 0, 0]

IterationCurrent ElementIndexArray State
100[0, 1, 0, 3, 12]
211[1, 1, 0, 3, 12]
301[1, 1, 0, 3, 12]
432[1, 3, 0, 3, 12]
5123[1, 3, 12, 3, 12]
Fill zeros-5[1, 3, 12, 0, 0]
💡

Why This Works

Step 1: Collect non-zero elements

The code moves through the array and copies each non-zero element to the front, keeping their order with arr[index++] = num.

Step 2: Fill zeros at the end

After placing all non-zero elements, the remaining positions are filled with zeros using a while loop.

Step 3: In-place modification

The array is changed directly without extra arrays, making it efficient in space.

🔄

Alternative Approaches

Using extra array
java
public class MoveZeros {
    public static void moveZerosToEnd(int[] arr) {
        int[] temp = new int[arr.length];
        int index = 0;
        for (int num : arr) {
            if (num != 0) {
                temp[index++] = num;
            }
        }
        while (index < arr.length) {
            temp[index++] = 0;
        }
        for (int i = 0; i < arr.length; i++) {
            arr[i] = temp[i];
        }
    }
}
Uses extra space equal to array size but keeps code simple.
Swapping zeros with non-zeros
java
public class MoveZeros {
    public static void moveZerosToEnd(int[] arr) {
        int lastNonZeroFoundAt = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] != 0) {
                int temp = arr[lastNonZeroFoundAt];
                arr[lastNonZeroFoundAt] = arr[i];
                arr[i] = temp;
                lastNonZeroFoundAt++;
            }
        }
    }
}
Swaps elements in place, useful if you want to minimize writes.

Complexity: O(n) time, O(1) space

Time Complexity

The algorithm loops through the array once, so it runs in linear time relative to the array size.

Space Complexity

It modifies the array in place using only a few extra variables, so space is constant.

Which Approach is Fastest?

The in-place method with a single pass is fastest and most memory efficient compared to using extra arrays.

ApproachTimeSpaceBest For
In-place overwriteO(n)O(1)Memory efficiency and speed
Extra arrayO(n)O(n)Simplicity and clarity
Swapping zerosO(n)O(1)Minimizing writes, preserving order
💡
Use a single pass to move non-zero elements forward, then fill zeros after.
⚠️
Trying to swap zeros immediately without tracking positions can cause incorrect order.