Class 1, Part 2 |
Intro to Java 30-IT-396 |
|
Method Parameters
-
Java uses call by value.
-
In other words, it passes the value of the parameter to methods.
-
The alternative is call by reference, where the memory location of the
parameter itself is passed.
-
In theory, you cannot change the value of the original parameter passed.
But this is debatable.
-
You can change the state of an object in a method. In other
words, you can change the instance fields of an object.
-
You can not change the object itself. In other words, you
can't make that object refer to another object.
-
You can not change the value of a primitive.
-
But there is a workaround.
-
You can change a primitive in a method, return that new primitive,
then assign it to the original primitive.. In other words,
int x = 5;
myMath.multiply(x, 3);
System.out.println("X value: " + x); // Does
not change the value of x in the calling object.
x = myMath.multiplyBy(x, 3); // Changes
the value of x in the called object, returns and reassigns it.
System.out.println("X value: " + x);
Would print:
X value: 5
X value: 15
A note. The first method is called multiply, and the second
is called multiplyBy. In Java, we cannot have different method signatures
based on the return type alone. Since nothing else in the methods
differed, I had to make a new method.
Object Construction Revisited


Created by: Brandan
Jones January 4, 2002