[Java] final的作用(包含String的编译优化) →→→→→进入此内容的聊天室

来自 , 2019-06-03, 写在 Java, 查看 104 次.
URL http://www.code666.cn/view/2de5d166
  1. package fengke.finalandstatic;
  2.  
  3. /**
  4.  * final的作用
  5.  *
  6.  * @author 锋客
  7.  *         这里面就是final变量和普通变量的区别了,当final变量是基本数据类型以及String类型时,
  8.  *         如果在编译期间能知道它的确切值,则编译器会把它当做编译期常量使用。
  9.  *         也就是说在用到该final变量的地方,相当于直接访问的这个常量,不需要在运行时确定。
  10.  *         这种和C语言中的宏替换有点像。因此在上面的一段代码中,由于变量b被final修饰,
  11.  *         因此会被当做编译器常量,所以在使用到b的地方会直接将变量b 替换为它的 值。 而对于变量d的访问却需要在运行时通过链接来进行。
  12.  *         想必其中的区别大家应该明白了,不过要注意,只有在编译期间能确切知道final变量值的情况下, 编译器才会进行这样的优化。
  13.  *        
  14.  *   总结:      编译时不会执行方法;
  15.  */
  16.  
  17. public class FinalAndStaticAndString {
  18.  
  19.         public static void main(String[] args) {
  20.          System.out.println("编译优化测试:");
  21.      test1();
  22.      System.out.println("编译优化详解测试:");
  23.      test2();
  24.      System.out.println("编译优化测试(static、final同时使用)");
  25.      test3();
  26.         }
  27.     /*
  28.      * 测试字符串编译优化:
  29.      * final与非final的区别
  30.      */
  31.         public static void test1() {
  32.                 String a = "hello2";
  33.                 final String b = "hello";
  34.                 String d = "hello";
  35.                 String c = b + 2;
  36.                 String e = d + 2;
  37.                 System.out.println("final String b = 'hello';   "+(a == c));
  38.                 System.out.println("String d = 'hello';    "+(a == e));
  39.         }
  40.     /*
  41.      * 测试字符串编译优化:
  42.      * final后直接写字符  与  final后调用方法的区别;
  43.      * 结果:编译时不会执行有final属性的变量的方法
  44.      */
  45.         public static void test2() {
  46.                 String a = "hello2";
  47.                 //b在编译阶段不会进行优化所以
  48.                 final String b = getHello();
  49.                 String c = b + 2;
  50.                 System.out.println("final String b = getHello();   "+(a == c));
  51.  
  52.         }
  53.         /*
  54.          *注意:
  55.          *静态方法中不能写有静态变量,需写在其外面;
  56.          *static与final连用,也不能使字符串变量在编译阶段调用方法,被当做编译器常量;
  57.          *
  58.          *
  59.          */
  60.         static final  String test3_b=getHello();
  61.         public static void test3(){
  62.                 String a="hello2";
  63.              String c=test3_b+2;
  64.              System.out.println("static final  String test3_b=getHello();   "+(a==c));
  65.        
  66.         }
  67.        
  68.  
  69.         public static String getHello() {
  70.                 return "hello";
  71.         }
  72.  
  73. }
  74.  

回复 "final的作用(包含String的编译优化)"

这儿你可以回复上面这条便签

captcha