Type Casting in Java

This tutorial covers only primitive data type casting which explains converting a value of type double  to an int or an int to a double. Casting Object / reference variable will be covered in next tutorial.

  1. Numerical data are called primitive data types
  2. Objects are called reference data types

The range of numeric / primitive data type increase in following order.

range increase
Java allows to perform binary operation on value of mix data type (different data types).  Performing binary operations on mix data type, java autometically converts the operand based on the following promotion rules.

  1. If one of the operand is double, the other is converted into double
  2. if one of the operand is float, the other is converted into float
  3. if one of the operand is long, the other is converted into long
  4. otherwise both operan is converted into int

The resule of 5/2 is 2, because both operands are type of int. The result of 5.0/2 is 2.5, because 5.0 is double and 2 is converted to 2.0.

Let’s consider another example :


If x is a float and y is an int, what will be the data type of the following expression?

Answer is : float

Explicit Type Casting

Instead of relying on the promotion rules, we can make an explicit type cast by prefixing the operand with the data type using the following syntax:
( data type ) expression

(float) x / 5; // type cast x to float, then divide it by 5
(int) (x / y * 5.0) // type cast the result of expression to int 

Casting a variable of a type with a large range to a variable of a type with a smaller range is known as narrowing a type.
Consider another example

float f = (float)10.5; //the double value 10.5 is casted into float.
int i = (int)f; //i has a value of 10, the fractional part in f is truncated.

Implicit Type Casting

Casting a variable of a type with a small range to a variable of a type with a larger range is known as widening a type. This type of casting is done autometically.

int i = 10; // i has a value of 10
double d = i; // d has a value of 10.0, int value is implicitly casted to double

Note : Casting does not change the variable being cast. For example, i is not changed after casting in the above code. i has a value of 10 and value in d is 10.0.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.