In this tutorial, you will learn how to convert a long value to an int in Java. We’ll explore explicit casting, potential data loss, and provide examples to demonstrate the conversion process.

Java – Convert long to int

Converting long to int in Java – In Java, converting a long to an int requires explicit casting because long has a larger range than int. This conversion might result in data loss if the long value is larger than the maximum int value.

Explicit Conversion from long to int

To convert a long to an int in Java, you need to use an explicit cast. Be cautious, as casting a large long value into an int can cause data loss by truncating the higher bits.

Example of Explicit Conversion

</>
Copy
public class LongToIntExample {

    public static void main(String[] args) {
        long longVal = 12345L;
        int intVal = (int) longVal; // Explicit conversion from long to int
        System.out.println("Long value: " + longVal);
        System.out.println("Int value after conversion: " + intVal);
    }
}

Output

Long value: 12345
Int value after conversion: 12345

In this example, the long value 12345 fits within the range of an int, so no data is lost in the conversion.

Data Loss with Large long Values

If the long value exceeds the range of int (-2,147,483,648 to 2,147,483,647), the conversion will result in data loss. This means only the lower 32 bits are retained, which can lead to unexpected results.

Example Demonstrating Data Loss

</>
Copy
public class LongToIntExample {

    public static void main(String[] args) {
        long longVal = 3000000000L; // A value larger than int range
        int intVal = (int) longVal; // Explicit conversion
        System.out.println("Long value: " + longVal);
        System.out.println("Int value after conversion: " + intVal);
    }
}

Output

Long value: 3000000000
Int value after conversion: -1294967296

In this example, the long value 3000000000 is out of the int range. The resulting int value appears as -1294967296, illustrating data loss due to overflow.

Conclusion

Converting a long to an int in Java requires explicit casting. This conversion may lead to data loss if the long value is outside the int range. It’s essential to consider the size of your long values before casting them to int to ensure accurate results.