Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Java identifies unreachable code only in case of while loop? [duplicate]

If I have code like

public static void main(String args[]){
    int x = 0;
    while (false) { x=3; }  //will not compile  
}

compiler will complaint that x=3 is unreachable code but if I have code like

public static void main(String args[]){
    int x = 0;
    if (false) { x=3; }
    for( int i = 0; i< 0; i++) x = 3;   
}

then it compiles correctly though the code inside if statement and for loop is unreachable. Why is this redundancy not detected by java workflow logic ? Any usecase?

like image 499
Aniket Thakur Avatar asked Dec 19 '22 14:12

Aniket Thakur


2 Answers

As described in Java Language Specification, this feature is reserved for "conditional compilation".

An example, described in the JLS, is that you may have a constant

static final boolean DEBUG = false;

and the code that uses this constant

if (DEBUG) { x=3; }

The idea is to provide a possibility to change DEBUG from true to false easily without making any other changes to the code, which would not be possible if the above code gave a compilation error.

like image 169
Egor Avatar answered May 13 '23 09:05

Egor


The use case with the if condition is debugging. AFAIK it is explicitly allowed by the spec for if-statements (not for loops) to allow code like this:

class A {
    final boolean debug = false;

    void foo() {
        if (debug) {
            System.out.println("bar!");
        }
        ...
    }
}

You can later (or via debugger at runtime) change the value of debug to get output.

EDIT As Christian pointed out in his comment, an answer linking to the spec can be found here.

like image 25
Axel Avatar answered May 13 '23 09:05

Axel