菜鸟笔记 -- Chapter 5.4 Dead Code

Posted Abri

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了菜鸟笔记 -- Chapter 5.4 Dead Code相关的知识,希望对你有一定的参考价值。

不知道有没有前辈注意过,当你编写一段“废话式的代码时”会给出一个Dead Code警告,点击警告,那么你所写的废物代码会被编译器消除,那么如果你不理睬这个警告呢?编译后会是什么样的呢?下面我们写点代码,来查看一下编译后的结果,这里使用反编译工具jd-gui.exe。代码如下:

package cn.five.four;

public class Test {
    public static void main(String[] args) {
        int a = 7;
        int b = 9;
        test1();
        test2(a, b);
    }
    //废话代码--条件语句中,已经可以确定条件真假的会被认为是死代码(Dead Code),也叫无效代码
    public static void test1(){
        if(5>6){
            System.out.println("jdk1.7输出废话代码!!");
        }else {
            System.out.println("都不用编译,你自己都知道要输出这段代码!");
        }
    }
    //条件不确定的不是死代码
    public static void test2(int a,int b){
        if(a>b){
            System.out.println("条件语句块中只有一句代码!");
        }else if (a == b) {
            System.out.println("条件语句块中只有两句代码!");
            System.out.println("条件语句块中只有两句代码!");
        }else {
            System.out.println("会输出这句吗?");
        }
    }
}

反编译

package cn.five.four;

import java.io.PrintStream;

public class Test
{
  public static void main(String[] args)
  {
    int a = 7;
    int b = 9;
    test1();
    test2(a, b);
  }
  
  public static void test1()
  {
    System.out.println("都不用编译,你自己都知道要输出这段代码!");
  }
  
  public static void test2(int a, int b)
  {
    if (a > b)
    {
      System.out.println("条件语句块中只有一句代码!");
    }
    else if (a == b)
    {
      System.out.println("条件语句块中只有两句代码!");
      System.out.println("条件语句块中只有两句代码!");
    }
    else
    {
      System.out.println("会输出这句吗?");
    }
  }
}

 上面我们知道了编译器在编译后会自动将死代码优化为已知的结果,这是编译器的优化。不过聪明如我们的程序员应该不至于写出这样的代码,在这里仅仅是表明编译器也是可以优化我们的代码的。

以上是关于菜鸟笔记 -- Chapter 5.4 Dead Code的主要内容,如果未能解决你的问题,请参考以下文章

菜鸟笔记 -- Chapter 6 面向对象

菜鸟笔记 -- Chapter 3.4 环境变量

菜鸟笔记 -- Chapter 6.4.3 多态

菜鸟笔记 -- Chapter 09 常见类和接口

菜鸟笔记 -- Chapter 3.2 Java简介

菜鸟笔记 -- Chapter 3 Java开发前言