Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Let's say, final Map map = new HashMap(); new : is responsible to create object in heap which holds value</p> <p>"map" reference will be created in stack which is final.</p> <pre><code>The value of "map" reference is real object created in heap. As "map" reference is final, it can not have any other value in it. When we pass "map" reference, Actually we pass the value of map which is nothing but reference of object created in heap. In the called method, another reference "map" will be created in stack which holds the same reference of object in heap. The same concept is coded in this example </code></pre> <p>import java.util.HashMap; import java.util.Map;</p> <p>public class FinalExample { public static void main(String[] args) {</p> <pre><code> // Please see this example in case of normal variable and go through the // comment Final1 f1 = new Final1(); f1.fun2(); // Please see this example in case of Map Object and go through the // comment Final2 f2 = new Final2(); f2.fun2(); } </code></pre> <p>}</p> <p>class Final1 { final int a = 10;</p> <pre><code>void fun1(int a) { a += 20; System.out.println(a); } void fun2() { // Here we are passing just content of final variable "a" but not the // block "a" itself. // When method fun1 is called another local block "a" will be created // This local "a" has nothing to do with instance final "a". Both are // different // We can change the value of local a it has nothing to do with instance // "a" fun1(a); } </code></pre> <p>}</p> <p>class Final2 { final static Map map = new HashMap();</p> <pre><code>static { map.put("1", "Nandeshwar"); map.put("2", "Sah"); } void fun1(Map map) { map.put("3", "John"); map.put("4", "Nash"); System.out.println(map); } void fun2() { // Here (in fun1) we pass the content of final map. The content of final // map is // the refernece of real object which holds the value // "1" "Nandeshwar // "2" "Sah". // When we call fun1, Another object "map(Map)" will be created. this // newly created object "map" will also // indicate the same reference as instance map refers // So the local object "map" and instance object "map" both is // different. But indicates the real Object which holds the value fun1(map); } </code></pre> <p>}</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload