54
class Foo{
    public static void main(String args[]){
        final int x=101;

        int y;
        if(x>100){
            y=-1;
        }
        System.out.println(y);
    }
}

Java compiler understands the condition of the if statement is always true and therefore y will always be initialized. No compile error, as expected.

class Bar{
    public static void main(String args[]){
        final int x;
        x=101;

        int y;      
        if(x>100){
            y=-1;
        }
        System.out.println(y);
    }
}

But when I break the declaration and initialization of x into two lines, the compiler does not seem to get that the condition is always true and y will always be initialized.

final int x;
x=101;
byte b;
b=x;
System.out.println(b);

Same thing happens here and the compiler gives a loss of precision error.

final int x=101;
byte b;
b=x;
System.out.println(b);

Again, the compiler can understand that x is inside the range of b.

PrashanD
  • 2,643
  • 4
  • 28
  • 58
  • Good question. I don't know the answer but it may be helpful to see the error you're getting when trying to compile it. – kentcdodds Nov 05 '12 at 15:51
  • 18
    The compiler is only so smart. It wont pick up `if(i <= Integer.MAX_VALUE)` either. I suggest you not write such code as it's confusing and it's better for the compiler to be cautious IMHO – Peter Lawrey Nov 05 '12 at 15:52
  • you are missing a } at the end of both classes... did you ever try to compile this? – amphibient Nov 05 '12 at 15:54
  • 3
    Sure I compiled it, and seem to have dropped the } ending both classes when I copied it from the IDE to the browser. – PrashanD Nov 05 '12 at 15:56
  • 1
    I am wondering, though, is there a practical setting in which you couldn't just assign i a default value first? It sounds like poor coding style to have your entire program's compileability hinge on x having a particular value, after all, the entire point of final variables is for when you use some constant several times, so you can change it more easily later. – AJMansfield Nov 05 '12 at 20:48

3 Answers3

46

As part of aiming for portability, there is a very specific set of rules for what a compiler should accept and what it should reject. Those rules both permit and require only a limited form of flow analysis when determining whether a variable is definitely assigned at its use.

See the Java Language Specification Chapter 16. Definite Assignment

The critical rule is the one in 16.2.7. if Statements, "if (e) S" case. The rule for being definitely assigned expands to:

V is assigned after if (e) S if, and only if, V is assigned after S and V is assigned after e when false.

y is the relevant V. It is unassigned before the if statement. It is indeed assigned after S, y = {y=-1;} but there is nothing making it assigned when x>100 is false.

Thus y is not definitely assigned after the if statement.

A more complete flow analysis would determine that the condition x>100 is always true, but the compiler is required by the JLS to reject the program based on these specific rules.

The final variable is fine. The rule is actually: -

"It is a compile-time error if a final variable is assigned to unless it is definitely unassigned (§16) immediately prior to the assignment."

The declaration leaves it definitely unassigned, and even the limited flow analysis can determine that x is still definitely unassigned at the assignment.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75
  • Your original answer pointed in the right direction, but the quote you use is not related to the issue: x is definitely unassigned before being assigned to. The problem is that the compiler can't determine that `y` is definitely assigned before the println statement. – assylias Nov 05 '12 at 16:20
  • That is what I was talking about in the first paragraph, but given the popularity of the question I think I'll extend my answer to be more explicit. – Patricia Shanahan Nov 05 '12 at 16:22
  • 1
    @PatriciaShanahan The underlying reason is that with `final int x = 101;`, `if(x>100)` is a constant expression, whereas with `final int x; x = 101;`, it is not a constant expression. See my answer for additional precision. – assylias Nov 05 '12 at 16:38
27

It has to do with how the compiler determines if a statement will be executed or not. It is defined in the JLS #16:

Each local variable and every blank final field must have a definitely assigned value when any access of its value occurs.

In your case, the compiler can't determine that y has been definitely assigned and gives you an error. This is because it would need to determine that the condition is always true and that is only possible if the condition in the if is a constant expression.

JLS #15.28 defines constant expressions:

A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:

  • [...]
  • Simple names (§6.5.6.1) that refer to constant variables (§4.12.4).

The JLS #4.12.4 defines constants variables as:

A variable of primitive type or type String, that is final and initialized with a compile-time constant expression, is called a constant variable.

In your case, final int x = 101; is a constant variable but final int x; x = 101; is not.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • 3
    +1 This answer is the best at getting past the symptom of `y`'s assignedness to the cause, which is `x` and the `if`. – Paul Bellora Nov 06 '12 at 03:46
  • I’m not sure I agree with the rationale for mandating definite assignment the cases of non-final variables, namely the primitive variables. That should be more on the developer’s side, not the compiler side. For example, by default, an `int` variable has a value is `0`, so why would we need to definitely assign it if we are checking if a method returns a valid value? Sure we can initialize it, but why is it so critical for the compiler to know the definite value instead of relying on the default value? – Sometowngeek Jul 29 '19 at 16:13
  • In addition, if a non-primitive variable is created, like `String`, or `Foo`, then the default is `null`. If we are trying to access it when it is null, then the runtime exception should be thrown because it is null. Or at least could point it out as a warning for IDEs to flag. – Sometowngeek Jul 29 '19 at 16:14
11

What have you done for the variable x in the second code is called blank final variable. If a final variable is not initialized when it is declared, then it is known as a blank final variable.

Many Java developers think that value of a final variable is known in the compile time. This is NOT always true. It is said that value of a blank final variable NOT known at the compile time. Hence your second code will give you a compile error. Compiler can see that you have initialized the final variable x, but compile doesn't know it's value. So compiler can't resolve the if statement. Therefor it thinks that variable y is not initialized.

You can read more about Java final variables here.

SajithA
  • 437
  • 1
  • 9
  • 23