final修饰符(4)-"宏替换"
对于一个final变量来说,不管它时类变量,实例变量还是局部变量,只要满足三个条件,这个final变量就不再是一个变量,而是一个直接量.final变量的一个重要用途,就是定义"宏变量"
1,使用final修饰符修饰
2,在定义该final变量时指定了初始值
3,该初始值可以在编译时就被确定下来
package com.j1803.finalTest;
public class FinalRespleceTest {
public static void main(String[] args) {
//定义"宏变量"
final int a=5;
final int b=5+2;
final String str1="zhou"+"wen";
final String str2="zhouwen"+9.90;
final String str3="zhouwen"+String.valueOf(9.90);
System.out.println(a);
System.out.println(b);
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
System.out.println(str1=="zhouwen");
System.out.println(str2=="zhouwen9.90");
System.out.println(str3=="zhouwen9.90");
/*answer:
5
7
zhouwen
zhouwen9.9
zhouwen9.9
true
false
false
*/
System.out.println("==============================");
String s1="zhouwen";
//s2变量引用的字符串可以在编译时就确定下来
//因此s2直接引用常量池中已经存在的"zhouwen"字符串
String s2="zhou"+"wen";
System.out.println(s1==s2);
String s11="zhou";
String s21="wen";
String s3=s11+s21;
System.out.println(s1==s3);
final String s12="zhou";
final String s22="wen";
String s4=s12+s22;
System.out.println(s1==s4);
answer
==============================
true
false
true
注意:只有在定义该变量时指定初始值才会有"宏变量"的效果
//定义"宏变量"
final int a=5;
final int b=5+2;
final String str1="zhou"+"wen";
final String str2="zhouwen"+9.90;
final String str3="zhouwen"+String.valueOf(9.90);
System.out.println(a);
System.out.println(b);
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
System.out.println(str1=="zhouwen");
System.out.println(str2=="zhouwen9.90");
System.out.println(str3=="zhouwen9.90");
/*answer:
5
7
zhouwen
zhouwen9.9
zhouwen9.9
true
false
false
*/
System.out.println("==============================");
String s1="zhouwen";
//s2变量引用的字符串可以在编译时就确定下来
//因此s2直接引用常量池中已经存在的"zhouwen"字符串
String s2="zhou"+"wen";
System.out.println(s1==s2);
String s11="zhou";
String s21="wen";
String s3=s11+s21;
System.out.println(s1==s3);
final String s12="zhou";
final String s22="wen";
String s4=s12+s22;
System.out.println(s1==s4);
answer
==============================
true
false
true
注意:只有在定义该变量时指定初始值才会有"宏变量"的效果