What is meant by Type Casting? Explain with the help of an example program.
Advertisements
प्रश्न
What is meant by Type Casting? Explain with the help of an example program.
Advertisements
उत्तर
Type Casting in Java is the process of explicitly converting a value from one data type into another data type. It is performed by the programmer using the type casting operator, which specifies the desired data type within parentheses. Type casting is commonly used to convert a larger data type into a smaller data type and may result in loss of data or precision.
Syntax:
dataType variableName = (dataType) expression;
Example Program:
class TypeCasting
{
public static void main(String[] args)
{
double a = 25.75;
int b = (int) a;
System.out.println("Original Value: " + a);
System.out.println("Converted Value: " + b);
}
}
Output:
Original Value: 25.75 Converted Value: 25In the above program, the variable a is declared as a double and initialised with the value 25.75. The statement int b = (int) a; explicitly converts the double value into an integer using the type casting operator (int). During this conversion, the fractional part .75 is discarded, and the integer value 25 is assigned to b. Finally, both the original and converted values are displayed as output.
