Unlock the Power of Java Type Casting
Understanding the Basics
Before diving into the world of Java Type Casting, it’s essential to have a solid grasp of Java Data Types. Type Casting is the process of converting the value of one data type (int, float, double, etc.) to another data type. In Java, there are 13 types of type conversion, but we’ll focus on the two most critical ones: Widening Type Casting and Narrowing Type Casting.
Widening Type Casting: Seamless Conversions
In Widening Type Casting, Java automatically converts one data type to another. For instance, converting an int to a double. This process is also known as Implicit Type Casting. The lower data type (having smaller size) is converted into the higher data type (having larger size), ensuring no loss of data. This automatic conversion occurs because Java can handle the transition without compromising the integrity of the data.
Example: Converting int to double
java
int num = 10;
double data = num;
In this example, Java first converts the int type data into the double type and then assigns it to the double variable.
Narrowing Type Casting: Manual Conversions
In Narrowing Type Casting, we manually convert one data type into another using parentheses. For example, converting a double into an int. This process is also known as Explicit Type Casting. The higher data types (having larger size) are converted into lower data types (having smaller size), which may result in data loss. This is why this type of conversion does not happen automatically.
Example: Converting double to int
java
double num = 10.5;
int data = (int) num;
Notice the int keyword inside the parentheses, indicating that the num variable is converted into the int type.
Exploring Other Type Conversions
Let’s examine some additional examples of type conversions in Java.
Example 1: Converting int to String
java
int num = 10;
String data = String.valueOf(num);
In this example, we use the valueOf() method of the Java String class to convert the int type variable into a string.
Example 2: Converting String to int
java
String num = "10";
int data = Integer.parseInt(num);
Here, we use the parseInt() method of the Java Integer class to convert a string type variable into an int variable. Note that if the string variable cannot be converted into the integer variable, a NumberFormatException occurs.
Further Reading
- Java Program to convert int type variables to char
- Java Program to convert int type variables to long
- Java Program to convert long type variables into int
- Java Program to convert double type variables to int