Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this "s" effectively final?

Tags:

java

Here is some sample code (assuming Java 8).

while (true){
    Socket s = serverSocket.accept();
    // some code here ... we don't assign anything to s again here ... 
}

Is s effectively final inside the loop?

like image 501
peter.petrov Avatar asked Feb 11 '16 22:02

peter.petrov


1 Answers

Assuming that s isn't assigned past its declaration, then yes, s is "effectively final", according to the JLS, Section 4.12.4, which defines it, in your case:

Certain variables that are not declared final are instead considered effectively final:

  • A local variable whose declarator has an initializer (§14.4.2) is effectively final if all of the following are true:

    • It is not declared final.

    • It never occurs as the left hand side in an assignment expression (§15.26). (Note that the local variable declarator containing the initializer is not an assignment expression.)

    • It never occurs as the operand of a prefix or postfix increment or decrement operator (§15.14, §15.15).

  • A local variable whose declarator lacks an initializer is effectively final if all of the following are true:

    • It is not declared final.

    • Whenever it occurs as the left hand side in an assignment expression, it is definitely unassigned and not definitely assigned before the assignment; that is, it is definitely unassigned and not definitely assigned after the right hand side of the assignment expression (§16 (Definite Assignment)).

    • It never occurs as the operand of a prefix or postfix increment or decrement operator.

You only assign s at declaration time, and being an object it can't be the operand of an increment or decrement operator, so it is effectively final.

It also states that a variable can be effectively final in another case, if it's not assigned when it's declared, as long it's only assigned once, it's definitely not assigned before the declaration, and it's definitely assigned after the declaration.

Also, at the end of that section, it states:

If a variable is effectively final, adding the final modifier to its declaration will not introduce any compile-time errors. Conversely, a local variable or parameter that is declared final in a valid program becomes effectively final if the final modifier is removed.

You should be able to make it explicitly final without causing a compiler error. If so, it's effectively final.

like image 148
rgettman Avatar answered Sep 28 '22 15:09

rgettman