Conversion between int, long, Integer and Long

一、int<->long

1. long -> int

(1) Type coercion

 long numberLong = 123L;// "L"理论上不分大小写,但是若写成"l"容易与数字"1"混淆,不容易分辩。所以最好大写。
 int numberInt = (int) numberLong;

注意
int has 4 bytes, and the value range is [-231, 231 - 1]
long has 8 bytes, [-263, 263 -1].
If the value of long exceeds the value range of the int area, a value overflow problem will occur.

(2) Use BigDecimal conversion

long numberLong = 100L;
BigDecimal numBigDecimal = new BigDecimal(numberLong);
   // 或 numBigDecimal = BigDecimal.valueOf(numberLong);
int numberInt = numBigDecimal.intValue();

2. int -> long

(1) Type coercion

 int numberInt = 123;
 long numberLong = numberLong;    // 因为long类型精度大于int类型精度,转换过程不会发生精度丢失情况,所以隐式强制转换即可

(2) Use BigDecimal conversion

int numberInt = 100;
BigDecimal numBigDecimal = new BigDecimal(numberInt);
   // 或 numBigDecimal = BigDecimal.valueOf(numberInt);
long numberlong = numBigDecimal.longValue();

二、Long <-> Integer

1. Convert Long to Integer

(1) Using Long’s API

Long numberLong = new Long(1000L);
Integer intNumber = numberLong.intValue();

(2) Use String conversion 

Long longValue = new Long(1000l);
String strValue = longValue.toString();
// 或者 Integer intValue = new Integer(strValue);
Integer intValue = Integer.valueOf(strValue);

2. Convert Integer to Long 

(1) Using Integer’s API

Integer intValue = new Integer(1000);
Long longValue = intValue.longValue();

(2) Use Long’s construction method 

Integer intValue = new Integer(1000);
Long longValue = new Long(intValue);

(3) Using String 

Integer intValue = new Integer(1000);
String strValue = intValue.toString();
Long longValue = new Long(strValue);

 

Guess you like

Origin blog.csdn.net/m0_69057918/article/details/132389064