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 :
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.