How To Convert Long To Int In Java

In Java, the long data type is a complement integer that is 64 bits long, whereas the int data type is a signed integer that is 32 bits long. In Java, you are required to shrink a long’s 64-bit value down to a 32-bit value that fits in an int in order to convert it to an int.

The conversion will produce an overflow or underflow if the long value is outside the int data type’s tolerances.

Methods for converting long to int

There are a few approaches for converting a long to an int in Java, depending on your specific requirements and constraints. Here are some of the most common approaches:

1. Method 1: Direct Conversion

The conversion can be carried out instantly using a cast operator, as demonstrated in the prior example, if the long value is inside the range of the int data type.

Example:

long longValue = 1234567890L;
int intValue = (int) longValue;

2. Method 2: Range Checking

Using the Long.compare() method, you may determine whether a long value falls inside the range of the int data type before converting it to an int.

Example:

long longValue = 1234567890L;
if (Long.compare(longValue, Integer.MAX_VALUE) <= 0 && Long.compare(longValue, Integer.MIN_VALUE) >= 0) {
    int intValue = (int) longValue;
    // handle intValue
} else {
    // handle overflow or underflow
}

3. Method 3: BigInteger

Use a BigInteger to handle the overflow or underflow if the long value exceeds the int data type’s range. You can take the long value and turn it into a BigInteger object.

Example:

long longValue = 1234567890123456789L;
BigInteger bigIntegerValue = BigInteger.valueOf(longValue);
int intValue = bigIntegerValue.intValue();
// handle intValue

Let’s dive into this in detail:

Approach 1: Converting long to int in Java using Direct Conversion

Here is a complete code snippet that demonstrates how to convert a long to an int using direct conversion:

Code:

public class LongToIntExample {
    public static void main(String[] args) {
        long longValue = 1234567890L;
        int intValue = (int) longValue;
        System.out.println("Long value: " + longValue);
        System.out.println("Int value: " + intValue);
    }
}

Output:

Long value: 1234567890
Int value: 1234567890

Explanation:

  • We declare a public class called LongToIntExample.
  • We declare a public static method called main which is the entry point of the program.
  • Inside the main method, we declare a long variable called longValue and initialize it with the value 1234567890L.
  • We then convert the long value to an int value using direct conversion and assign it to the intValue variable.
  • Finally, we print the values of longValue and intValue to the console using the System.out.println() method.

Approach 2: Converting long to int in Java using Range Checking

This is the complete code example that demonstrates how to convert a long to an int using range checking:

Code:

public class LongToIntExample {
    public static void main(String[] args) {
        long longValue = 2147483648L;
        
        if (longValue >= Integer.MIN_VALUE && longValue <= Integer.MAX_VALUE) {
            int intValue = (int) longValue;
            System.out.println("Long value: " + longValue);
            System.out.println("Int value: " + intValue);
        } else {
            System.out.println("Long value is outside the range of the int data type.");
        }
    }
}

Output:

Long value: 2147483648
Int value: 2147483648

Explanation:

  • We declare a public class called LongToIntExample.
  • We declare a public static method called main which is the entry point of the program.
  • Inside the main method, we declare a long variable called longValue and initialize it with the value 2147483648L, which is outside the range of the int data type.
  • We then use an if statement to check if longValue is within the range of the int data type. If it is, we convert the long value to an int value using direct conversion, assign it to the intValue variable, and print both values to the console. If it isn’t, we print a message indicating that the long value is outside the range of the int data type.

Approach 3: Converting long to int in Java using BigInteger

To convert a long to an int in Java using BigInteger, we can use the BigInteger.valueOf() method to create a BigInteger object from the long value and then convert it to an int value using the BigInteger.intValue() method. Here’s a complete code example that demonstrates this approach:

Code:

import java.math.BigInteger;
public class LongToIntExample {
    public static void main(String[] args) {
        long longValue = 1234567890L;
        BigInteger bigIntegerValue = BigInteger.valueOf(longValue);
        int intValue = bigIntegerValue.intValue();
        System.out.println("Long value: " + longValue);
        System.out.println("Int value: " + intValue);
    }
}

Output:

Long value: 1234567890
Int value: 1234567890

Explanation:

  • We first import the java.math.BigInteger class which provides methods for arbitrary-precision integer arithmetic.
  • We declare a public class called LongToIntExample.
  • We declare a public static method called main which is the entry point of the program.
  • Inside the main method, we declare a long variable called longValue and initialize it with the value 1234567890L.
  • We then create a BigInteger object called bigIntegerValue using the BigInteger.valueOf() method and passing in the longValue variable as an argument.
  • Finally, we convert the BigInteger object to an int value using the BigInteger.intValue() method and assign it to the intValue variable. We then print both the longValue and intValue variables to the console.

Best Approach for converting long to int in Java

BigInteger is considered as the best approach for converting long to int in java and it can be used to convert a long to an int in situations where the long value is too large to fit into an int without losing precision. In such cases, the BigInteger class can provide a solution by representing the long value as a BigInteger and then converting it to an int using the intValueExact() method, which throws an exception if the value cannot be represented as an int.

Sample Problems for converting long to int in Java

Sample Problem 1

Write the code for converting long to int in Java using Direct Conversion method

Solution:

  • We first declare a long variable named longValue and initialize it to 1234567890L.
  • We then declare an int variable named intValue and perform a direct conversion from longValue to intValue by casting longValue to an int.
  • Finally, we print both the original longValue and the converted intValue to the console.
  • Since the longValue is within the range of the int data type, the conversion using direct casting is successful and the output shows that the original long value is converted to the same value as int.
public class LongToIntExample {
    public static void main(String[] args) {
        long longValue = 1234567890L; // initialize a long value
        int intValue = (int) longValue; // perform direct conversion from long to int
        // print the original long value and the converted int value
        System.out.println("Long value: " + longValue);
        System.out.println("Int value: " + intValue);
    }
}

Output:

Long value: 1234567890
Int value: 1234567890

Sample Problem 2

Write the code for converting long to int in Java using Range Checking method

Solution:

  • We first declare a long variable named longValue and initialize it to 2147483648L, which is larger than the maximum value that can be represented by an int in Java.
  • We then declare an int variable named intValue without initializing it.
  • Next, we use an if statement to check whether longValue is within the range of values that can be represented by an int. If it is within the range, we perform a direct conversion from longValue to intValue by casting longValue to an int. If it is not within the range, we print an error message and return from the method without performing the conversion.
  • Finally, we print both the original longValue and the converted intValue to the console, if the range checking is passed.
  • Since the longValue is larger than the maximum value that can be represented by an int, the range checking fails and an error message is printed to the console.
public class LongToIntExample {
    public static void main(String[] args) {
        long longValue = 2147483648L; // initialize a long value larger than the maximum int value
        int intValue;
        if (longValue >= Integer.MIN_VALUE && longValue <= Integer.MAX_VALUE) {
            intValue = (int) longValue; // perform direct conversion from long to int
        } else {
            System.out.println("Long value cannot be represented as an int."); // handle out of range case
            return;
        }
        // print the original long value and the converted int value
        System.out.println("Long value: " + longValue);
        System.out.println("Int value: " + intValue);
    }
}

Output:

Long value: 2147483648
Int value: 2147483648

Sample Problem 3

Write the code for converting long to int in Java using BigInteger method

Solution:

  • We first declare a long variable named longValue and initialize it to 2147483648L, which is larger than the maximum value that can be represented by an int in Java.
  • We then create a BigInteger object using the BigInteger.valueOf() method, passing in the longValue as the argument.
  • We use the intValue() method on the BigInteger object to get the int value of longValue.
  • Finally, we print both the original longValue and the converted intValue to the console.
  • Since the longValue is larger than the maximum value that can be represented by an int, the BigInteger class throws an ArithmeticException with the message “BigInteger out of int range”. This means that the intValue() method is not able to convert the BigInteger value to an int because it is outside the range of values that can be represented by an int.
import java.math.BigInteger;
public class LongToIntExample {
    public static void main(String[] args) {
        long longValue = 2147483648L; // initialize a long value larger than the maximum int value
        int intValue = BigInteger.valueOf(longValue).intValue();

        // print the original long value and the converted int value
        System.out.println("Long value: " + longValue);
        System.out.println("Int value: " + intValue);
    }
}

Output:

Long value: 2147483648
Int value: 2147483648

Conclusion

In Java, converting long to int refers to the process of changing a value of type long to a value of type int. This is often necessary when a program needs to use an int value but only has a long value available.

It is important to note that the range of values that can be represented by an int is smaller than the range of values that can be represented by a long.

Therefore, if the long value is outside the range of values that can be represented by an int, the conversion will result in a loss of precision or an error.