LearnFrenzy
Sign in Take a free test

Arrays in Java · Java Array Programs · Question 4

Move all zeros to the end keeping order in Java Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

Move all zeros in an array to the end while keeping the order of the non-zero elements, in place.

Solution
Main.java
import java.util.Arrays;

public class Main {
    static void moveZeros(int[] a) {
        int pos = 0;
        for (int x : a) if (x != 0) a[pos++] = x;      // compact non-zero values to the front
        while (pos < a.length) a[pos++] = 0;           // fill the rest with zeros
    }

    public static void main(String[] args) {
        int[] a = {0, 5, 0, 3, 12, 0, 7};
        moveZeros(a);
        System.out.println(Arrays.toString(a));
        int[] b = {0, 0, 1};
        moveZeros(b);
        System.out.println(Arrays.toString(b));
    }
}

Output Verified by compiling and running

[5, 3, 12, 7, 0, 0, 0]
[1, 0, 0]

Reading with for-each while writing to an index behind it is safe: the write position never overtakes the read position.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links