{"id":1172,"date":"2012-05-26T23:28:55","date_gmt":"2012-05-26T21:28:55","guid":{"rendered":"http:\/\/doanduyhai.wordpress.com\/?p=1172"},"modified":"2012-05-26T23:28:55","modified_gmt":"2012-05-26T21:28:55","slug":"final-variable-in-java","status":"publish","type":"post","link":"https:\/\/www.doanduyhai.com\/blog\/?p=1172","title":{"rendered":"Final variable in Java"},"content":{"rendered":"<p>This short article introduces the definition and usage of final variables in Java and some interesting use cases.<\/p>\n<p><!--more--><\/p>\n<h1>I Definition<\/h1>\n<p> A variable is said &#8220;<strong>final<\/strong>&#8221; when, after its declaration, its reference cannot be changed.<\/p>\n<p> The below code will raise error during compilation because we attempt to modify a variable declared as <strong>final<\/strong>.<\/p>\n<pre class=\"brush: java; highlight: [3]; title: ; notranslate\" title=\"\">\nfinal Object finalObj = new Object();\n...\nfinalObj = new Object(); \/\/ Compilation error\n<\/pre>\n<p>&nbsp;<\/p>\n<h1>II Usage<\/h1>\n<p> The final keyword can be used in 3 situations:<\/p>\n<ul>\n<li>when declaring a local variable in a method or code block (delimited by brackets)<\/li>\n<li>when declaring a class attribute<\/li>\n<li>when declaring a method\/constructor argument<\/li>\n<\/ul>\n<p>The first case is quite straightforward, no much to say.<\/p>\n<p>For a <strong>class attribute declaration<\/strong>, the final variable should either:<\/p>\n<ul>\n<li>be initialized directly in the declaration statement<\/li>\n<\/ul>\n<pre class=\"brush: java; highlight: [4]; title: ; notranslate\" title=\"\">\npublic class Test\n{\n\t\/\/ Immediate initialization\n\tfinal String finalVar = &amp;quot;test&amp;quot;;\n}\n<\/pre>\n<ul>\n<li>be initialized in alls the Object constructors, either public or private<\/li>\n<\/ul>\n<pre class=\"brush: java; highlight: [7,12]; title: ; notranslate\" title=\"\">\npublic class Test\n{\n\tfinal String finalVar;\n\n\tpublic Test(String input)\n\t{\n\t\tthis.finalVar=&amp;quot;firstConstructor&amp;quot;;\n\t}\n\n\tpublic Test()\n\t{\n\t\tthis.finalVar=&amp;quot;defaultConstructor&amp;quot;;\n\t}\n}\n<\/pre>\n<p>Any subsequent attempt to assign a new value to <strong>finalVa<\/strong>r will result in compilation error.<\/p>\n<p>The last use case of final variable relates to method argument:<\/p>\n<pre class=\"brush: java; highlight: [8]; title: ; notranslate\" title=\"\">\npublic class Test\n{\n\t...\n\tpublic void doSomething(final String value)\n\t{\n\t\t...\n\t\t\/\/ Compilation error, forbidden\n\t\tvalue = &amp;quot;anotherString&amp;quot;;\n\t\t...\n\t}\n}\n<\/pre>\n<p> &nbsp;<\/p>\n<h1>III Final vs immutable<\/h1>\n<p> There are some false beliefs among developers, stating that a final variable cannot be modified. It is right and wrong at the same time, depending on what we mean by &#8220;<strong>being modified<\/strong>&#8220;.<\/p>\n<p> Let&#8217;s have a look at the definition of &#8220;<strong>final<\/strong>&#8220;: &#8230;after its declaration, <strong>its reference cannot be changed<\/strong><\/p>\n<p> The definition clearly states that the reference of a final variable cannot be changed after its initialization. Nothing is said about its internal state. Especially if the object is mutable, its internal state can be modified even though the variable is declared &#8220;<strong>final<\/strong>&#8220;.<\/p>\n<pre class=\"brush: java; highlight: [3,5]; title: ; notranslate\" title=\"\">\npublic class Test\n{\n\tpublic void addToList(final List&amp;lt;String&amp;gt; items)\n\t{\n\t\titems.add(&amp;quot;dummy&amp;quot;);\n\t}\n}\n\n...\n\tList&amp;lt;String&amp;gt; items = new ArrayList&amp;lt;String&amp;gt;();\n\titems.add(&amp;quot;singleton&amp;quot;);\n\n\tSystem.out.println(&amp;quot;items size before == &amp;quot; + items.size());\n\n\tTest testObject = new Test();\n\ttestObject.addToList(items);\n\n\tSystem.out.println(&amp;quot;items size after == &amp;quot; + items.size());\n...\n<\/pre>\n<p> The output displays:<\/p>\n<pre>\nitems size before == 1\nitems size after == 2\n<\/pre>\n<p>Indeed, mutability and final are two distinct notions in Java. You can have a final mutable variable as well as final immutable variable.<\/p>\n<p> You can have more details about immutability in my previous article <a href=\"http:\/\/doanduyhai.wordpress.com\/2012\/05\/26\/object-immutability-in-java\/\" title=\"Object immutability in\u00a0Java\" target=\"_blank\">Java immutability<\/a><\/p>\n<p>&nbsp;<\/p>\n<h1>IV Pass by reference\/copy of reference<\/h1>\n<p> I&#8217;ve been told in the past to put the <strong>final<\/strong> modifier on all method\/constructor arguments. The reason of this practice was, supposedly, to avoid modifying the reference of the object passed in argument.<\/p>\n<p> Though I quite agree that it could be a good coding practice, <strong>it is absolutely not necessary<\/strong>. Even if you omit the <strong>final<\/strong> keyword for your method arguments, you still can&#8217;t change the reference of the source object.<\/p>\n<p>Let&#8217;s see a concrete example:<\/p>\n<pre class=\"brush: java; highlight: [3,5,15]; title: ; notranslate\" title=\"\">\npublic class Test\n{\n\tpublic void addToList(List&amp;lt;String&amp;gt; items)\n\t{\n\t\titems = new ArrayList&amp;lt;String&amp;gt;();\n\t\titems.add(&amp;quot;one&amp;quot;);\n\t\titems.add(&amp;quot;two&amp;quot;);\n\t\titems.add(&amp;quot;three&amp;quot;);\n\n\t\tSystem.out.println(&amp;quot;items size inside = &amp;quot; + items.size());\n\t}\n}\n\n...\n\tList&amp;lt;String&amp;gt; items = new ArrayList&amp;lt;String&amp;gt;();\n\titems.add(&amp;quot;singleton&amp;quot;);\n\n\tSystem.out.println(&amp;quot;items size before == &amp;quot; + items.size());\n\n\tTest testObject = new Test();\n\ttestObject.addToList(items);\n\n\tSystem.out.println(&amp;quot;items size after == &amp;quot; + items.size());\n...\n<\/pre>\n<p>Above, at <strong>line 5<\/strong>, we assign a new ArrayList instance to the <em>items<\/em> argument of the <em>addToList()<\/em> method. But with no surprise, the output is:<\/p>\n<pre>\nitems size before == 1\nitems size inside == 3\nitems size after == 1\n<\/pre>\n<p> Indeed, as I showed in my post about <a href=\"http:\/\/doanduyhai.wordpress.com\/2011\/10\/23\/java-pass-by-valuereference-or-copy-of-valuereference\/\" title=\"Java, pass by value\/reference or copy of value\/reference\u00a0?\" target=\"_blank\">Java passed by reference\/value<\/a>, the <em>items<\/em> argument of the <em>addToList()<\/em> method is a <strong>pointer pointing to the original list reference<\/strong>. Assigning this pointer to a new list reference inside <em>addToList()<\/em> doesn&#8217;t affect the original pointer declared at <strong>line 15<\/strong>.<\/p>\n<p> &nbsp;<\/p>\n<h1>V Final variable and anonymous classes<\/h1>\n<p> One usage of the <strong>final<\/strong> keyword relates to anonymous classes and the capture of local variables. According to the official documentation, an anonymous class can access to all variable of the enclosing class, provided that they are declared as &#8220;final&#8221;.<\/p>\n<pre class=\"brush: java; highlight: [12]; title: ; notranslate\" title=\"\">\npublic interface Listener\n{\n\tvoid onAction();\n\n}\n\n\n...\n...\n\tpublic Listener getListener()\n\t{\n\t\tfinal List&amp;lt;String&amp;gt; list = new ArrayList&amp;lt;String&amp;gt;();\n\n\t\tListener listener = new Listener()\n\t\t{\n\n\t\t\tpublic void onAction()\n\t\t\t{\n\t\t\t\tlist.add(&amp;quot;listener called&amp;quot;);\n\t\t\t}\n\t\t};\n\n\t\tlist.add(&amp;quot;start&amp;quot;);\n\t\tlistener.onAction();\n\t\tlist.add(&amp;quot;end&amp;quot;);\n\t}\n...\n<\/pre>\n<p>Again, marking the local variable as final does not mean that the variable itself is immutable. The above code example clearly proves it.<\/p>\n<p> Why do we need to declare a variable &#8220;<strong>final<\/strong>&#8221; for the anonymous class ? There is a good reason for that, as per Java language design.<\/p>\n<p> Since &#8220;<strong>closure<\/strong>&#8221; does not exist in Java, <strong>as soon as the execution flow exits a method, all local variable references, which are stored on the call stack, are removed<\/strong>. The consequence is that when a method exits, all local variables declared inside this method no longer exist.<\/p>\n<p> It is possible that in some cases, a method returned value is an anonymous class. If this anonymous class is using a local variable declared inside the method, on method exit, weird behaviors will occur.<\/p>\n<p> To prevent such issue, the compilator forces the local variable to be declared as <strong>final<\/strong> if used in an anonymous class. Declaring a variable &#8220;<strong>final<\/strong>&#8221; will result in moving it from the call stack to a <strong>pool of &#8220;constants&#8221;<\/strong> so the variable still exists on method exit.  <\/p>\n<p>&nbsp;<br \/>\n&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This short article introduces the definition and usage of final variables in Java and some interesting use cases.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[22,6],"tags":[],"_links":{"self":[{"href":"https:\/\/www.doanduyhai.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1172"}],"collection":[{"href":"https:\/\/www.doanduyhai.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.doanduyhai.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.doanduyhai.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.doanduyhai.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1172"}],"version-history":[{"count":0,"href":"https:\/\/www.doanduyhai.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1172\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.doanduyhai.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1172"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.doanduyhai.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1172"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.doanduyhai.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1172"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}