title: Duplicating objects in Java
body: <p>I learned that when you modify a variable in Java it doesn't change the variable it was based on</p>
  
  <pre><code>int a = new Integer(5);
  int b = a;
  b = b + b;
  System.out.println(a); // 5 as expected
  System.out.println(b); // 10 as expected
  </code></pre>
  
  <p>I assumed a similar thing for objects. Consider this class.</p>
  
  <pre><code>public class SomeObject {
      public String text;
  
      public SomeObject(String text) {
          this.setText(text);
      }
  
      public String getText() {
          return text;
      }   
  
      public void setText(String text) {
          this.text = text;
      }
  }
  </code></pre>
  
  <p>After I tried this code I got confused.</p>
  
  <pre><code>SomeObject s1 = new SomeObject("first");
  SomeObject s2 = s1;
  s2.setText("second");
  System.out.println(s1.getText()); // second as UNexpected
  System.out.println(s2.getText()); // second as expected
  </code></pre>
  
  <p>Please explain to me why changing any of the objects affects the other one. I understand that the value of variable text is stored in the same place in memory for both of the objects. </p>
  
  <p>Why the values for variables are independent but correlated for objects?</p>
  
  <p>Also, how to duplicate SomeObject, if simple assignment does not do the job?</p>