Thursday, February 11, 2016

Java is ALWAYS pass-by-value Java is ALWAYS pass-by-value

1. Java pass by value or pass by reference


Java is ALWAYS pass-by-value (meaning make another new copy ).
That’s why when we change object’s value within function, the original object’s value is untouchable.
public class Main
{
     public static void main (String[] args)
     {
             Foo f = new Foo(“f”);
             changeReference(f);
             modifyReference(f);
      }
}
enter image description here
public class Main
{
     public static void main (String[] args)
     {
             Foo f = new Foo(“f”);
             changeReference(f);
             modifyReference(f);
      }

     public static void changeReference (Foo a)
     {
        Foo b = new Foo(“b”);
        a=b;
      }
}
enter image description here
public class Main
{
     public static void main (String[] args)
     {
             Foo f = new Foo(“f”);
             changeReference(f);
             modifyReference(f);
      }
     public static void changeReference (Foo a)
     {
        Foo b = new Foo(“b”);
        a=b;
      }
}
enter image description here
public static void changeReference (Foo a)
{
        Foo b = new Foo(“b”);
        a=b;
}
enter image description here
public static void changeReference (Foo a)
{
        Foo b = new Foo(“b”);
        a=b;
}
enter image description here
public class Main
{
     public static void main (String[] args)
     {
             Foo f = new Foo(“f”);
             changeReference(f);
             modifyReference(f);
      }

     public static void changeReference (Foo a)
     {
        Foo b = new Foo(“b”);
        a=b;
      }
      public static void modifyReference (Foo c)
      {
            c.setAttribute(“c”);
       }
}
enter image description here
public class Main
{
     public static void main (String[] args)
     {
             Foo f = new Foo(“f”);
             changeReference(f);
             modifyReference(f);
      }

     public static void changeReference (Foo a)
     {
        Foo b = new Foo(“b”);
        a=b;
      }
      public static void modifyReference (Foo c)
      {
            c.setAttribute(“c”);
       }
}
enter image description here
Reference: