Unreachable statement using final variable in Java

JavaServer Side ProgrammingProgramming

Unreachable statements are those that don’t get executed when the code is being executed. This could be so because −

  • There is a return statement before the code.
  • There is an infinite loop in the code.
  • The execution of the code is terminated forcibly before it executes.

Here, we will see how the unreachable statement can be used with the ‘final’ keyword −


 Live Demo

class Demo_example{
   final int a = 56, b = 99;
   void func_sample(){
      while (a < b){
         System.out.println("The first value is less than the second.");
      System.out.println("This is an unreachable statement");
public class Demo{
   public static void main(String args[]){
      Demo_example my_instance = new Demo_example();


/Demo.java:11: error: unreachable statement
   System.out.println("This is an unreachable statement");
1 error

A class named ‘Demo_example’ contains two final integers (basically like constants), and a function named ‘func_sample’, that compares the two integers. Relevant message is displayed on the console. Another class named ‘Demo’ is defined and it contains the main function. In this function, an instance of the Demo class is created, and the function ‘func_sample’ is called on this instance. Relevant output is displayed on the console.

Published on 17-Aug-2020 09:04:16