Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does String passed by reference doesn't change its value?

Why does the piece of code bellow modifies only value in array t and doesn’t change value of the string s as well? I expected that String would also be changed because of its object properties.

class A {
    private int i = 0;
    private String s = "";
    private int[] t = new int[1];

    void m() {
        B.m(i, s, t);
    }

    @Override
    public String toString() {
        return "i=" + i + ", s=" + s + ", t[0]=" + t[0];
    }
}

class B{
   public static void m(int i, String s, int[] t){
      i += 1;
      s += "1";
      t[0] += 1;
   }  
}

public class Zad {

   public static void main( String [ ] args ){
      A a = new A() ;
      System.out.println(a);
      a.m();
      System.out.println(a);
   } 
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is what happening in your code: In Java, when you pass primitive types (like int) to a method, you pass the value itself. Any modification made to the parameter within the method do not affect the original value outside the method. This is known as "pass-by-value". This you may already know.

In definition of class b, i, s, and t are local variables within the method m(). It means, changes made to these variables do not affect the original values in the calling code.

When you call instance method a.m(); in your main method:

A a = new A();
System.out.println(a);  // Output: i=0, s=, t[0]=0
a.m();
System.out.println(a);  // Output: i=0, s=, t[0]=1

You’ll see that the value of t[0] has changed because arrays in Java are objects, and modifications to their elements are reflected outside the method. However, the values of i and s remain unchanged because they are primitive types or immutable objects (like String), and any changes made to them within the method are local and don’t affect the original values.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading