In this tutorial, we will learn about the Java Type Casting with the help of an example.
Type casting is nothing but assigning a value of one primitive data type to another. When you assign the value of one data type to another, you should be aware of the compatibility of the data type. If they are compatible, then Java will perform the conversion automatically known as Automatic Type Conversion and if not, then they need to be casted or converted explicitly.
byte -> short -> char -> int -> long -> float -> double
double -> float -> long -> int -> char -> short -> byte
Type conversion from int to String
class Codemistic
{
public static void main(String[] args)
{
// create int type variable
int num = 10;
System.out.println("The integer value is: " + num);
// converts int to string type
String data = String.valueOf(num);
System.out.println("The string value is: " + data);
}
}
Output:
The integer value is: 10
The string value is: 10
Type conversion from String to int
class Codemistic
{
public static void main(String[] args)
{
// create string type variable
String data = "10";
System.out.println("The string value is: " + data);
// convert string variable to int
int num = Integer.parseInt(data);
System.out.println("The integer value is: " + num);
}
}
Output:
The string value is: 10
The integer value is: 10