Java 基本数据类型、包装类、String类的相互转换和自动拆箱/装箱

基本数据类型和包装类的对应关系
在这里插入图片描述

1.基本数据类型→包装类

  • 调用包装类的构造器
  • 自动装箱( JDK5.0以后出现 )
//调用包装类的构造器
Integer in1 = new Integer(100);//in1=100
Integer in2 = new Integer("100");//in2=100
Integer in3 = new Integer("100a");//NumberFormatException异常

Boolean b1=new Boolean(true); //true
Boolean b2=new Boolean("true");//true
Boolean b3=new Boolean("TruE");//true
Boolean b4=new Boolean("true1");//false
// boolean构造函数不同于其他包装类的构造函数,具体请查看源码(如下)
//不难发现是字符串忽略了大小写之后比较得出的结果,只有true和false,没有异常
 public Boolean(String s) 
 {
    
    
     this(parseBoolean(s));
 }
 public static boolean parseBoolean(String s)
 {
    
    
    return "true".equalsIgnoreCase(s);
}
//自动装箱
int num=10;
Integer in=num

Object o1 = true ? new Integer(1) : new Double(2.0);
System.out.println(o1);// 1.0
//因为三目运算符 :左右类型得相同,Integer自动类型提升为Double

2. 包装类→基本数据类型

  • 调用包装类方法 xxxValue()
  • 自动拆箱
//调用包装类方法  xxxValue()
Integer in=new Integer(12);
int num=in.intValue();

//自动拆箱
int num=in

3.基本数据类型/包装类→String类

  • 基本数据类型/包装类+""
  • 调用 String.ValueOf()
//基本数据类型/包装类+""
String str1=10+"";

//调用 String.ValueOf()
String str2=String.ValueOf(10)
Integer in=10;
String str2=String.ValueOf(in);

3.String类→基本数据类型/包装类

  • 调用 包装类.ValueOf( )
//调用 包装类.ValueOf()
String str="10";
int a=Integer.valueOf(str);
Integer in1=Integer.valueOf(str);

猜你喜欢

转载自blog.csdn.net/weixin_43956248/article/details/112720643