Integer类型、int类型类型、String类型的相互转换

public class TestInteger {

public static void main(String[] args) {

//使用Integer类中的构造方法来构造对象,该类没有无参构造方法
// int类型转换成Integer
Integer it1 = new Integer(123);
//自动调用toString()方法,得到字符串类型的十进制整数

System.out.println("it1 = " + it1); //123

// String转换成Integer
Integer it2 = new Integer("456");
System.out.println("it2 = " + it2); //456

System.out.println("-----------------------------");


//实现int类型和Integer类型之间的相关转换

//int类转转换成String类型

Integer it3 = Integer.valueOf(789);

System.out.println("it3 = " + it3); //789  String类型的

//String类型转换成Int类型

int res = it3.intValue();
System.out.println("res = " + res); //789  int类型的

System.out.println("-----------------------------");


//实现String类型向int类型的转换
res = Integer.parseInt("12345");
//要求字符串中的每个字符都是十进制整数的字符,否则产生数字格式异常
//res = Integer.parseInt("12345a");
System.out.println("res = " + res); //12345  int类型的

//将-1(整数)转换为字符串形式的二进制
System.out.println(Integer.toBinaryString(-1));//全是1
//将-1(整数)转换为字符串形式的十六进制
System.out.println(Integer.toHexString(-1)); //全是f

System.out.println("-----------------------------");


//自动装箱和自动拆箱的机制
Integer it4 = 100;//int 转换 Integer 发生自动装箱,自动调用valueOf()方法
res = it4;         //Integer 转换 int   发生自动拆箱,自动调用intValue()方法

}

}
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值