close
The Wayback Machine - https://web.archive.org/web/20240930181232/https://www.geeksforgeeks.org/unreachable-code-error-in-java/
Open In App

Unreachable Code Error in Java

Last Updated : 22 Oct, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Unreachable statements refers to statements that won’t get executed during the execution of the program are called Unreachable Statements. These statements might be unreachable because of the following reasons:

  • Have a return statement before them 
  • Have an infinite loop before them 
  • Any statements after throwing exception in a try block 

Scenarios where this error can occur: 

  • Have a return statement before them: When a return statement gets executed, then that function execution gets stopped right there. Therefore any statement after that wont get executed. This results in unreachable code error.

Example: 

Java




class GFG {
    public static void main(String args[])
    {
 
        System.out.println("I will get printed");
 
        return;
 
        // it will never run and gives error
        // as unreachable code.
        System.out.println("I want to get printed");
    }
}


  • Compile Errors: 

prog.java:11: error: unreachable statement 
System.out.println(“I want to get printed”); 
^ 
1 error 

  • Have an infinite loop before them: Suppose inside “if” statement if you write statements after break statement, then the statements which are written below “break” keyword will never execute because if the condition is false, then the loop will never execute. And if the condition is true, then due to “break” it will never execute, since “break” takes the flow of execution outside the “if” statement.

Example: 

Java




class GFG {
    public static void main(String args[])
    {
        int a = 2;
        for (;;) {
 
            if (a == 2)
            {
                break;
                // it will never execute, so
                // same error will be there.
                System.out.println("I want to get printed");
            }
        }
    }
}


  1. Compile Errors: 

prog.java:13: error: unreachable statement 
System.out.println(“I want to get printed”); 
^ 
1 error 
 

  • Any statement after throwing an exception: If we add any statements in a try-catch block after throwing an exception, those statements are unreachable because there is an exceptional event and execution jumps to catch block or finally block. The lines immediately after the throw is not executed.

Example: 

Java




class GFG {
    public static void main(String args[])
    {
 
        try {
            throw new Exception("Custom Exception");
            // Unreachable code
            System.out.println("Hello");
        }
        catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}


  • Compile Errors: 

prog.java:7: error: unreachable statement 
System.out.println(“Hello”); 
^ 
1 error 
 

  • Any statement after writing continue : If we add any statements in a loop after writing the continue keyword, those statements are unreachable because execution jumps to the top of the for loop. The lines immediately after the continue is not executed.
    Example: 
     

Java




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


  • Compile Errors: 

prog.java:6: error: unreachable statement 
System.out.println(“Hello”); 
^ 
1 error 



Previous Article
Next Article

Similar Reads

How to Convert Java Code to Kotlin Code in Android Studio?
In Google I/O 2017, Kotlin has been declared as an official language for Android app development. This language gains popularity among developers very quickly because of its similarities as well as interoperable with Java language. One can mix code of Java and Kotlin while designing an Android project. Some of the major challenges faced by develope
4 min read
How to Convert Kotlin Code to Java Code in Android Studio?
Java programming language is the oldest and most preferred language for Android app development. However, during Google I/O 2017, Kotlin has been declared as an official language for Android development by the Google Android Team. Kotlin has gained popularity among developers very quickly because of its similarities as well as interoperable with th
4 min read
Difference Between Source Code and Byte Code
Source code refers to the high-level code or assembly code that is generated by a human/programmer. Source code is easy to read and modify. It is written by the programmer by using any High-Level Language or Intermediate language which is human-readable. Source code contains comments that the programmer puts for better understanding. Source code is
3 min read
Difference between Byte Code and Machine Code
Byte code is an intermediate code between the source code and machine code. It is a low-level code that is the result of the compilation of a source code which is written in a high-level language. It is processed by a virtual machine like Java Virtual Machine (JVM). Byte code is a non-runnable code after it is translated by an interpreter into mach
3 min read
How to Fix java.io.StreamCorruptedException: invalid type code in Java?
There are several problems been faced which are as follows: When you write an object in a file using serialization in java for the first time, no problem arises in reading the file afterward, even when you write multiple objects in one go.Now, when next time you try to append new objects (of the same type) to that file using serialization, writing
6 min read
How to Fix int cannot be dereferenced Error in Java?
Here, we will follow the below-mentioned points to understand and eradicate the error alongside checking the outputs with minor tweaks in our sample code Introduction about the error with exampleExplanation of dereferencing in detailFinally, how to fix the issue with Example code and output. If You Got this error while you're compiling your code? T
4 min read
Java Error - All illegal Modifier Combinations For Methods w.r.t Abstract
In Java, we can apply a variety of modifiers to classes, methods, blocks, and variables and each one has a different use case and all of these primarily define how and where those classes, methods, blocks, and variables can be accessed and modified. But not all the modifiers can be applied simultaneously due to some contradiction among their defini
6 min read
Why Array.length() gives error when used in Java?
What will happen if we use Array.length()? Before moving to the reason why we cannot write Array.length(), let us first see what will happen if we try to use the Array.length() in the Java code. Below is a code snippet to check that. Java Code import java.io.*; class GFG { public static void main(String[] args) { int arr[] = new int[3]; int size =
3 min read
How to Resolve The Cannot Find Symbol Error in Java?
The Cannot Find Symbol Error in Java error occurs when the Java compiler cannot find a symbol that you are trying to reference in your code. In this article, we will explore how to resolve the "Cannot Find Symbol" error in Java. The "Cannot Find Symbol" error occurs when you are trying to reference a symbol that has not been defined or imported pro
5 min read
Method overloading and null error in Java
In Java it is very common to overload methods. Below is an interesting Java program. Java Code public class Test { // Overloaded methods public void fun(Integer i) { System.out.println(&quot;fun(Integer ) &quot;); } public void fun(String name) { System.out.println(&quot;fun(String ) &quot;); } // Driver code public static void main
2 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java Generics to Code Efficiently in Competitive Programming
Templates are the foundation of generic programming, which involve writing code in a way that is independent of any particular type. These powerful tools can be used for writing our code effectively. Some cool tricks that may be used in Competitive Programming are given as follows: Fast Input/Output: This uses the time advantage of BufferedReader a
9 min read
Java Competitive Programming Setup in VS Code with Fast I/O and Snippets
Though C++ is the dominating language in the competitive programming universe, there is a fair share of users who still continue to use Java as it has been there seen in the development arena and at the same time can be used competitive programming being fast as it can be toggled to and from where python being slowest among dynamic is hardly seen i
8 min read
Byte Code in Java
Byte Code Byte Code can be defined as an intermediate code generated by the compiler after the compilation of source code(JAVA Program). This intermediate code makes Java a platform-independent language. How is Byte Code generated? Compiler converts the source code or the Java program into the Byte Code(or machine code), and secondly, the Interpret
2 min read
Introduction to Checkstyle Plugin for Checking Java Code Quality
Checkstyle is a development tool to help programmers to write Java code that sticks to a coding standard. It automates the process of checking Java code. It is an open-source tool that checks code against a configurable set of rules. It allows you to define your own set of rules and check your code against it. These rules can be used in your IDE or
5 min read
How to Generate Code Coverage Report with JaCoCo in Java Application?
Testing is a most important part of a software development lifecycle. Without testing, the software is not ready for deployment. To test Java applications we mostly used Junit. JUnit framework is a Java framework that is used for testing. And now, JUnit is used as a standard when there is a need to perform testing in Java. But what is Code Coverage
4 min read
Java String Manipulation: Best Practices For Clean Code
In Java, a string is an object that represents a sequence of characters. It is a widely used data type for storing and manipulating textual data. The String class in Java is provided as a part of the Java standard library and offers various methods to perform operations on strings. Strings are fundamental to Java programming and find extensive usag
7 min read
How to Run the Java Code in Git Bash?
Git Bash is a command-line interface that provides a Unix-like environment on Windows. You can use it to compile and run Java programs just as you would in traditional terminals on Linux or macOS. Step to Run Java Code in Git Bash:1. Install JavaMake sure you have Java installed on your Windows computer. You can download and install Java from the o
2 min read
Guidelines for adding C++/Java/Python/C#/JavaScript code to existing articles of GeeksforGeeks
You may please first go through code writing instructions: Guide to write an articleGuidelines for writing code for an existing code on GeeksforGeeks: This guideline is for those who directly write in https://write.geeksforgeeks.org/. To write code in multiple languages use the format shown below: Click on the Add Code button present in the Toolbar
3 min read
How to Run Java Code in Node.js ?
Running Java code within a Node.js environment can be useful for integrating Java-based libraries or leveraging Java's robust capabilities within a JavaScript application. This article will guide you through the steps required to execute Java code from a Node.js application, covering various methods and tools available to facilitate this integratio
2 min read
12 Tips to Optimize Java Code Performance
While working on any Java application we come across the concept of optimization. It is necessary that the code which we are writing is not only clean, and without defects but also optimized i.e. the time taken by the code to execute should be within intended limits. In order to achieve this, we need to refer to the Java coding standards and review
8 min read
How to avoid Compile Error while defining Variables
Variables: A variable is the name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. A variable is only a name given to a memory location, all the operations done on the variable effects that memory location. All the variables must be declared before use.
3 min read
Spring Boot - Service Class Example for Displaying Response Codes and Custom Error Codes
Sometimes the error or status messages in webpages would be different from the default error message thrown by Tomcat (or any other server). An important reason for this is websites want to look unique in their approach to their users. So, a customized page for displaying status codes is always better than the standard template. Spring Boot makes i
6 min read
Line Plot in R with Error Bars
A line plot is a graphical representation of a series of data. Line plots are widely used in data visualization. In we use ggplot2( ) and plot( ) function to create line plot. Error bars act as a visual enhancement that help us to see variability of the plotted data. Error Bars are used to show standard error, standard deviation i.e. with the help
2 min read
Spring Boot - 415 Unsupported Media Type Error for Post Request for @ManyToMany Relation
Spring Boot is a widely used Java-based framework that simplifies the process of building enterprise applications by providing an opinionated and flexible approach to development. It offers features such as auto-configuration, embedded servers, and a wide range of tools and libraries for building various types of applications. Spring Boot supports
4 min read
Correcting EOF error in python in Codechef
EOF stands for End Of File. Well, technically it is not an error, rather an exception. This exception is raised when one of the built-in functions, most commonly input() returns End-Of-File (EOF) without reading any data. EOF error is raised in Python in some specific scenarios: Sometimes all program tries to do is to fetch something and modify it.
3 min read
Spring Boot - Customize Whitelabel Error Page
In the Spring Boot ecosystem, when there is no custom error page to handle a specific error, Spring Boot by default handles the error with the help of the Whitelabel error page. This is the default Whitelabel error page. We can also customize this whitelabel error page. In this article, let us discuss some approaches to customize this Whitelabel er
4 min read
Implement Form Validation (Error to EditText) in Android
Many of the already existing Android applications when it comes to the forms include user details. If the user enters the wrong information into the text fields or if the user leaves the text fields without filling them, there is a need to provide certain alert information to the TextFields which are unfilled and which contain the wrong information
6 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
How to Build a QR Code Android App using Firebase?
QR (Quick Response) code is a type of two-dimensional barcode that contains information encoded in a pattern of black and white squares. It was first developed in 1994 by a company named Denso Wave. Qr codes can be scanned by a smartphone or a dedicated QR code scanner, which uses the device's camera to read the code and extract the information sto
6 min read