In Java, type casting is a method or process for manually and automatically converting one data type into another. The compiler performs the automatic conversion, while the programmer performs the manual conversion. In this section, we’ll go over typecasting and the various types with examples.
There are two types of typecasting:
Implicit type casting is the process of converting a lower data type to a higher one. It’s also known as casting down or implicit conversion. It’s done for you automatically. Furthermore, it is secure because there is no risk of data loss. It occurs when the following occurs:
public class TypeCastingExample
{
public static void main(String args[])
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}
Before conversion, int value 7
After conversion, long value 7
After conversion, float value 7.0
Explicit type casting is the process of converting a higher data type to a lower one. It’s also known as casting up or explicit conversion. The programmer performs this task manually. The compiler will report a compile-time error if we do not perform casting.
public class TypeCastingExample
{
public static void main(String args[])
{
double d = 166.66;
//converting double data type into long data type
long l = (long)d;
//converting long data type into int data type
int i = (int)l;
System.out.println("Before conversion: "+d);
//fractional part lost
System.out.println("After conversion into long type: "+l);
//fractional part lost
System.out.println("After conversion into int type: "+i);
}
}
Before conversion: 166.66
After conversion into long type: 166
After conversion into int type: 166
Note: also read about the Operator Precedence & Associativity
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Find the length of the longest absolute path to a file within the abstracted file…
You manage an e-commerce website and need to keep track of the last N order…
You are given a stream of elements that is too large to fit into memory.…
The formula for the area of a circle is given by πr². Use the Monte…
Given an integer k and a string s, write a function to determine the length…
There is a staircase with N steps, and you can ascend either 1 step or…