文章目录
1.基本数据类型和包装类的对应
基本数据类型:byte、short、int、long、floot、double、boolean、char
8种包装类型:Byte、Short、Integer、Long、Floot、Double(父类都是Number)、Boolean、Character(父类都是Object)
2. 8种包装类种其中6个都是数字对应的包装类,他们的父类都是Number,可以先研究一下Number中公共方法:
Number是一个抽象类,无法实例化对象
Number类中有这样的方法:
byte byteValue()以 byte 形式返回指定的数值。
abstract double doubleValue() 以 double 形式返回指定的数值。
abstract float floatValue()以 float 形式返回指定的数值。
abstract int intValue()以 int 形式返回指定的数值。
abstract long longValue()以 long 形式返回指定的数值。
short shortValue() short 形式返回指定的数值。
这些方法是负责拆箱的[把引用数据类型都转换成基本数据类型]
3.装箱和拆箱
装箱:将基本数据类型变为包装类对象。
拆箱:将包装类中包装的基本数据类型取出。
package Integer;
/*
关于Integer类的构造方法,有两个:
Integer(int)
Integer(String)
*/
public class Test02 {
public static void main(String[] args) {
//将数字100转换为Integer类型
Integer x = new Integer(100);
System.out.println(x);
//将字符串123转换为Integer类型
Integer y = new Integer("123");
System.out.println(y);
Double d = new Double(1.23);
System.out.println(d);
Double e = new Double(1);
System.out.println(e);
}
package Integer;
/*
在JDK1.5之后支持自动拆箱和自动装箱
*/
public class Test04 {
public static void main(String[] args) {
Integer x = 100;//自动装箱 int类型自动转换为Integer
int y = x;//自动拆箱 Integer自动转换为int
}
}
4.以int Integer类为案例学习
int到Integer类:
三种方法:
(1)使用Integer类的构造方法
(2)使用Integer类内部的valueOf( )方法
(3)自动装箱
方法1:使用Integer类的构造方法
public Integer(int value):将int类型转换为Integer类。
public Integer(String s):将String类型转换为Integer类。
注意:使用此构造方法时,字符串内的字符必须由数字组成,不可以是字母或者
其他形式 ,否则抛出NumberFormatException。
public static void main(String[] args)
{
//方式1:public Integer(int value)
int i