Practical Coding in Java

Learn to write and validate your own code

Darren Kessner, PhD

(revised September 1, 2025)

Previous: Binimate

Coding Exercises: Loops and Algorithms

Implement the following functions, including unit tests. A few example tests are shown (commented). Add at least 3 more tests of your own for each function.

1. Sum of squares

Write a function sumOfSquares(int n) that calculates and returns the sum \(1^2 + 2^2 + 3^2 ... + n^2\).

sumOfSquares(1) -> 1
sumOfSquares(2) -> 1+4 = 5
sumOfSquares(3) -> 1+4+9 = 14

2. Count occurrences

Write a function that counts the number of times one string occurs in another.

countOccurrences("Mississippi", "iss") -> 2
countOccurrences("banananana", "na") -> 4

3. Reverse

Write a function that returns the reverse of a string.

reverse("bad") -> "dab"
reverse("Hello, world!") -> "!dlrow ,olleH"
reverse("tacocat") -> "tacocat"

4. Factorial

Implement the function factorial(int n) that calculates the factorial \(n! = n \cdot (n-1) \, \cdot \, ... \, \cdot \, 1\).

factorial(0) -> 1
factorial(1) -> 1
factorial(2) -> 2*1 = 2
factorial(3) -> 3*2*1 = 6
factorial(4) -> 4*3*2*1 = 24
factorial(5) -> 5*4*3*2*1 = 120

5. Interlace

Write a function to interlace 2 strings.

interlace("abc", "123") -> "a1b2c3"
interlace("bed", "ras") -> "breads"

6. Find second occurrence

Write a function to find the position of the 2nd “a” in a string.

find2nd("banana") -> 3
find2nd("happy birthday") -> 12

7. Add “na”

Write a function to add a specified number of “na” strings to “ba”.

addNa(0) -> "ba"
addNa(1) -> "bana"
addNa(2) -> "banana"
addNa(3) -> "bananana"

8. Powers of 2

Write a function to calculate the sum of powers of 2.

sumPowers(0) -> 0
sumPowers(1) -> 0+1 = 1
sumPowers(2) -> 0+1+2 = 3
sumPowers(3) -> 0+1+2+4 = 7
sumPowers(4) -> 0+1+2+4+8 = 15 

Reading


Next: