Java Exercises: Move every zero to the right side of a given array of integers
Java Basic: Exercise-167 with Solution
Write a Java program to move every zero to the right side of a given array of integers.
Pictorial Presentation:

Sample Solution:
Java Code:
import java.util.*;
public class Solution {
public static int[] move_zero(int[] nums) {
if (nums == null) {
throw new IllegalArgumentException("Null array!");
}
boolean swap = true;
while (swap) {
swap = false;
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] == 0 && nums[i + 1] != 0) {
swap(nums, i, i + 1);
swap = true;
}
}
}
return nums;
}
private static void swap(int[] nums, int a, int b) {
int temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
}
public static void main(String[] args) {
int[] nums = {0,3,4,0,1,2,5,0};
System.out.println("\nOriginal array: "+Arrays.toString(nums));
int[] result = move_zero(nums);
System.out.println("\nResult: " + Arrays.toString(result));
}
}
Sample Output:
Original array: [0, 3, 4, 0, 1, 2, 5, 0] Result: [3, 4, 1, 2, 5, 0, 0, 0]
Flowchart:

Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to transform a given integer to String format.
Next: Write a Java program to multiply two given integers without using the multiply operator(*).
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
Java: ConvertInputStreamToString
Converts InputStream to a String.
public static String convertInputStreamToString(final InputStream in) throws IOException { ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) != -1) { result.write(buffer, 0, length); } return result.toString(StandardCharsets.UTF_8.name()); }
Ref: https://bit.ly/2N1GDss
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises