While working with Java in eclipse I got a warning saying "dead code". What does it mean?

Java 8Object Oriented ProgrammingProgramming

A code block/statement in Java to which the control never reaches and never gets executed during the lifetime of the program is known as unreachable block/statement.

public class UnreachableCodeExample {
   public String greet() {
      System.out.println("This is a greet method ");
      return "Hello";
      System.out.println("This is an unreachable code ");
   }
   public static void main(String args[]) {
      new UnreachableCodeExample().greet();
   }
}

Dead code

A dead code is an unreachable code, but it doesn’t generate compile time error. But if you execute it in eclipse it gives you a warning.

Example

In the following Java program

 Live Demo

public class UnreachableCodeExample {
   public void greet() {
      System.out.println("This is the greet method ");
      if(true){
         return;
      }
      System.out.println("This is a dead code ");
   }
   public static void main(String args[]) {
      new UnreachableCodeExample().greet();
   }
}

Output

This is the greet method

If you run the same program in eclipse it raises a warning as −

raja
Updated on 29-Jun-2020 13:30:28

Advertisements