Casting
- Casting in Java can be manually done with the proper syntax.
- To do this you must use a cast, which is an explicit type conversion.
- The following syntax is used to perform casting.
(target type) variable
- The “target type” is the data type that we want to change to.
- Target data type must be kept inside brackets, and next we need to mention the variable (Or the value) that we need to get converted.
- The following example shows casting of double to integer.
num = (int) dbl;
- When casting floating point values to integers, the value will be truncated. (The decimal pace will be removed without rounding.)
- The following example shows casting of integer to float.
flt = (float) num;
- But integers cannot be converted to strings in the above method.
- Next let’s explore the process of converting integers to strings.
When casting a floating point value to an integer variable, what will happen to the number?