English

What is meant by Type Casting? Explain with the help of an example program.

Advertisements

Question

What is meant by Type Casting? Explain with the help of an example program.

Code Writing
Explain
Advertisements

Solution

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: 25

In 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.

shaalaa.com
  Is there an error in this question or solution?
Chapter 6: Variables and Expressions - EXERCISE [Page 131]

APPEARS IN

Dheeraj Mehrotra Computer Science [English] Class 12
Chapter 6 Variables and Expressions
EXERCISE | Q 23. | Page 131
Advertisements
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×