What are unreachable blocks in java?

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.

Generally, it happens whenever a piece of code has

  • A return statement before it.
  • An infinite loop before it.

Java does not support unreachable code. If you have any such statements, (which are unreachable) Java compiler raises a compile time error.

Example1

In the following Java program, the class UnreachableCodeExample has a method named greet which returns a String value. After the return statement it has a print statement.

 Live Demo

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();
   }
}

Compile time error

Since we have a return Statement, before the println method call, in the greet method it is unreachable. If you compile this program it generates the following compile time error −

Output

UnreachableCodeExample.java:5: error: unreachable statement
System.out.println("This is an unreachable code ");
^
UnreachableCodeExample.java:6: error: missing return statement
}
^
2 errors

Example2

In the following Java program, the class UnreachableCodeExample has a method named greet it has an infinite while loop which is followed by a print statement.

 Live Demo

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

Compile time error

Since we have an infinite loop, before the println method call, in the greet method it is unreachable. If you compile this program it generates the following compile time error −

UnreachableCodeExample.java:6: error: unreachable statement
System.out.println("This is an unreachable code ");
       ^
1 error
raja
Published on 03-Jul-2019 13:32:47
Advertisements