Java Program to Implement Type Casting and Type Conversion
There are many situations that come when we have to change the functionality of the output as well as the type of output according to the need of the requirements. For e.g. Entered PI value in decimal format should be converted in the decimal format so that value can be used efficiently without any kind of errors and wrong output.
There are two ways we can change the type from one to another.
- Type casting
- Type conversion
Type Casting means to change one state to another state and is done by the programmer using the cast operator. Type Casting is done during the program design time by the programmer. Typecasting also refers to Narrow Conversion. Because in many cases, We have to Cast large datatype values into smaller datatype values according to the requirement of the operations. We can also convert large datatype values into smaller datatype values that’s why Type Casting called Narrow Casting.
Syntax: () is Cast Operator
Type Conversion is a type conversion that is done by compiler done by a compiler without the intention of the programmer during the compile time. This Conversion sometimes creates an error or incorrect answer if the proper resultant data type does not mention at the end of the multiple expression of the datatype that’s why Type Conversion is less efficient than Type Casting.
The working mechanism of type conversion is as follows:
double > float > long > int > short > byte
Example 1: Error during type conversion
prog.java:9: error: incompatible types: possible lossy conversion from double to int int final_datatype = (a + b + c); ^ 1 error
When you assign the value of one data type to another, the two types might not be compatible with each other. If the data types are compatible, then Java will perform the conversion automatically known as Automatic Type Conversion, and if not then they need to be cast or converted explicitly. For example, assigning an int value to a long variable.
Please Login to comment...