Unreachable Code Error in Java

JavaServer Side ProgrammingProgramming

Unreachable code error occurs when the code can’t be compiled due to a variety of reasons, some of which include: infinite loop, return statement before the unreachable line of code.

Let us see an example −

Example

 Live Demo

public class Demo{
   public static void main(String args[]){
      int val = 5;
      for (;;){
         if (val == 5){
            break;
            System.out.println("If the condition is not true, this line would be printed. ");
         }
      }
   }
}

Output

/Demo.java:11: error: unreachable statement
System.out.println("If the condition is not true, this line would be printed. ");
^
1 error

A class named Demo contains the main function, and a value is defined, and this value is checked for and an empty ‘for’ loop is run. If the value is found, the control breaks out of the loop otherwise prints a message. Since it is an infinite loop, it gives an unreachable statement error.

raja
Published on 09-Jul-2020 06:39:50
Advertisements