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

For each of these exercises, you should write a class, and all functions should be static, like the MonkeyTrouble example above.

Example GoodDeal.java:

class GoodDeal
{
    public static boolean goodDeal(double originalPrice, 
                                   double salePrice)
    {
        // your code here
    }

    public static void testGoodDeal(double originalPrice, 
                                    double salePrice,
                                    boolean expected)
    {
        // your testing code here
    }

    public static void main(String[] args)
    {
        // unit tests
        testGoodDeal(100, 50, true);
        testGoodDeal(100, 80, false);
        // add more unit tests...
    }
}

1. 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 test function and include several unit tests.

2. 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 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 test function and several unit tests.

Challenge: Implement your isVampire() function by returning a single expression built from comparisons and logical operators.

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 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: