基本数据类型与常量池
基本数据类型
Java中的基本数据类型只有8个:byte(1字节=8位)、short(2字节)、int(4字 节)、long(8字节)、float(4字节)、double(8字节)、char(1字 节)、boolean(1位)。
除了以上8种基本数据类型,其余的都是引用数据类型。
对应的包装类分别是:Byte、Short、Integer、Long、Float、Double、 Character、Boolean。
JVM的内存区域组成
java把内存分两种:一种是栈内存,另一种是堆内存
- 在函数中定义的基本类型变量(即基本类型的局部变量)和对象的引用变量(即对象的变量名)都在函数的栈内存中分配;
- 堆内存用来存放由new创建的对象和数组以及对象的实例变量(即全局变量)。
在函数(代码块)中定义一个变量时,java就在栈中为这个变量分配内存空间,当超过变量的作用域后,java会自动释放掉为该变量所分配的内存空间;在堆中分配的内存由java虚拟机的自动垃圾回收器来管理。
堆和栈的优缺点
堆的优势:是可以动态分配内存大小,生存期也不必事先告诉编译器,因为它是在运行时动态分配内存的。
缺点:就是要在运行时动态分配内存,存取速度较慢;
栈的优势:是存取速度比堆要快,仅次于直接位于CPU中的寄存器。另外,栈数据可以共享。
缺点:是存在栈中的数据大小与生存期必须是确定的,缺乏灵活性。
方法区
方法区中主要存储所有对象数据共享区域,存储静态变量和普通方法、静态方法、常量、字符串常量(严格说存放在常量池,堆和栈都有)等类信息,、说白了就是保存类的模版。(方法区包含所有的class和static变量)
自动拆箱和装箱
自动装箱就是Java自动将原始类型值转换成对应的对象,比如将int的变量转换成Integer对象,这个过程叫做装箱,反之将Integer对象转换成int类型值,这个过程叫做拆箱。
因为这里的装箱和拆箱是自动进行的非人为转换,所以就称作为自动装箱和拆箱。
原始类
byte,short,char,int,long,float,double和boolean
对应的封装类Byte,Short,Character,Integer,Long,Float,Double,Boolean。
赋值
在Java 1.5以前我们需要手动地进行转换才行,而现在所有的转换都是由编译器来完成。
//before autoboxing
Integer iObject = Integer.valueOf(3);
Int iPrimitive = iObject.intValue()
//after java5
Integer iObject = 3; //autobxing - primitive to wrapper conversion
int iPrimitive = iObject; //unboxing - object to primitive conversion
方法调用
public static Integer show(Integer iParam){
System.out.println("autoboxing example - method invocation i: " + iParam);
return iParam;
}
//autoboxing and unboxing in method invocation
show(3); //autoboxing
int result = show(3); //unboxing because return type of method is Integer
对象相等比较
public class AutoboxingTest {
public static void main(String args[]) {
// Example 1: == comparison pure primitive – no autoboxing
int i1 = 1;
int i2 = 1;
System.out.println("i1==i2 : " + (i1 == i2)); // true
// Example 2: equality operator mixing object and primitive
Integer num1 = 1; // autoboxing
int num2 = 1;
System.out.println("num1 == num2 : " + (num1 == num2)); // true
// Example 3: special case - arises due to autoboxing in Java
Integer obj1 = 1; // autoboxing will call Integer.valueOf()
Integer obj2 = 1; // same call to Integer.valueOf() will return same
// cached Object
System.out.println("obj1 == obj2 : " + (obj1 == obj2)); // true
// Example 4: equality operator - pure object comparison
Integer one = new Integer(1); // no autoboxing
Integer anotherOne = new Integer(1);
System.out.println("one == anotherOne : " + (one == anotherOne)); // false
}
}
Output:</