Practical Coding in Java

Learn to write and validate your own code

Darren Kessner, PhD

(revised September 1, 2025)

Previous: MonkeyTrouble

Coding Exercises: Functions and Testing

1. Vampire

A person is a vampire if she is asleep during waking hours (6:00 to 22:00), or awake during sleeping hours (before 6:00 or after 22:00). Write a class with a static function boolean isVampire(float hour, boolean awake) where hour is the time represented as a float (e.g. 6.5 means 6:30), and awake represents whether the person is awake, returning true if that person is a vampire. Most importantly, write a unit test function and several tests.

2. Good Deal

A store has marked down the prices of many items, but you only want to buy something if the discount is more than 25% (or in other words, the sale price is < 75% of the original price). Write a function boolean goodDeal(double originalPrice, double salePrice) that returns true if you’re getting a good deal on the item. Most importantly, write a unit test function and several tests.

3. (Challenge) Prime Numbers

Write a program to print the prime numbers.

To do this, first write a function isPrime():

static boolean isPrime(int n)
{
    // return true <-> n is prime
}

Write a unit test function and several unit tests for isPrime().

Then in your main() function, loop through the first 100 integers and print only the ones for which isPrime() returns true.


Next: