1.8 Type Conversion and Casting

Java is a strongly typed language. This means that before a value is assigned to a variable, Java checks the data types of the variable and the value being assigned to it to determine whether they are compatible.

For example, look at the following statements:

int x;
double y = 8.5;
x = y; // error!! double value can not be assigned to int variable
double a;
int b = 8;
a = b; // Ok. int value can be assigned to double variable

int i;
short j = 10;
i = j; // Ok. short value can be assigned to int variable

 

Java’s Automatic Conversions

When one type of data is assigned to another type of variable, an automatic type conversion will take place if the following two conditions are met:

  • The two types are compatible.
  • The destination type is larger than the source type.

Casting Incompatible Types

To create a conversion between two incompatible types, you must use a cast. A cast is simply an explicit type conversion. It has this general form:

(target-type) value

int x;
double y = 8.5;
x = (int)y; // Ok. The cast operator is applied to the value of y. 
//Ihe operator returns 8, which is stored in variable x.

 

Mixed Expression

When evaluating an operator in a mixed expression, if the operator has the same types of operands, the operator is evaluated according to the type of the operand. If the operator has different types of operands, the result is a larger type number.

Consider the following code:

int x, y;
double a;
x = 3;
y = 2;
a = 5.1;
System.out.println( x / y + a );
output : 6.1

Named Constants

In some program we need a memory location whose content should not be changed during program execution. To declare such named constant, use the final keyword before the variable declaration and include an initial value for that variable, as in the following:

final float PI = 3.141592;
final boolean DEBUG = false;
final double INTEREST_RATE = 0.075;

It is a common coding convention to choose all uppercase identifiers for final variables.