基本数据类型 | 包装类型 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
boolean | Boolean |
char | Character |
装箱:基本类型转引用类型
拆箱:引用类型转基本类型
类型转换
public class Demo01 {
public static void main(String[] args) {
//类型转换:装箱,基本类型转成引用类型的过程
//基本类型
int num1 = 10;
//使用Integer类创建对象
// Integer integer1 = new Integer(num1); 已弃用
Integer integer2 = Integer.valueOf(num1);
System.out.println("装箱:" + integer2);
//基本类型转换:拆箱,引用类型转成基本类型的过程
Integer integer3 = Integer.valueOf(100);
int num2 = integer3.intValue();
System.out.println("拆箱:" + num2);
//以上为JDK 1.5之前的拆箱和装箱
//在JDK 1.5之后,提供了自动装箱和拆箱
int age1 = 20;
//自动装箱
Integer integer4 = age1;
System.out.println("自动装箱:" + integer4);
//自动拆箱
int age2 = integer4;
System.out.println("自动拆箱:" + age2);
}
}
输出
装箱:10
拆箱:100
自动装箱:20
自动拆箱:20
示例
public class Demo02 {
public static void main(String[] args) {
//基本类型和字符串之间的转换
//基本类型转成字符串
int n1 = 255;
//1.使用+号
String s1 = n1 + "";
//2.使用Integer中的toStirng()方法
String s2 = Integer.toString(n1);
String s3 = Integer.toString(n1,16);//重载方法,转换成16进制
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
//字符串转成基本类型
String str = "150";
//使用Integer.parseXXX();
int n2 = Integer.parseInt(str);
System.out.println(n2);
//特殊:boolean字符串形式转成基本形式:"true"--->true 非"true"--->false
String str2 = "true";
boolean b1 = Boolean.parseBoolean(str2);
System.out.println(b1);
}
}
输出
255
255
ff
150
true
原文:https://www.cnblogs.com/dt746294093/p/14660122.html