Module: Variables and Data Types

Type Casting

Java Core: Type Casting

Type casting in Java refers to converting a value of one data type into another. This is often necessary when you need to perform operations on variables of different types, or when you want to store a value in a variable of a different type. Java has two main types of type casting:

  • Widening Casting (Implicit Casting): Converting a smaller data type to a larger data type. This is done automatically by the compiler.
  • Narrowing Casting (Explicit Casting): Converting a larger data type to a smaller data type. This requires you to explicitly tell the compiler to perform the conversion.

1. Widening Casting (Implicit Casting)

Widening casting happens when you assign a value of a smaller data type to a variable of a larger data type. No data loss occurs during this process because the larger data type can accommodate all the values of the smaller data type. The compiler handles this automatically.

Example:

public class WideningCasting {
    public static void main(String[] args) {
        int myInt = 10;
        long myLong = myInt; // int is automatically converted to long

        float myFloat = myInt; // int is automatically converted to float
        double myDouble = myFloat; // float is automatically converted to double

        System.out.println("Integer: " + myInt);
        System.out.println("Long: " + myLong);
        System.out.println("Float: " + myFloat);
        System.out.println("Double: " + myDouble);
    }
}

Valid Widening Conversions:

  • byte -> short -> int -> long -> float -> double
  • char -> int -> long -> float -> double

2. Narrowing Casting (Explicit Casting)

Narrowing casting happens when you assign a value of a larger data type to a variable of a smaller data type. This can lead to data loss because the smaller data type might not be able to hold all the information from the larger data type. Therefore, you must explicitly tell the compiler to perform the conversion using a cast operator (dataType).

Example:

public class NarrowingCasting {
    public static void main(String[] args) {
        double myDouble = 9.78;
        int myInt = (int) myDouble; // Explicitly cast double to int

        System.out.println("Double: " + myDouble);
        System.out.println("Integer: " + myInt); // Output: 9 (fractional part is truncated)

        long myLong = 150L;
        byte myByte = (byte) myLong; // Explicitly cast long to byte

        System.out.println("Long: " + myLong);
        System.out.println("Byte: " + myByte); // Output: -106 (due to overflow/underflow)
    }
}

Important Considerations with Narrowing Casting:

  • Data Loss: The fractional part of a double or float is truncated when cast to an int.
  • Overflow/Underflow: If the value of the larger data type is outside the range of the smaller data type, overflow or underflow can occur, leading to unexpected results. The value "wraps around".
  • Explicit Cast: The compiler will not perform narrowing casting automatically. You must use the (dataType) cast operator.

Valid Narrowing Conversions:

  • double -> float -> long -> int -> short -> byte
  • double -> float -> long -> int -> char
  • long -> int -> short -> byte
  • float -> long -> int -> short -> byte

3. Casting with Strings

You can't directly cast a String to a numeric type. You need to parse the string first.

Example:

public class StringCasting {
    public static void main(String[] args) {
        String strNumber = "123";

        int myInt = Integer.parseInt(strNumber); // Parse string to int
        double myDouble = Double.parseDouble(strNumber); // Parse string to double

        System.out.println("String: " + strNumber);
        System.out.println("Integer: " + myInt);
        System.out.println("Double: " + myDouble);

        //Error:  int myInt2 = (int) strNumber; // This will not compile
    }
}

Methods for Parsing Strings:

  • Integer.parseInt(String s): Parses a string to an int.
  • Double.parseDouble(String s): Parses a string to a double.
  • Float.parseFloat(String s): Parses a string to a float.
  • Long.parseLong(String s): Parses a string to a long.
  • Short.parseShort(String s): Parses a string to a short.
  • Byte.parseByte(String s): Parses a string to a byte.

Summary

Casting Type Description Compiler Handling Data Loss Cast Operator
Widening Smaller to Larger Automatic No Not Required
Narrowing Larger to Smaller Manual Possible (dataType)
String to Numeric String to int/double/etc. Manual Possible Integer.parseInt(), Double.parseDouble(), etc.

Understanding type casting is crucial for writing correct and efficient Java code. Always be mindful of potential data loss when performing narrowing casts and use the appropriate parsing methods when converting strings to numeric types.