Menu
Coddy logo textTech

Recap - Counter & Utility

Part of the Object Oriented Programming section of Coddy's Java journey — lesson 19 of 87.

challenge icon

Challenge

Easy

Let's build a complete system that combines a Counter class for tracking instances with a MathUtils utility class - bringing together everything you've learned about static variables, static methods, static blocks, and constants.

You'll create three files to organize your code:

  • Counter.java: Create a class that tracks how many instances have been created:
    • A private static variable to count total instances
    • A private instance variable id that stores each counter's unique identifier
    • A constructor that increments the total count and assigns the current count as this instance's id
    • A method getId() that returns this counter's unique id
    • A static method getTotalCount() that returns how many Counter objects have been created
  • MathUtils.java: Create a utility class with only static members (never instantiated):
    • A public constant PI with value 3.14159
    • A public constant HALF with value 0.5
    • A static method square(int n) that returns n squared
    • A static method cube(int n) that returns n cubed
    • A static method circleArea(double radius) that returns PI * radius * radius
  • Main.java: Demonstrate both classes working together. You'll receive two inputs: a number for math operations and a count of how many Counter objects to create. Print the following:
    • Square: [value]
    • Cube: [value]
    • Circle area (radius=[number]): [value] (area formatted to 2 decimal places)
    • For each Counter created, print: Counter [id] created
    • Finally: Total counters: [count]

You will receive two inputs: a number (int) for the math calculations, and a count (int) for how many Counter objects to create.

Remember to access static members through the class name (like MathUtils.PI and Counter.getTotalCount()), and use String.format("%.2f", value) for formatting decimal values.

Try it yourself

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int number = scanner.nextInt();
        int count = scanner.nextInt();
        
        // TODO: Use MathUtils static methods to calculate and print:
        // - Square: [value]
        // - Cube: [value]
        // - Circle area (radius=[number]): [value] (formatted to 2 decimal places)
        
        // TODO: Create 'count' number of Counter objects
        // For each Counter created, print: Counter [id] created
        
        // TODO: Print the total number of counters created
        // Total counters: [count]
    }
}

All lessons in Object Oriented Programming