Home »
Java Programs »
Java Array Programs
Java program to move all zero at the end of the array
In this java program, we are implementing a logic in which all zeros (0) of given array will be moved at the end of the array.
By IncludeHelp Last updated : December 23, 2023
Problem statement
Given an integer array with zeros (0's) and we have to move all zeros at the end of the array using java program.
Example
Input array: 5, 1, 6, 0, 0, 3, 9, 0, 6, 7, 8, 12, 10, 0, 2
After moving 0 at the end
Output array: 5, 1, 6, 3, 9, 6, 7, 8, 12, 10, 2, 0, 0, 0, 0
Program to move zeros at the end of the array in java
public class MoveZeros {
static void moveZeroElementToEnd(int[] arr) {
// declare and initialize.
int size = arr.length;
int count = 0;
// access all array elements.
for (int i = 0; i < size; i++) {
if (arr[i] != 0) {
arr[count++] = arr[i];
}
}
while (count < size)
arr[count++] = 0;
}
public static void main(String[] args) {
// take default elements in array.
int[] arr = {
5,
1,
6,
0,
0,
3,
9,
0,
6,
7,
8,
12,
10,
0,
2
};
moveZeroElementToEnd(arr);
// print elements after moving 0's to end
System.out.print("Array after moving zeros to end : ");
for (int i = 0, size = arr.length; i < size; i++)
System.out.print(arr[i] + " ");
}
}
Output
Array after moving zeros to end : 5 1 6 3 9 6 7 8 12 10 2 0 0 0 0
Java Array Programs »