目录
1.基本数据类型的包装类
1) java 八大基本数据类型:
byte, short,int,long,flaot,double, boolean, char
jdk: 为这八种基本数据类型, 提供了对应的类类型, 又称为基本类型的包装类
6个基本数据类型的包装类: 就是第一个字母大写
int --> Integer
char --> Character
包装类位于java.lang包
2.包装类的类结构图:
六大数字类型, 都一个共同的父类: Number类
3. 包装类中的常用方法
1. 基本数据类型与包装类之间转换的方法
基本数据类型转换为包装类这个过程称为: 装箱
1、 Integer i1 = new Integer(10); // 利用构造方法
2、 Integer i2 = Integer.valueOf(10); //利用包装类中的静态方法
拆箱:把包装类对象转换为对应的基本数据类型。
1、int i3= i1.intValue(); //返回包装类对象i1对应的基本数据
代码实例:
public class Num {
public static void main(String[] args) {
String str = args[0];
//------------- String转换成Integer
Integer integer = new Integer(str); // 方式一
// Integer integer = Integer.valueOf(str); //方式二
//------------- Ingeter转换成String
String str2 = integer.toString();
//------------- 把integer转换成int
int i = integer.intValue();
//------------- 把int转换成Integer
Integer integer2 = new Integer(i);//
//Integer integer2 = Integer.valueOf(i);
//------------- String转换成int
int i2 = Integer.parseInt(str);
//------------- 把int转换成String
String str3 = String.valueOf(i2); // 方式一
String str4 = i2 + ""; // 方式二
}
其他方法: 数字类型的其他
public static void main(String[] args) {
int num = 2022; //十进制
//转换为二进制
System.out.println("二进制:"+Integer.toBinaryString(num));
//八进制
System.out.println("八进制:"+Integer.toOctalString(num));
//十六进制
System.out.println("十六进制:"+Integer.toHexString(num));
char c = 'a';
//判断是否是一个数字
System.out.println(Character.isDigit(c));//false
}
4 .自动装箱和自动拆箱
自jdk1.5开始,java增加的对基本数据类型的自动装箱和自动拆箱操作。
1、 自动装箱:可以直接把一个基本数据类型赋值给包装类
2、 自动拆箱:可以直接把一个包装类对象,赋值给基本类型
int a = 100;
Integer i2 = a; // JDK 自动装箱, 底层使用valueOf() 方法实现
int b = i2;//JDK 自动拆箱, 底层使用 intValue() 方法实现