包装类
介绍
包装类:在Java语言中一切皆对象,而八种基本数据类型不是,所以这里就有了针对这八种基本数据类型的包装类产生了,就是相当于给他外边套一个被识别的壳。
作用: 为了方便使用,里面封装了一些基本类型的一些操作
列举
八种基本数据类型都有对应的包装类
- byte =>Byte
- short => Short
- int => Integer
- long => Long
- float => Float
- double => Double
- boolean=> Boolean
- char => Character
这把种包装类都在java.lang下,意味着使用不需要导入
他们都覆写了toString和equals 方法
操作与常用方法
由于这八种数据类型的应用操作都差不多,我们以Integer为例:
int ,Integer,String三者转换
// int---->Integer
Integer i1=new Integer(23);
Integer i5=Integer.valueOf(2423);
// Integer---->int
int i2=i1.intValue();
// String--->Integer
Integer i3=new Integer("234");
Integer i4=Integer.valueOf("324");
// Integer---->String
String s1=i3.toString();
// String---->int
int i4=Integer.parseInt("2344");
// int---->String
String s2=23+"";
最大值,最小值:
System.out.println("int最大值"+Integer.MAX_VALUE);
System.out.println("int最小值"+Integer.MIN_VALUE);
System.out.println("long最大值"+Long.MAX_VALUE);
System.out.println("char最大值"+Character.MAX_VALUE);
指定值转换为进制格式的字符串
// staic String toOctalString(int value)把指定值转换为八进制格式的字符串
System.out.println(Integer.toOctalString(10));
// staic String toHexString (int value)把指定值转换为十六进制格式的字符串
System.out.println(Integer.toHexString(10));
其他数据类型的包装类操作一样,例如:
int i3=Integer.parseInt("2423");
double d1=Double.parseDouble("342.343");
注意:
这里也涉及到了自动装箱和自动拆箱的概念:
要明白:自动装箱和自动拆箱是编译时的概念 和运行时无关
作用是:方便编码
这里跟字符串相似 有一个整形常量池,但是这个常量池有范围限制:
- 如果是直接赋值,没有new,范围在-128-127之间都保存在常量池不会去堆内存创建对象
- 如果是直接赋值,没有new并且超过范围,会在堆内存创建对象
Integer i1=new Integer(10);
Integer i2=new Integer(10);
System.out.println(i1 == i2);
System.out.println(i1.equals(i2));
Integer i3 = 128; // 等同于 Integer i3 = new Interger(128);
Integer i4 = 128;
// false
System.out.println(i3 == i4);
Integer i5 =10; // 这种不等于 Integer i5 = new Interger(10);
Integer i6 =10;
// true
System.out.println(i5 == i6);