- 1Convert Decimal to Binary in Java
- 2Convert Binary to Decimal in Java
- 3Convert Decimal to Octal in Java
- 4Convert Octal to Decimal in Java
- 5Convert Decimal to Hexadecimal in Java
- 6Convert Hexadecimal to Decimal in Java
- 7Convert Binary to Hexadecimal in Java
- 8Convert Hexadecimal to Binary in Java
- 9Convert Octal to Binary in Java
- 10Convert Temperature from Celsius to Fahrenheit in Java
- 11Convert Kilometers to Miles, Meters, and Centimeters in Java
- 12Convert a String to Uppercase and Lowercase in Java
Convert Temperature from Celsius to Fahrenheit in Java
Topic
In this Java program, we will learn how to convert a temperature from Celsius to Fahrenheit. This type of program is often asked in beginner-level interviews to test your understanding of basic arithmetic operations and input/output in Java.
The formula to convert Celsius to Fahrenheit is: Fahrenheit = (Celsius * 9/5) + 32
.
Examples
- Input: 0 °C → Output: 32.0 °F
- Input: 100 °C → Output: 212.0 °F
- Input: -40 °C → Output: -40.0 °F (interesting edge case where both scales match)
Interviewer Expectations
The interviewer expects you to:
- Understand and apply a given formula correctly
- Use arithmetic operations with floating-point numbers
- Display formatted output using
System.out.println
- Write clean and readable Java code
Approach
To convert Celsius to Fahrenheit:
- Declare a variable for Celsius temperature.
- Apply the formula:
fahrenheit = (celsius * 9 / 5) + 32
. - Print the result.
Dry Run:
Let’s dry run the example where Celsius = 25
:
Fahrenheit = (25 * 9 / 5) + 32
= (225 / 5) + 32
= 45 + 32
= 77.0
Java Program
public class TemperatureConverter {
public static void main(String[] args) {
double celsius = 25;
double fahrenheit = (celsius * 9 / 5) + 32;
System.out.println("Celsius: " + celsius);
System.out.println("Fahrenheit: " + fahrenheit);
}
}
Celsius: 25.0
Fahrenheit: 77.0
Possible Followup Questions with Answers
1. How do you convert Fahrenheit to Celsius?
You can use the reverse formula: Celsius = (Fahrenheit - 32) * 5 / 9
.
2. How would you accept user input for Celsius in your program?
import java.util.Scanner;
public class TemperatureConverter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter temperature in Celsius: ");
double celsius = scanner.nextDouble();
double fahrenheit = (celsius * 9 / 5) + 32;
System.out.println("Fahrenheit: " + fahrenheit);
}
}
3. What happens if you use integer division accidentally?
If you write celsius * 9 / 5
and celsius
is an integer, you might lose precision. Always use double
for accurate results in temperature conversion.
⬅ Previous TopicConvert Octal to Binary in Java
Next Topic ⮕Convert Kilometers to Miles, Meters, and Centimeters in Java
Next Topic ⮕Convert Kilometers to Miles, Meters, and Centimeters in Java
Comments
Loading comments...