package fengke.finalandstatic; /** * final的作用 * * @author 锋客 * 这里面就是final变量和普通变量的区别了,当final变量是基本数据类型以及String类型时, * 如果在编译期间能知道它的确切值,则编译器会把它当做编译期常量使用。 * 也就是说在用到该final变量的地方,相当于直接访问的这个常量,不需要在运行时确定。 * 这种和C语言中的宏替换有点像。因此在上面的一段代码中,由于变量b被final修饰, * 因此会被当做编译器常量,所以在使用到b的地方会直接将变量b 替换为它的 值。 而对于变量d的访问却需要在运行时通过链接来进行。 * 想必其中的区别大家应该明白了,不过要注意,只有在编译期间能确切知道final变量值的情况下, 编译器才会进行这样的优化。 * * 总结: 编译时不会执行方法; */ public class FinalAndStaticAndString { public static void main(String[] args) { System.out.println("编译优化测试:"); test1(); System.out.println("编译优化详解测试:"); test2(); System.out.println("编译优化测试(static、final同时使用)"); test3(); } /* * 测试字符串编译优化: * final与非final的区别 */ public static void test1() { String a = "hello2"; final String b = "hello"; String d = "hello"; String c = b + 2; String e = d + 2; System.out.println("final String b = 'hello'; "+(a == c)); System.out.println("String d = 'hello'; "+(a == e)); } /* * 测试字符串编译优化: * final后直接写字符 与 final后调用方法的区别; * 结果:编译时不会执行有final属性的变量的方法 */ public static void test2() { String a = "hello2"; //b在编译阶段不会进行优化所以 final String b = getHello(); String c = b + 2; System.out.println("final String b = getHello(); "+(a == c)); } /* *注意: *静态方法中不能写有静态变量,需写在其外面; *static与final连用,也不能使字符串变量在编译阶段调用方法,被当做编译器常量; * * */ static final String test3_b=getHello(); public static void test3(){ String a="hello2"; String c=test3_b+2; System.out.println("static final String test3_b=getHello(); "+(a==c)); } public static String getHello() { return "hello"; } }