Convert Long into Integer

后端 未结 14 2086
伪装坚强ぢ
伪装坚强ぢ 2020-12-07 07:48

How to convert a Long value into an Integer value in Java?

相关标签:
14条回答
  • 2020-12-07 08:19

    If you are using Java 8 Do it as below

        import static java.lang.Math.toIntExact;
    
        public class DateFormatSampleCode {
            public static void main(String[] args) {
                long longValue = 1223321L;
                int longTointValue = toIntExact(longValue);
                System.out.println(longTointValue);
    
            }
    }
    
    0 讨论(0)
  • 2020-12-07 08:20
    Integer i = theLong != null ? theLong.intValue() : null;
    

    or if you don't need to worry about null:

    // auto-unboxing does not go from Long to int directly, so
    Integer i = (int) (long) theLong;
    

    And in both situations, you might run into overflows (because a Long can store a wider range than an Integer).

    Java 8 has a helper method that checks for overflow (you get an exception in that case):

    Integer i = theLong == null ? null : Math.toIntExact(theLong);
    
    0 讨论(0)
提交回复
热议问题