Java Reference
In-Depth Information
method argument passing
There is one final point I want to make in regard to the way parameter variables are passed to meth-
ods. Argument passing can be daunting and tricky in Java at first sight, so I've devoted a section to
this concept to get the point across.
To start the discussion, consider the following code:
class Test {
int a = 4;
static void increaseInt(int anInt) {
anInt++;
}
public static void main(String[] args) {
Test t = new Test();
System.out.println("Instance var a is: "+t.a);
Test.increaseInt(t.a);
System.out.println("Instance var a is now: "+t.a);
}
}
What will this code output?
Instance var a is: 4
Instance var a is now: 4
Even though you have supplied the instance variable to the method, after the method finishes, the
value of this variable remains unchanged. This might lead you to believe that the anInt variable will
be considered as a copy of t.a . In programming jargon, this behavior is called “pass by value.”
This is easy enough to understand until you try the same trick with a non‐primitive data type, such
as arrays:
class Test {
int[] array = new int[]{1,2,3};
static void increaseFirstInt(int[] anIntArray) {
anIntArray[0]++;
}
public static void main(String[] args) {
Test t = new Test();
System.out.println("First element in array is: "+t.array[0]);
Test.increaseFirstInt(t.array);
System.out.println("First element in array is now: "+t.array[0]);
}
}
The output given now? Completely different:
First element in array is: 1
First element in array is now: 2
 
Search WWH ::




Custom Search