Type Casting

Thinking

Java is a statically typed language, which means each variable must be declared with a data type. However, sometimes we need to convert data from one type to another to perform operations or store values appropriately.

Type casting ensures that we can safely and explicitly convert data types when required, helping avoid data loss or logic errors in programs.

Description

Type casting in Java refers to converting a variable from one data type to another. There are two main types:

  • Implicit (Widening) Casting: Automatically done by Java when converting from a smaller to a larger data type (e.g., int to double).
  • Explicit (Narrowing) Casting: Must be manually done when converting from a larger to a smaller type (e.g., double to int).

Understanding type casting is essential to prevent data loss and unexpected behaviors during computation and storage.

Video Resources

Java Type Casting

Detailed explanation of type conversion in Java with practical examples.

Examples (code)

Implicit (Widening) Type Casting


public class WideningExample {
    public static void main(String[] args) {
        int num = 100;
        double doubleNum = num;  // Automatic casting
        System.out.println("Double value: " + doubleNum);
    }
}
  

Explicit (Narrowing) Type Casting


public class NarrowingExample {
    public static void main(String[] args) {
        double d = 9.78;
        int i = (int) d;  // Manual casting
        System.out.println("Integer value: " + i);
    }
}
  

Real-World Applications

Financial Calculations

Converting between float and int ensures precision when handling currency and rounding.

Robotics & IoT

Sensors often provide float values which need to be cast into integers for microcontrollers.

Data Processing

Reading different data types from files requires proper casting for accurate computation.

Interview Questions

Q1: What is type casting in Java?

Show Answer

Type casting is converting a variable from one data type to another. Java supports both implicit and explicit casting.

Q2: What is the difference between widening and narrowing conversions?

Show Answer

Widening is automatic and safe (e.g., int to double), while narrowing requires explicit casting and may cause data loss (e.g., double to int).

Q3: Can you cast a boolean to another type in Java?

Show Answer

No, Java does not support casting between boolean and numeric types.