Type Casting
There are some conditions where we have to convert one data type to the other data type. In programming languages these conversions are referred to as Type Casting.
Java type casting can be classified in teo types:
1. Implicit type conversion (Java’s automatic conversions)
2. Explicit type conversion
1. Java’s Automatic Conversions
When one type of data type is assigned to another data type value then java will convert the data types automatically under two conditions.
1. The two types are compatible to each other
2. The destination type is of larger range than the source type.
For example, an Byte is internally casted to int, because int has range larger than that of byte range.
but the vice versa conversion will result in an error
byte b=5; int i = b; // automatic type conversion b = i; // will give error (byte is of 1 byte whereas int if of 4 bytes)
2. Explicit or Forced Conversions
For this conversion a type is forcefully converted to another type as :
byte b=5; int i = b; // automatic type conversion b = (byte) i; // (byte) is for typecast from int to byte
have a look at another casting example
public class anotherCastingExample { public static void main(String args[]) { byte b = 42; char c = 'a'; int i = 50000; float f = 5.67f; double d = .1234; int cast1 = b; // implicit cast int cast2 = c; //implicit cast float cast3 = (float)d; //explicit casting System.out.println("cast 1st " + cast1); System.out.println("cast 2nd " + cast2); System.out.println("cast 3rd " + cast3); } }