3

If have the following code I correctly get an warning in eclipse at the else if code :

final int x = 8;
if (x < 10) {
    System.out.println(x);
} else if (x < 5) {
    System.out.println(x);
}

But I don't get any warning if I replace the line

final int x = 8;

with

final int x = getX();

getX() is defined somewhere.

What is the reason for this?

fastcodejava
  • 39,895
  • 28
  • 133
  • 186

7 Answers7

11

JVM knows that x always would be less than 10 in compile-time, but if you replace x declaration

final int x = getX();

JVM will know x value to compare only in runtime

Related questions:

Community
  • 1
  • 1
bsiamionau
  • 8,099
  • 4
  • 46
  • 73
  • 3
    Question: if getX() is something like int getX() {return 8;}, will it sitll be a problem? – smk Mar 05 '13 at 18:44
3
final int x = 8;
    if (x < 10) {
        System.out.println(x);
    } else if (x < 5) {
        System.out.println();
    }

Here you declared value as 8.

so if will execute.There is no possibility to execute else.

But in second case first we dont know the value.In runtime only it know.

PSR
  • 39,804
  • 41
  • 111
  • 151
0

if you write final int x = 8; the compiler knows for sure that x < 10 and the if branch is always executed, while in the second case it cannot know the value returned by the called function.

niculare
  • 3,629
  • 1
  • 25
  • 39
0

At compile time, the compile know that x will always be 8. But if you use a function, it doesn't drill down into that.

Andres Olarte
  • 4,380
  • 3
  • 24
  • 45
0

A final primitive is a compile time constant, so it can do the unreachable code check when compiling. In this case, the compiler knows x = 8 and can determine the results of the if statement accordingly.

For the getX() approach, it won't do that check at compile time. This means you won't see that warning.

thegrinner
  • 11,546
  • 5
  • 41
  • 64
0
if (8 < 10) {
  //Executing code
} else {
  if (8 < 5) {
    //Alternative code
  }
}

I believe this is the essential equivalent of how your code is read by the compiler (someone with more knowledge than I may be able to correct me. Scratch that, I'm certain they can correct me).

With that said if you look at the logical sequence of your steps, you'll see that the compiler has already determined the steps of execution and can determine that the second if is never satisfied. If you use getX() alternatively though the compiler cannot make those assumptions.

Grambot
  • 4,370
  • 5
  • 28
  • 43
0

If this holds x<5

Then this also holds x<10.

Therefore, the second part will never execute even the value in x is unknown.

celik
  • 174
  • 1
  • 11