Resolving Java unreachable statement

Resolve Java unreachable statement

The java unreachable statement is a compilation error thrown when the compiler detects a code that was not executed as part of the program. When you reach this state, it means that your program would not be executed anymore, and hence this piece of code is unnecessary and should be removed.

There are a couple of reasons that might result to this issue. Let’s discuss some of the possible causes and how to solve this:

Return Statement

Function execution ends when a return statement is called. Any statement within the function that comes after the return statement will not be executed. Thus, writing your code after this return statement results in an unreachable java statement.
Example:

public class Main
{
	public static void main(String[] args) {
	    
	    System.out.println("The java unreachable statement");
	return;
 
        System.out.println("I will not  be printed");
	}
}

Output:

Main.java:16: error: unreachable statement
        System.out.println("I will not  be printed");
        ^
1 error

In the above example, we have a print statement after the return statement. Using the return statement, we tell the control to go back to the caller explicitly; hence, any code after this will be considered a dead code as it will never be executed.

To solve this error, double-check the flow of your code and make sure the return statement is always the last line of code in a function.
Example:

public class Main
{
	public static void main(String[] args) {
	    
	  System.out.println("The java unreachable statement");
      
      System.out.println("I will not  be printed");
	return;
 
        
	}
}

Output:

The java unreachable statement
I will not  be printed

Infinite loop

An infinite loop is an endless loop. Its code keeps reiterating the loop location hence any code written after the loop will never be executed.
Example:

public class Main
{
	public static void main(String[] args) {
	    
	  for(;;){
       break;
        
       System.out.print("I'm outside the infinite loop");
	  }
        
	}
}

Output:

Main.java:10: error: unreachable statement
       System.out.print("I'm outside the infinite loop");
       ^
1 error

The infinite loop code executes the loop forever. This may consume the CPU, preventing other programs from being executed. As programmers, we block or sleep the loop by adding the break statement to let other applications run. Any code after the break statement will never be executed. To solve this, make sure no code is written after sleeping or blocking the infinite loop.

Any statement after continue

The continue statement enforces the execution of a loop in a code. Any statement after the continue statement will not be executed because the execution jumps to the top of the loop to continue with the execution of the previous code.
Example:

public class Main
{
	public static void main(String[] args) {
	    
	   for (int j = 0; j < 5; j++)
        {
             System.out.println(j);
            continue;
           System.out.println("Java unreachable statement");
       }        
	}
}

Removing the print system outside the function will make the obsolete code execute.

public class Main
{
	public static void main(String[] args) {
	    
	   for (int j = 0; j < 5; j++)
        {
             System.out.println(j);
            continue;
          
        }

      System.out.println("Java unreachable statement");
        
	}
}

Output:

0
1
2
3
4
Java unreachable statement

Any statement after break

Break statements are used in terminating a loop. Any code after the break statement means the code will not be compiled since the program’s running was terminated by the break. This will result in the java unreachable statement.

public class Main
{
	public static void main(String[] args) {
	    
	   for (int i = 0; i < 5; i++)
        {
            System.out.println(i);
            break;
        System.out.println("Java unreachable statement");
          
        } 
	}
}

Output:

Main.java:10: error: unreachable statement
        System.out.println("Java unreachable statement");
        ^
1 error

Any statement after throwing an exception

Any statements added in a try-catch block after throwing an exception is a dead code. This is because the exceptional event forces the execution to jump to the catch block statement.
Example:

public class Main
{
	public static void main(String[] args) {
	    
	   try {
            throw new Exception("New Exception");
            //java Unreachable code
            System.out.println("Dead code");
        }
        catch (Exception exception) {
           
            System.out.print("Home");
        }
	}
}

Output:

Main.java:9: error: unreachable statement
            System.out.println("Dead code");
            ^
1 error

Removing the statement after the try-catch block prints ‘home.’

Home

Unreachable while loop

A while loop is a repeated block of code until a specific condition is met or true. If the condition in a while loop is never met or true, the code inside the loop will never run, resulting in an unreachable statement.

public class Main
{
	public static void main(String[] args) {
	    
	   while(2>5){
            System.out.println("The greates value is 5");
      }
	}
}

Output:

Main.java:6: error: unreachable statement
	   while(2>5){
	             ^
1 error

In the above code, 2 will ever be greater than 5; hence this condition will never be true. Any statement after this condition will never be executed.

How to solve java unreachable statement

Solving this error may entirely depend on your programming skills. However, there are key things that you should always not do as a programmer.

  1. Do not place any code after the infinite loop
  2. You should not put any statements after the return, break and continue statements.
  3. Avoid puttig any code after the tyr-catch block

Conclusion

It’s always good as a programmer to examine the flow of your code to make sure that every statement in the code is reachable. You can always draw a flowchart to get a deep understanding of the flow of loops. In this tutorial, we have discussed the possible causes of the java unreachable statement and how to solve it.


Happy learning!!

Similar Posts

  • Java Array tool (with examples)

    In Java, the array object is used to store several pieces of information. This utility sequentially assigns certain memory regions based on the array size. In Java, an array object can hold any form of primitive or non-primitive data. That is, it can hold a list of integers, strings, objects, and so on. As a result, all of the values in an array can be data of a specific datatype. In some programming languages, the index value of an array starts at 0. In Java, you can declare both single-dimensional and multi-dimensional arrays. Using an array, you may easily arrange and sort a list of data.

  • Method Overloading in Java with examples

    Method Overloading takes place when a class has many methods with the same name but different parameters. If we only need to do one operation, having the methods named the same improves the program’s readability. If you define the method as a(int, int) for two parameters and b(int, int, int) for three parameters, it may be difficult for you and other programmers to grasp the behavior. As a result, we use overloading to figure out the program quickly.

  • TreeMap in Java

    Besides the AbstractMap Class, Java’s TreeMap discreetly implements the Map interface and NavigableMap. Depending on which constructor is used, the map is sorted either by the natural ordering of its keys or by a Comparator specified at map creation time.

  • How to call a Method in Java

    A method in Java refers to a group of lines that performs a single action or operation. It is commonly used because it allows code to be reused, which implies that you can write once and use it many times. It also allows for easy customization.
    Upon calling the given method, it will carry out the specified work as soon as the compiler can read the name.

One Comment

  1. Given an integer n, your task is to print the pattern as shown in example:-
    For n=5, the pattern is:
    1
    1 2 1
    1 2 3 2 1
    1 2 3 4 3 2 1
    1 2 3 4 5 4 3 2 1
    1 2 3 4 3 2 1
    1 2 3 2 1
    1 2 1
    1
    please solve this problem

Leave a Reply

Your email address will not be published. Required fields are marked *