Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an error issued with an if statement in Java even though it is always true? [duplicate]

Possible Duplicate:
Compiler complains about “missing return statement” even though it is impossible to reach condition where return statement would be missing

The following method in Java compiles fine.

public String temp() {
    while(true) {
        if(true) {
            // Do something.
        }
    }
}

The method has an explicit return type which is java.lang.String with no return statement though it compiles fine. The following method however fails to compile.

public String tempNew() {
    if(true) {
        return "someString";
    }        
}

A compile-time error is issued indicating "missing return statement" even though the condition specified with the if statement is always true (it has a boolean constant that is never going to be changed neither by reflection). The method must be modified something like the following for its successful compilation.

public String tempNew() {
    if(true) {
        return "someString";
    } else {
        return "someString";
    }
}

or

public String tempNew() {
    if(true) {
        return "someString";
    }

    return "someString";
}

Regarding the first case with the while loop, the second case appears to be legal though it fails to compile.

Is there a reason in the second case beyond one of the compiler's features.

like image 919
Tiny Avatar asked Oct 20 '12 17:10

Tiny


People also ask

What is the problem with IF statement?

1. What is the problem with IF statement? Explanation: The IF statement has a priority according to which conditions are being tested. Whenever it is found to be true, all the following ELSIF statements are skipped and the END IF is executed.

What happens when the condition in an IF block is true?

When the condition after if is true, only the first block is executed. The else block is only executed when the condition is false.

Why is Java skipping my IF statement?

The if statement is skipped because you have a bug and you don't yet fully understand what you're doing. That's normal for a newbie. Learn how to debug by using your IDE's facilities and using println statements. You'll get it if you work at it.

Why is my IF ELSE statement not working?

If you are getting an error about the else it is because you've told the interpreter that the ; was the end of your if statement so when it finds the else a few lines later it starts complaining. A few examples of where not to put a semicolon: if (age < 18); if ( 9 > 10 ); if ("Yogi Bear". length < 3); if ("Jon".


1 Answers

Because it is dead code. The dead code analysis is done in a separate pass to the method return analysis, which does some more in-depth analysis that looks inside branch conditions.

like image 186
Ravindra Bagale Avatar answered Nov 15 '22 21:11

Ravindra Bagale