What are unreachable blocks in java?


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

Updated on: 29-Jun-2020

332 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements