Practical Coding in Java

Learn to write and validate your own code

Darren Kessner, PhD

(revised October 21, 2025)

Previous: Generate

Coding Exercises: Array Algorithms

You can do these exercises with either for or for-each loops. Practice both!

Finding a maximum value

Write a function that takes an array of double values as input and returns the maximum value. Write a test function and several unit tests.

findMax(ArrayList({1.0, 2.1, 5.3})) -> 5.3
findMax(ArrayList({-35.0, 90.1, 0.0, 6.7})) -> 90.1

Filtering a list

Write a function that takes an ArrayList of integer scores, and returns an ArrayList representing the scores below 50.

Demonstrate that the function works. Optional: write unit tests.

filterBadScores(ArrayList({51, 49, 37, 100})) -> ArrayList({49, 37})
filterBadScores(ArrayList({92, 89, 90, 99})) -> ArrayList({})

Transforming a list

(Re)write a reverse() function that returns the reverse of a single string. Then, using this function, write a function reverseAll() takes an array of Strings and returns a new array containing the same strings, but with each string reversed.

Demonstrate that the function works. Optional: write unit tests.

reverseAll({"abcd", "xyz"}) -> {"dcba", "zyx"}
reverseAll({"1234", "5678"}) -> {"4321", "8765"}
reverseAll({"racecar", "tacocat", "izzi"}) -> {"racecar", "tacocat", "izzi"}

Constructing a sequence

Write a function that takes a single integer n and returns an array of integers containing the first n terms of the Fibonacci sequence.

fibonacci(2) -> {1, 1}
fibonacci(3) -> {1, 1, 2}
fibonacci(4) -> {1, 1, 2, 3}
fibonacci(5) -> {1, 1, 2, 3, 5}

Demonstrate that the function works. Optional: write unit tests.

Bonus Challenge: Generate prime numbers

Write a function that returns the first n prime numbers in an array or ArrayList.

prime(3) -> {2, 3, 5}
prime(5) -> {2, 3, 5, 7, 11}

Next: