Home >>Java Tutorial >Java Type Casting
Java Type Casting is basically the process of assigning a value of another type to a variable of another type. In simple words, it can be understood in such a way that whenever a value of one primitive data type is assigned to another type.
There are generally two types of typecasting available in Java:
Widening casting is known as the automatically happening typecasting that is done when a small size type is passed to a larger size type.
Here is an example of the widening casting in Java language that will definitely help you in understanding the topic:
public class Demo { public static void main(String[] args) { int num = 5; double num1 = num; //it will Automatic cast int to double System.out.println(num); // Output is 5 System.out.println(num1); // Output is 5.0 } }
Narrowing Casting is generally needed to be done manually just by placing the type in parentheses in front of the value.
Here is an example of the Narrowing casting in Java language that will definitely help you in understanding the topic:
public class Demo { public static void main(String[] args) { double num = 5.75; int num_int = (num) myDouble; System.out.println(num); // Output 5.75 System.out.println(num_int);// Outputs 5 } }