Temperature Converter in Java: Solution, Explanation & Practice
Create a temperature conversion class
Problem summary
Create a Temperature class that converts between Celsius, Fahrenheit, and Kelvin.
Starter code
// Create Temperature class with:
// - double celsius
// - double toFahrenheit() - C * 9/5 + 32
// - double toKelvin() - C + 273.15
// - static Temperature fromFahrenheit(double f)
public class Main {
public static void main(String[] args) {
// Test case 1: 25 Celsius
// Print: C: <c>, F: <f>, K: <k>
}
}Expected output and test cases
- Convert 25C
C: 25.0, F: 77.0, K: 298.15
- Freezing point
C: 0.0, F: 32.0, K: 273.15
- Boiling point
C: 100.0, F: 212.0, K: 373.15
Hints
- F = C * 9/5 + 32
- K = C + 273.15
- From F: C = (F - 32) * 5/9
Validated solution
Reveal Java solution
class Temperature {
private final double celsius;
Temperature(double celsius) { this.celsius = celsius; }
double fahrenheit() { return celsius * 9 / 5 + 32; }
double kelvin() { return celsius + 273.15; }
}
public class Main {
public static void main(String[] args) {
Temperature temperature = new Temperature(25);
System.out.printf("C: 25.0, F: %.1f, K: %.2f%n", temperature.fahrenheit(), temperature.kelvin());
}
}How to approach the problem
Store one canonical unit, Celsius, and derive Fahrenheit and Kelvin from it. This avoids the drift and ambiguity that come from keeping three independently mutable values.
Approach
- Choose one source-of-truth unit.
- Implement each conversion as a pure calculation.
- Format only at the presentation boundary.
Time and space complexity
Time: O(1). Space: O(1).
Edge cases to test
- -273.15°C is absolute zero; below it is physically invalid.
- Decimal formatting changes display, not the stored value.
Common mistakes
- Using integer arithmetic such as 9 / 5.
- Keeping Celsius, Fahrenheit, and Kelvin fields synchronized manually.
Follow-up challenge
Support construction from Fahrenheit while retaining one canonical internal unit.
Related OOP Basics exercises
- Practice Time Class in Java
- Practice Fraction Class in Java
- Practice Point Distance Calculator in Java
Practice all OOP Basics exercises · Run this idea in the Java compiler