﻿ Java: All even numbers come before odd numbers in an array

Java Exercises: Rearrange all the elements of an given array of integers so that all the odd numbers come before all the even numbers

Java Basic: Exercise-94 with Solution

Write a Java program to rearrange all the elements of an given array of integers so that all the odd numbers come before all the even numbers.

Pictorial Presentation:

Sample Solution:

Java Code:

``````import java.util.*;
import java.io.*;
public class Exercise94 {
public static void main(String[] args)
{
int[] array_nums = {1, 7, 8, 5, 7, 13, 0, 2, 4, 9};

int i = 0;
System.out.println("Original Array: "+Arrays.toString(array_nums));
while(i < array_nums.length && array_nums[i] % 2 == 0)
i++;

for(int j = i + 1; j < array_nums.length; j++) {
if(array_nums[j] % 2 != 0) {
int temp = array_nums[i];
array_nums[i] = array_nums[j];
array_nums[j] = temp;
i++;
}
}

System.out.println("New Array: "+Arrays.toString(array_nums));
}
}
```
```

Sample Output:

```Original Array: [1, 7, 8, 5, 7, 13, 0, 2, 4, 9]
New Array: [7, 5, 7, 13, 9, 1, 0, 2, 4, 8]
```

Flowchart:

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿

Java: Tips of the Day

countOccurrences

Counts the occurrences of a value in an array.

Use Arrays.stream().filter().count() to count total number of values that equals the specified value.

```public static long countOccurrences(int[] numbers, int value) {
return Arrays.stream(numbers)
.filter(number -> number == value)
.count();
}
```

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