Fraction Class in Java: Explanation & Practice

Create a Fraction class with arithmetic operations

Problem summary

Create a Fraction class that can add two fractions and simplify the result.

Starter code

// Create Fraction class with:
// - int numerator, denominator
// - Fraction add(Fraction other)
// - void simplify() using GCD
// - String toString() as "num/den"

public class Main {
    public static void main(String[] args) {
        // Test case 1: 1/2 + 1/3
        // Print: <result>
    }
}

Expected output and test cases

  • 1/2 + 1/3 = 5/6
    5/6
  • 1/2 + 1/2 = 1
    1/1
  • 1/4 + 1/2 = 3/4
    3/4

Hints

  1. Common denominator: a*d + b*c / b*d
  2. Find GCD to simplify
  3. Divide both by GCD

Related OOP Basics exercises

Practice all OOP Basics exercises · Run this idea in the Java compiler