常量:一种不会修改的变量
- Java无constant关键字
- 不能修改,final
- 不会修改,只有一份,static
- 方便访问public
- 故Java中常量为 public static final,一般变量名称全大写,以连字符相连,如BUUU_AFTE
注:接口里面定义的变量默认是常量(遵循契约设计)
常量池:相同的值只存储一份,节省内存,共享访问
-
Java为很多基本类型的包装类 /字符串都建立常量池
-
基本类型的包装类
-Boolean,Byte,Short,Integer,Long,Character,Float,Double
-Boolean:true,false
-Byte:-128~127,Character:0 ~127
-Short,Int,Long:-128~127
-Float,Double:没有常量池 -
基本类型的包装类和字符串有两种创建方式
- 常量式(字面量)赋值创建,放在栈内存(将被常量化)
Integer a=10;
String b="abc";
- new对象进行创建,放在堆内存(不会被常量化)new将根据构造函数来创建对象
Integer c=new Integer(10);
String d=new String ("abc");
- 这两种创建方式将导致对象存放位置不同
- 栈内存读取速度快但容量小
- 堆内存读取速度慢但容量大
A.java
public class A {
public Integer num = 100;
public Integer num2 = 128;
public Character c = 100;
}
B.java
public class B {
public Integer num = 100;
public Integer num2 = 128;
public Character c = 100;
public static void main(String[] args) {
A a = new A();
B b = new B();
//Integer -128~127有常量池 true
System.out.println(a.num == b.num);
//Integer 128不在常量池 false
System.out.println(a.num2 == b.num2);
//Character 0-127在常量池 true
System.out.println(a.c == b.c);
}
}
以下几个例子供更好的理解
例1.
public class BoxClassTest {
public static void main(String[] args)
{
int i1 = 10;
Integer i2 = 10; // 自动装箱
System.out.println(i1 == i2); //true
// 自动拆箱 基本类型和包装类进行比较,包装类自动拆箱
Integer i3 = new Integer(10);
System.out.println(i1 == i3); //true
// 自动拆箱 基本类型和包装类进行比较,包装类自动拆箱,成为普通类型
System.out.println(i2 == i3); //false
// 两个对象比较,比较其地址。
// i2是常量,放在栈内存常量池中,i3是new出对象,放在堆内存中
Integer i4 = new Integer(5);
Integer i5 = new Integer(5);
System.out.println(i1 == (i4+i5)); //true
System.out.println(i2 == (i4+i5)); //true
System.out.println(i3 == (i4+i5)); //true
// i4+i5 操作将会使得i4,i5自动拆箱为基本类型并运算得到10.
// 基础类型10和对象比较, 将会使对象自动拆箱,做基本类型比较
Integer i6 = i4 + i5; // +操作使得i4,i5自动拆箱,得到10,因此i6 == i2,是一个基本类型
System.out.println(i1 == i6); //true
System.out.println(i2 == i6); //true
System.out.println(i3 == i6); //false
}
}
例2:
public class StringNewTest {
public static void main(String[] args) {
String s0 = "abcdef";
String s1 = "abc";//栈上
String s2 = "abc";//s1,s2指向同一块内存
String s3 = new String("abc");//s3指向堆中的一块abc
String s4 = new String("abc");//s4指向堆中另一块abc
System.out.println(s1 == s2); //true 常量池
System.out.println(s1 == s3); //false 一个栈内存,一个堆内存
System.out.println(s3 == s4); //false 两个都是堆内存
System.out.println("=========================");
String s5 = s1 + "def"; //涉及到变量,故编译器不优化
String s6 = "abc" + "def"; //都是常量 编译器会自动优化成abcdef
String s7 = "abc" + new String ("def");//涉及到new对象,编译器不优化
System.out.println(s5 == s6); //false
System.out.println(s5 == s7); //false,堆中不同的abcdef
System.out.println(s6 == s7); //false
System.out.println(s0 == s6); //true
//注:s0,s6都指向栈中一块abcdef
System.out.println("=========================");
String s8 = s3 + "def";//涉及到new对象,编译器不优化
String s9 = s4 + "def";//涉及到new对象,编译器不优化
String s10 = s3 + new String("def");//涉及到new对象,编译器不优化
System.out.println(s8 == s9); //false
System.out.println(s8 == s10); //false
System.out.println(s9 == s10); //false
//s8,s9,s10都在堆上
}
}