In this article we will see 'Type Casting in Java', and how to use Type Casting with example.

Assigning the value of one data type to other data type is called Type Casting.
long a = 100;
int b = (int)a; 

1) Widening Casting(Implicit)

When a narrow range data type value is assigned to a wide range data type, the type casting is called widening, this does not require any special syntax and the compiler automatically does the work.
int a = 100;
long b = a;
System.out.println(b); // 100

2) Narrowing Casting(Explicitly done)

When a wide range data type value is assigned to a narrow range data type, the type casting is called widening, this require explicitly put the converting type before the value to be casted.
long a = 100000;
int b = (int) a;
System.out.println(b);// 100000
In case wide datatype value is bigger than the limit of narrow datatype to which value is being casted, at runtime the bigger value will be truncated to fit in the narrow one, and would return a garbage value as shown below:
long a = 100000000000000l;
int b = (int) a;
System.out.println(b); // 276447232
Following is the list of premetive data types in narrow to wide order that follows while casting value in Java.

byte < short < int < long < float < double

Hence it is guaranteed that any int value will be successfully casted in long, float or double, but all double values will be successfully casted in int is not sure.

In this article we have seen 'What is Type Casting in Java', and how to use them with example. In upcoming articles we will see more about Java.
  • By Techburps.com
  • Nov 7, 2017
  • Core Java