java - difference of final variable in code block -


i see code like

public void foo() {     final int x = 3;     final object z = new object();     ....... } 

i know x can't modified since final there other reason/explaination that? compare without using final? or developer added final variable because likes to. thanks.

declaring variable immutable (final) pretty reason itself. besides adding clarity code, provides valuable information compiler might able optimize code better when knows things not going change.

one other reason might hidden in example behind ellipsis: if there closure somewhere in function, references local variables, not compile if not final. imagine example:

public void foo() {     final int x = 3;     final object z = new object();     new thread() {         public void run() {             for(int = 0; < x; i++) {                 system.out.println(z);             }         }     }.start(); } 

for work, x , z must declared final. why? well, local variables created on stack, and, once function returns, disappear completely. code inside thread.run() method defined here, might still executing, after function created returns. because variables final, values known jvm @ time closure created, can copy values closure. if weren't final, not possible, because copies become stale original value modified.


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -