How can I convert a long to int in Java?

后端 未结 16 2093
余生分开走
余生分开走 2020-11-29 16:49

How can I convert a long to int in Java?

相关标签:
16条回答
  • 2020-11-29 17:29
    long x = 3;
    int y = (int) x;
    

    but that assumes that the long can be represented as an int, you do know the difference between the two?

    0 讨论(0)
  • 2020-11-29 17:30

    You can use the Long wrapper instead of long primitive and call

    Long.intValue()
    

    Java7 intValue() docs

    It rounds/truncate the long value accordingly to fit in an int.

    0 讨论(0)
  • 2020-11-29 17:34

    If using Guava library, there are methods Ints.checkedCast(long) and Ints.saturatedCast(long) for converting long to int.

    0 讨论(0)
  • 2020-11-29 17:39

    If direct casting shows error you can do it like this:

    Long id = 100;
    int int_id = (int) (id % 100000);
    
    0 讨论(0)
提交回复
热议问题