How to convert long to integer in Java?

Member

by raul , in category: Java , 2 years ago

I just started to learn Java and was stuck with some basics, I need to convert this long variable to an integer, is there any idea how can I do that?


1
2
3
4
5
6
public class Main {
    public static void main(String[] args) {
        final long aLong = 1664L;
        // to int
    }
}
Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by jerod.sauer , 2 years ago

@raul use toIntExact to convert any long number to an integer in Java, your code would be:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import static java.lang.Math.toIntExact;

public class Main {
    public static void main(String[] args) {
        final long aLong = 1664L;
        // to int
        final int anInteger = toIntExact(aLong);

        // Output: 1664
        System.out.println(anInteger);
    }
}


by mazie_pollich , 2 years ago

@raul you can use type-casting as well to convert any long number to integer in Java:


1
2
3
4
5
6
7
8
9
public class Main {
    public static void main(String[] args) {
        long l = 1664L;
        int i = (int) l;
        System.out.println(i);

        // Output: 1664
    }
}