title: Weak Reference vs setting to Null
body: <p>What is the difference between using WeakReference and setting the strong ref type to null ?</p>
  
  <p>Say for example in the following code the variable "test" is a strong ref to "testString". When I set the "test" to null. There is no longer a Strong ref and hence "testString" is now eligible for GC. So if I can simply set the object reference "test" to equal null what is the point of having a WeakReference Type ?    </p>
  
  <pre><code>class CacheTest {
    private String test = "testString";
  
    public void evictCache(){
      test = null; // there is no longer a Strong reference to "testString" 
      System.gc(); //suggestion to JVM to trigger GC 
    }
  }
  </code></pre>
  
  <p>Why would i ever want to use WeakReference ?</p>
  
  <pre><code>class CacheTest {
    private String test = "testString";
    private WeakReference&lt;String&gt; cache = new WeakReference&lt;String&gt;(test);
  
    public void evictCache(){
      test = null; // there is no longer a Strong reference to "testString" 
      System.gc(); //suggestion to JVM to trigger GC 
    }
  }
  </code></pre>