Type casting is the process of converting a value from one data type to another. This can be done explicitly or implicitly.
Implicit Type Casting
Implicit type casting is when the compiler automatically converts a value from one data type to another. This happens when the compiler can determine that the conversion is safe. For example, the compiler will implicitly convert an int value to a double value because double can store larger values than int.
Here is an example of implicit type casting:
int number = 10;
double d = number;
In this example, the number variable is an int and the d variable is a double. The compiler will implicitly convert the number variable to a double value because double can store larger values than int.
Explicit Type Casting
Explicit type casting is when the programmer explicitly converts a value from one data type to another. This is done using a cast expression. A cast expression is a set of parentheses that contain the data type to which the value should be converted.
Here is an example of explicit type casting:
int number = 10;
double d = (double)number;
In this example, the number variable is an int and the d variable is a double. The programmer has explicitly converted the number variable to a double value using the cast expression (double)number.
Example 2:
double numDouble = 1.23;
int numInt = (int)numDouble;
Here, the numDouble variable is a double and the numInt variable is an int. The programmer has explicitly converted the numDouble variable to an int value using the cast expression (int)numDouble.
Explicit type casting can be dangerous because it can lead to data loss. For example, if you convert a double value to an int value, you will lose any fractional part of the number.
Rules for Type Casting:
There are a few rules for type casting:
Using Type Casting Safely
It is important to use type casting safely. Here are a few tips for using type casting safely: