Java Type Casting:
Java type casting is the process of converting a value of one data type to another. There are two types of type casting in Java: implicit casting (also known as widening) and explicit casting (also known as narrowing).
int num = 10;
double dNum = num; // implicit casting from int to double
In this example, the integer value 10 is assigned to the double variable dNum. Since double has a larger range than int, the conversion happens automatically.
double dNum = 10.5;
int num = (int) dNum; // explicit casting from double to int
In this example, the double value 10.5 is assigned to the integer variable num. Since int has a smaller range than double, the conversion needs to be done explicitly using a cast operator “(int)”.
It is important to note that explicit casting can result in loss of data or precision. For example, when casting a double value to an integer, the fractional part of the value is lost.
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.