Today my trainer on conducting mcq test send a question paper to write the answer of this question after completing test 25 out of 18.
After the test class going on casting on java.
Casting means converting one data type into another. Java is a strongly-typed language, so sometimes you canβt directly assign values of one type to another. Casting helps you make that conversion.
π― Types of Casting in Java
There are two main types of casting:
1οΈβ£ Widening Casting (Automatic Conversion)
Also called upcasting.
Java automatically converts a smaller type into a larger type.
β Safe because thereβs no data loss.
π Example:
public class WideningExample {
public static void main(String[] args) {
int num = 100;
double d = num; // automatic casting (int β double)
System.out.println("Integer value: " + num);
System.out.println("Double value: " + d);
}
}
Output:
Integer value: 100
Double value: 100.0
2οΈβ£ Narrowing Casting (Manual Conversion)
Also called downcasting.
You need to manually tell Java to convert a larger type into a smaller type.
β οΈ Risky because data may be lost.
π Example:
public class NarrowingExample {
public static void main(String[] args) {
double d = 99.99;
int num = (int) d; // manual casting (double β int)
System.out.println("Double value: " + d);
System.out.println("Integer value: " + num);
}
}
Output:
Double value: 99.99
Integer value: 99
Top comments (0)