基本概念:
1.常量:一种不会修改的变量
-Java没有constant关键字
-不能修改,final
-不会修改/只读/只要一份, static
-方便访问public
2.Java中的常量:
-public static final
-建议变量名字全大写,以连字符相连,例如MAX_VALUE
public class Constants {
public final static double PI_NUMBER = 3.14;
public static final String DEFAULT_COUNTRY="China";
public static void main(String[] a)
{
System.out.println(Constants.PI_NUMBER);
System.out.println(Constants.DEFAULT_COUNTRY);
}
}
一种特殊的常量:接口内定义的变量默认是常量。
Java为很多基本类型的包装类/字符串都建立常量池。
3.常量池:相同的值只存储一份,节省内存,共享访问
基本类型的包装类
-Boolean, Byte, Short, Integer, Long, Character, Float, Double
-Boolean: true, false
-Byte,Character: 0-127
-Short, Int, Long: -128~127
-Float, Double: 没有缓存(常量池)
4.Java为常量字符串都建立常量缓存机制:字符串常量
public class StringConstantTest {
public static void main(String[] args) {
String s1 = "abc";
String s2 = "abc";
String s3 = "ab" + "c"; //都是常量,编译器将优化,下同
String s4 = "a" + "b" + "c";
System.out.println(s1 == s2); //true
System.out.println(s1 == s3); //true
System.out.println(s1 == s4); //true
}
}
5.基本类型的包装类和字符串有两种创建方式
-常量式(字面量)赋值创建,放在栈内存(将被常量化)
·Integer a = 10;
`String b = "kfc";
-new对象进行创建,放在堆内存(不会常量化)
·Integer c = new Integer(10);
·String d = new String("kfc");
这两种创建方式导致创建的对象存放的位置不同。
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);
}
}