w3resource

Java Array Exercises: Move all 0's to the end of an array

Java Array: Exercise-26 with Solution

Write a Java program to move all 0's to the end of an array. Maintain the relative order of the other (non-zero) array elements.

Pictorial Presentation:

Java Array Exercises: Move all 0's to the end of an array

Sample Solution:

Java Code:

import java.util.*;
 public class Exercise26 {
     public static void main(String[] args) throws Exception {
        int[] array_nums = {0,0,1,0,3,0,5,0,6};
         int i = 0;
		System.out.print("\nOriginal array: \n");
		for (int n : array_nums)
            System.out.print(n+"  ");
		
        for(int j = 0, l = array_nums.length; j < l;) {
            if(array_nums[j] == 0)
                j++;
            else {
                int temp = array_nums[i];
                array_nums[i] = array_nums[j];
                array_nums[j] = temp;
                i ++;
                j ++;
            }
        }
        while (i < array_nums.length)
            array_nums[i++] = 0;
		System.out.print("\nAfter moving 0's to the end of the array: \n");
        for (int n : array_nums)
            System.out.print(n+"  ");
			System.out.print("\n");
    }
}

Sample Output:

                                                                              
Original array:                                                        
0  0  1  0  3  0  5  0  6                                              
After moving 0's to the end of the array:                              
1  3  5  6  0  0  0  0  0 

Flowchart:

Flowchart: Java exercises: Move all 0's to the end of an array

Visualize Java code execution (Python Tutor):


Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to find common elements from three sorted (in non-decreasing order) arrays.
Next: Write a Java program to find the number of even and odd integers in a given array of integers.

What is the difficulty level of this exercise?



Java: Tips of the Day

Different between parseInt() and valueOf() in java?

Well, the API for Integer.valueOf(String) does indeed say that the String is interpreted exactly as if it were given to Integer.parseInt(String). However, valueOf(String) returns a new Integer() object whereas parseInt(String) returns a primitive int.

If you want to enjoy the potential caching benefits of Integer.valueOf(int), you could also use this eyesore:

Integer k = Integer.valueOf(Integer.parseInt("123"))

Now, if what you want is the object and not the primitive, then using valueOf(String) may be more attractive than making a new object out of parseInt(String) because the former is consistently present across Integer, Long, Double, etc.

Ref: https://bit.ly/3vRuIPY