Long和Integer相互转换

目录

  • 一、int和long互相转换
    • (一)long转化为int
      • (1)类型强制转换
      • (2)利用BigDecimal强制转换
    • (二)int转化为long
      • (1)类型强制转换
      • (2)利用BigDecimal强制转换
  • 二、Long和Integer的互相转换
    • (一)Long转化为Integer
      • (1)类型强制转化(不可用)
      • (2)使用Long的api
      • (3)利用String转换
    • (二)Integer转化为Long
      • (1)类型强制转化(不可用)
      • (2)使用Integer的api
      • (3)使用Long的构造方法
      • (4)利用String

一、int和long互相转换

(一)long转化为int

(1)类型强制转换

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

注意:
int有4个字节,取值范围为[-231,231 - 1]
long有8个字节,[-263 ,263 -1]
如果long的值超过了int区值范围,会出现值溢出的问题:
Long和Integer相互转换_第1张图片
就会得以下内容:
Long和Integer相互转换_第2张图片
这是因为:当取值范围超过int的最大值时,会变为int取值范围的最小值,不会继续增长了。

Long和Integer相互转换_第3张图片

(2)利用BigDecimal强制转换

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

(二)int转化为long

(1)类型强制转换

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

(2)利用BigDecimal强制转换

 int numberInt = 100;
 BigDecimal bigNumber = new BigDecimal(numberInt);
// 或者 BigDecimal bigNumber = BigDecimal.valueOf(numberInt);
 long numberLong = bigNumber.longValue();

二、Long和Integer的互相转换

(一)Long转化为Integer

(1)类型强制转化(不可用)

Long和Integer相互转换_第4张图片
会出现报错
Long和Integer相互转换_第5张图片
报编译错:无法转换的类型,Long不能被强制转化为Integer。

(2)使用Long的api

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

(3)利用String转换

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

(二)Integer转化为Long

(1)类型强制转化(不可用)

Long和Integer相互转换_第6张图片

(2)使用Integer的api

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

(3)使用Long的构造方法

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

(4)利用String

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

你可能感兴趣的:(常用API,java)