Java Type Casting is the process of converting one data type into another data type. In Java, there are two types of casting: Widening Casting (Implicit) and Narrowing Casting (Explicit).
Widening Casting is the process of converting a smaller data type into a larger data type. This is done automatically by the Java compiler. For example:
int num1 = 10;
double num2 = num1;
In the above code, the integer variable num1 is automatically converted into a double variable num2. This is because double is a larger data type than int.
Narrowing Casting is the process of converting a larger data type into a smaller data type. This is done manually by the programmer. For example:
double num1 = 10.5;
int num2 = (int) num1;
In the above code, the double variable num1 is manually converted into an integer variable num2. This is done by using the (int) keyword before the variable name.
Let's take an example to understand the concept of Java Type Casting:
int num1 = 10;
double num2 = 20.5;
double result = num1 num2;
System.out.println("Result: " result);
In the above code, the integer variable num1 is automatically converted into a double variable num2. Then, the two variables are added and stored in a double variable result. Finally, the result is printed on the console.
Java Type Casting is an important concept in Java programming. It allows the programmer to convert one data type into another data type. Widening Casting is done automatically by the Java compiler, while Narrowing Casting is done manually by the programmer.
Oracle. (n.d.). Casting and Type Conversions (Java Tutorials). Retrieved from https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html