java语言基础--包装类
包装类:
8个基本数据类型对应的类,就是包装类;
包装类的优点:
可以在对象中定义更多的功能和方法操作该数据,方便开发者操作该数据,例如基本数据和字符创之间的转换;
基本数据类型 包装类
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
包装类的一些方法:
public class Main { public static void main(String[] args) { System.out.println(Integer.MAX_VALUE); System.out.println(Integer.MIN_VALUE); Integer i = new Integer(100); System.out.println(i); Integer i1 = new Integer("1023"); System.out.println(i1); //将Integer类型转化成int类型数据 int i2 = i1.intValue(); //将String类型的数据转换成int类型的数据 int i3 = Integer.parseInt("111"); } }
Integer、int、String三者之间的相互转换
public class Main2 { public static void main(String[] args) { //int ---->Integer Integer i1 = Integer.valueOf(10); //Integer ---->int int i2 = i1.intValue(); //String ----> Integer Integer i3 = Integer.valueOf("10"); //Integer ----> String String s1 = i3.toString(); //int ---->String String s2 = 10 + ""; //String ----> int int i4 = Integer.parseInt("10"); } }
自动装箱和自动拆箱
自动装箱:将基本类型数据自动转换为其对应的包装类;
Integer i1 = 10;
Integer i4 = new Integer(10);
//这两种写法是一样的
自动拆箱:
Integer i2 = new Integer(10); int i3 = i2;
举个栗子:
public class Main3 { public static void main(String[] args) { Integer i1 = 10; Integer i2 = 10; System.out.println(i1 == i2); //true System.out.println(i1.equals(i2) ); //true Integer i3 = 888; Integer i4 = 888; System.out.println(i3 ==i4); //false System.out.println(i3.equals(i4)); //true } }
上面的实例是不是有点怪?
是这样的,有个咚咚叫 整形常量值 如果值在 -128~127之间的时候,会在整形常量池里面直接获数。
浙公网安备 33010602011771号