类型转换
一、装箱与拆箱
二、基本类型和字符串之间转换(含boolean 字符串形式转成基本类型)
public class Text07 {
public static void main(String[] args) {
//一、装箱与拆箱
//类型转换:装箱,基本类型转成引用类型的过程
int num1=11; //基本类型
//使用Integer类创建对象,或调用方法
Integer integer1=new Integer(num1);
Integer integer2=Integer.valueOf(num1);
System.out.println("new Integer 装箱:"+integer1);
System.out.println("Integer引用 装箱:"+integer2);
//类型转型:拆箱,引用类型转成基本类型的过程
Integer integer3=new Integer(100);
int num2=integer3.intValue();
System.out.println("拆箱:"+ num2);
//JDK1.5之后,提供自动装箱和拆箱
int age=30;
//自动装箱
Integer integer4=age;
System.out.println("自动装箱:"+integer4);
//自动拆箱
int age2=integer4;
System.out.println("自动拆箱:"+age2); System.out.println("=================================================================");
//二、基本类型和字符串之间转换
//1.基本类型转换成字符串,两种方法:
int n1=15;
//1.1使用+号
String s1=n1+"";//直接在后面接一个字符串
//1.2使用Integer中的toString()方法
String s2=Integer.toString(n1,16);
System.out.println(s1);
System.out.println(s2);
System.out.println("=================================================================");
//2.字符串转成基本类型
String str="150";//引号内不能含字符类型
//使用Integer.parseXXX();
int n2=Integer.parseInt(str);
System.out.println(n2); System.out.println("=================================================================");
//3.boolean 字符串形式转成基本类型,"true"--->true 、非"true"--->false
String str2="true";
String str3="tru";//如果少了一个e呢?
boolean b2=Boolean.parseBoolean(str2);
boolean b3=Boolean.parseBoolean(str3);
System.out.println(b2);
System.out.println(b3);
}
}