Type Casting is use to convert value from one data type into another data type. There are 2 types of type casting: Implicit and Explicit type casting.
The process of assigning a smaller data type into larger data type is known as widening or promotion. This process is also known as Implicit or automatic conversion because we do not need to write any additional keyword to convert it. Syntax:
byte b = 10; int i = b; //Implicit Conversion
Assigning a larger data type value into a smaller data type is known as narrowing. In this type of assigning, loss of information may be possible. This process is also known as Explicit conversion because we have to write additional keyword to convert it. Syntax:
int i = 10; byte b = (byte)i
String value can be converted into integer, long, float, double value.
int i = Integer.valueOf("22").intValue(); long l = Long.valueOf("22").longValue(); float f = Float.valueOf("22.5").floatValue(); double d = Double.valueOf("22.5").doubleValue();
Another alternative way to convert string into intger, long value:
int i = Integer.parseInt (str); long l = Long.parseLong (str);
parseInt() and parseLong() methods throw a NumberFormatException, if the value of 'str' does not present an integer.
To convert numberic data value into string value:
string str = Integer.toString(i); string str = Float.toString(f); string str = Double.toString(d); string str = Long.toString(l);