JAVA SE - 数据类型
一、JAVA的数据类型的分类
Java的数据类型分为两类:基本数据类型和引用数据类型。上图解:
对于基本数据类型,赋值时,注意个数据类型的取值范围。具体取值范围请见JAVA-常量和变量
接下来对基本数据类型进行代码演示:
整数型:
byte b=10; //比特型
int i=100; //整型
short s=1000; //短整型
long l=10000L; //长整型
浮点型:
double d=1.1D; //双精度浮点型
float f=2.2F; //单精度浮点型
字符型:
char c='c'; //字符型
布尔型:
boolean b1=true; //布尔型
二、包装类
衍生条件:基本数据类型不具备对象的特征,不能调用对象的方法。同时,发现,集合类并不支持基本数据类型的存入。这时候,把基本类型封装为对象,使其具备对象的属性和方法。
包装类
基本类型 | 默认值 | 包装类 | 默认值 |
byte | 0 | Byte | null |
short | 0 | Short | |
int | 0 | Integer | |
long | 0L | Long | |
float | 0.0F | Float | |
double | 0.0D | double | |
char | null | Characater | |
boolean | false | Boolean |
包装类和基本数据类型的区别;
a、在内存中存储的区域不同:
包装类存储在堆内,调用时使用对象去调用
基本数据类型的值存储在栈内。
b、使用场景不同:
包装类型可以用在集合中,但是基本数据类型不可以(jdk1.5以后支持自动装箱)。
c、初始值不同(默认值)
详见上图。
三、基本类型和包装类的转换
a、手动转换:
基本类型——->包装类:对应包装类的构造方法实现:举例,上代码:
int i=10;
Integer i1=new Integer(i);
包装类——>基本类型:通过包装类的实例方法:xxxValue():进行转换。上举例代码:
Character c1='a';
char c=c1.charValue();
System.out.println(c); //a
b、自动装箱和自动拆箱(jdk1.5以后)
基本类型添加到集合里时进行自动装箱。上代码:
List<Integer> list=new ArrayList<Integer>();
int i1=1;
int i2=2;
list.add(i1);
list.add(i2);
在对包装类进行“加”,“减”,“乘”,“除”,“==”,“.equals”时,进行自动拆箱。代码实例:
Integer in=3;
int i=3;
System.out.println(in==i);//true
再来看一个举例:
Integer in=128;
Integer in1=128;
System.out.println(in==in1);
思考最后的结果。
结果为false。why?
既然是要了解原理,可以去对源码进行查看了解信息,因为设计到拆箱(包装类—->基本类型),所以查看valueof()方法;
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
由源码可以看到,当i的值不在(-127,127)这个范围时,会创建一个新的对象。而==比较的是地址,既然创建了一个新的对象,地址自然也不一样。所以显示为false。注意:版本为1.5,就表示1.5版本以后才生效的。
四、基本数据类型进行运算时的转换
首先:小的转大的自动转换,大的转到小的要强制转换,不然会报错。
如下图解:
其中黑色的箭头表示自动转换,红色的线条表示需要强制转换。
对于byte,short,int这三种类型,在进行运算的时候,若进行不同类型的运算,都默认自动转换为int类型的进行运算。
下面进行简单的代码举例;
byte b1=10;
short s=10;
int i=s+b1;
System.out.println(i); //20
具体的各种类型的转换不再进行过多的举例,推荐自己实践,代码的世界里,实践至上。
另外,在大的数据类型强转为小的数据类型时,会出现精度丢失。具体在使用的时候需要注意实现要求。
五、引用类型
a、类Class的引用:
举例:
Object类:所有类的超类(父类),所有类的实例对象都可以实现Object类的方法:
String类:代表字符串,是底层是一个字符数组实现,有长度限制(大概是-1)。
b、接口类型(interface)
c、数组类型
注意数组的定义方式;
int[] a={1,2,3}; //定义一个1,2,3的值的数组a
int[] b=new int[3]; //定义一个大小为3的一维数组b
int[][] d=new int[1][3]; //定义一个一行三列的二维数组d
int[][] c=new int[3][]; //定义一个3行的二维数组c
注意:二维数组的行数必须要给出,列可以不可给出。
d、枚举类型(enum)
总结:对数据类型的讲解就到这里了,如有错误和补充欢迎各位博主一起探讨,共勉。
一起加油!!!
还没有评论,来说两句吧...