Fraction Class in Java: Solution, 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
- Common denominator: a*d + b*c / b*d
- Find GCD to simplify
- Divide both by GCD
Validated solution
Reveal Java solution
class Fraction {
final int numerator, denominator;
Fraction(int numerator, int denominator) {
if (denominator == 0) throw new IllegalArgumentException("zero denominator");
int gcd = gcd(Math.abs(numerator), Math.abs(denominator));
this.numerator = numerator / gcd; this.denominator = denominator / gcd;
}
Fraction add(Fraction other) { return new Fraction(numerator * other.denominator + other.numerator * denominator, denominator * other.denominator); }
static int gcd(int a, int b) { while (b != 0) { int r = a % b; a = b; b = r; } return a; }
public String toString() { return numerator + "/" + denominator; }
}
public class Main { public static void main(String[] args) { System.out.println(new Fraction(1, 2).add(new Fraction(1, 3))); } }How to approach the problem
Fraction addition uses a common denominator, then the constructor normalizes the result with GCD. Keeping normalization in one place means every new Fraction has the same representation invariant.
Approach
- Reject a zero denominator.
- Cross-multiply to add numerators.
- Reduce the new fraction in the constructor.
Time and space complexity
Time: O(log(min(a, b))) for normalization. Space: O(1).
Edge cases to test
- A negative denominator should be normalized consistently in a fuller implementation.
- Cross-products can overflow int for large inputs.
Common mistakes
- Adding numerators and denominators directly.
- Allowing a denominator of zero.
Follow-up challenge
Normalize signs and compare fractions without converting to double.
Related OOP Basics exercises
- Practice Employee Salary Calculator in Java
- Practice Time Class in Java
- Practice Temperature Converter in Java
Practice all OOP Basics exercises · Run this idea in the Java compiler