Casts

1. Are a programmer’s way of telling the compiler to ignore possible loss of data or
precision that might result from a conversion?

2. Should be used with caution. Data loss is not to be taken lightly.

3. The general syntax is
identifier = (data-type) expression;

Example:
This is a corrected version of the previous program that uses a cast to prevent the compile error.

import java.util.*;
import java.io.*;
public class Application
{
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 = (float) (5 * (tempF – 32) / 9);
System.out.println(“Celsius equivalent is ” + tempC);
}
}
Output

Some thing on arithmetic expressions
Arithmetic expressions can be large and complex with several variables, constants, and operators. The order in which operations are performed is the same as in mathematics (multiplication and division first, then addition and subtraction, working from left to right).

To avoid confusion, good programmers keep their expressions as simple as possible and use parenthesis for clarity.

Scroll to Top