I have a question about changing the values of variables in methods in Java.
This is my code:
public class Test {
public static void funk(int a, int[] b) {
b[0] = b[0] * 2;
a = b[0] + 5;
}
public static void main(String[] args) {
int bird = 10;
int[] tiger = {7};
Test.funk(bird, tiger);
}
}
After the execution of the method Test.funk(bird, tiger)
, the value of bird is not changed - it remains with the value 10
, even though in the funk()
method we have changed the value with a = b[0] + 5;
On the other hand, the value of the element in the array changes, because we have the statement b[0] = b[0] * 2;
I don't understand why one thing changes and the other not? Could someone please explain this for me.
With instance variables, each new instance of the class gets a new copy of the instance variables that the class defines. Each instance then can change the values of those instance variables without affecting any other instances.
An instance variable is a variable that is specific to a certain object. It is declared within the curly braces of the class but outside of any method. The value of an instance variable can be changed by any method in the class, but it is not accessible from outside the class.
Look at Jon Skeet's article about Parameter-Passing in Java, which explains this.
In short (look at his site for a more throughout explanation):
Arrays are reference types. If you pass a reference that points to an array, the value of the reference is copied and assigned to the parameter of the function. So the parameter will point to the same array as the argument that was passed. Thus changes you make to the array through the parameter of your function will be visible in the calling function. Changing the parameter itself (b), for example by setting it to null, however, will not be noticed by the calling function, since the parameter (b) is just a copy of the argument (tiger) passed.
Integers are so-called primitive types. Passing the integer copies its value and assigns it to the parameter too. But that value is not a reference to the actual data, but is the data itself. So changes to the paramter in the function will affect the parameter (a), but not the argument passed in the calling function (bird).
Basically, objects (like arrays) are passed into methods "by reference". So when you change the object, it changes the same object that was passed into the method.
Primitives (like int) are "passed by value", so the variable you are assigning a value to in a is not the same as the int variable that was passed in.
I hope this helps...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With