Conversions

Conversion is performed automatically when mixed numeric types appear within an expression.

Variables and constants are not altered, but their values are copied to intermediate areas of larger size or precision to prevent possible data loss during the calculation. This is known as a “widening” conversion.

The order of conversion (from narrowest to widest) is as follows. Memorize this table!

The data type resulting from an expression is that of the largest or most precise variable or constant appearing in the expression but is never smaller than int.

Example:
This program to convert a fahrenheit temperature to celsius will NOT compile.

import

java.util.*;
import java.io.*;
public class Conversion
{
public static void main(String[] args)
{

// Variables for holding fahrenheit and celsius temperatures

float tempC;

// Prompt for and read the fahrenheit temperature

System.out.print(“Enter the fahrenheit temperature (nn.n): “);
Scanner Keyboard=new Scanner(System.in);
double tempF;
tempF= Keyboard.nextDouble();

// Convert to celsius and display the result

tempC = 5 * (tempF – 32) / 9;
System.out.println(“Celsius equivalent is ” + tempC);

}
}

Note:
To fix the compile error in this code, tempC must be double or tempF must be float .

After Correction changing the tempC into double the result is…..

Scroll to Top