Unreachable code in Java is considered an error.

What does an unreachable code mean?

  • 3
    A code that cannot be executed under any circumstances, which is possible to calculate at the compilation stage. For example, in return 3; int x = 2 return 3; int x = 2 last expression will be unattainable - etki

2 answers 2

The one in which the program will never go, and which leads to a compile-time error. For example:

 public int method() { int i = 1; return i; i++; // послСдняя ΠΊΠΎΠΌΠ°Π½Π΄Π° Π½ΠΈΠΊΠΎΠ³Π΄Π° Π½Π΅ выполнится, // компилятор Π²Ρ‹Π²Π΅Π΄Π΅Ρ‚ сообщСниС ΠΎΠ± ошибкС; // это нСдостиТимый ΠΊΠΎΠ΄ } 

And the following code is also unreachable (will also lead to a compile-time error):

 while (false) { x=3; } 

And here is another example:

 public static final CONST = 1; if (CONST == 1) { //Π­Ρ‚ΠΎΡ‚ ΠΊΠΎΠ΄ Π±ΡƒΠ΄Π΅Ρ‚ Π²Ρ‹ΠΏΠΎΠ»Π½ΡΡ‚ΡŒΡΡ всСгда } else { //Π­Ρ‚ΠΎΡ‚ ΠΊΠΎΠ΄ Π½ΠΈΠΊΠΎΠ³Π΄Π° Π½Π΅ выполнится } 

The code in the else block will never be executed, but in the technical sense this code is not "unreachable", since no compile-time error will occur.

See more here .

This is the code instructions that are unattainable when executed. To get this error, just write something after the keyword return; because the method ends after it.

Example:

 void wrongMethod(){ //some code here return;//Π²Ρ‹Ρ…ΠΎΠ΄ΠΈΠΌ ΠΈΠ· ΠΌΠ΅Ρ‚ΠΎΠ΄Π° - дольшС Π½ΠΈΡ‡Π΅Π³ΠΎ Π½Π΅ выполнится ΠΈ компилятор это Π½Π΅ пропустит System.out.println(); //ошибка компиляции }