Unreachable Code Error in Java
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
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:
classGFG {publicstaticvoidmain(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");}}chevron_rightfilter_noneCompile 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:
classGFG {publicstaticvoidmain(String args[]){inta =2;for(;;) {if(a ==2) {break;// it will never execute, so// same error will be there.System.out.println("I want to get printed");}}}}chevron_rightfilter_noneCompile Errors:
prog.java:13: error: unreachable statement
System.out.println(“I want to get printed”);
^
1 error
Recommended Posts:
- Unreachable statement using final and non-final variable in Java
- Bit Stuffing error detection technique using Java
- Method overloading and null error in Java
- Java | CDMA (Code Division Multiple Access)
- How to avoid Compile Error while defining Variables
- Code Optimization Technique (logical AND and logical OR)
- Java.util.LinkedList.poll(), pollFirst(), pollLast() with examples in Java
- Java.util.concurrent.Phaser class in Java with Examples
- Java.util.Collections.rotate() Method in Java with Examples
- Java.util.BitSet class methods in Java with Examples | Set 2
- Java.util.Collections.disjoint() Method in java with Examples
- Java.util.LinkedList.offer(), offerFirst(), offerLast() in Java
- Java lang.Long.lowestOneBit() method in Java with Examples
- Java.util.function.LongPredicate interface in Java with Examples
- Java lang.Long.numberOfTrailingZeros() method in Java with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



