title: Differentiating between copy-by-value and copy-by-reference instances/objects
body: <p>I am writing a static analysis tool for <code>Java</code> programs. And during analysis of assignment operators, for example, I want to know if underlying objects are using copy-by-value or copy-by-reference. </p>
  
  <p>In case of primitive data types, I know, variables use copy-by-value.</p>
  
  <pre><code>int x = 5;
  int y = x; // Both are pointing to independent memory locations.
  </code></pre>
  
  <p>In case of objects, usually they copy reference value of other objects. For example,</p>
  
  <pre><code>MyClass obj1 = new MyClass();
  MyClass obj2 = obj1; // Both instances pointing to the same memory location. 
  </code></pre>
  
  <p>However, in special cases, such as</p>
  
  <pre><code>String str1 = "myString";
  String str2 = str1; // Both pointing to independent memory locations.
  str1 = null; // Only str1 gets null
  </code></pre>
  
  <p>Objects use copy-by value, in my opinion. Please correct me if I am wrong. Similarly, <code>StringBuilder</code> and other <code>java/lang/*</code> classes that are declared with <code>final</code> keyword, their objects/instances behave like that. However, when being passed as parameter to a method, their reference values are passed.</p>
  
  <p>So my question is that is there any way to find all such special cases where objects always use copy-by-value behavior? How can I find all such classes? This may not be an easy task, any kind of suggestion is welcome. Thanks.</p>