The example below looks at the passing of primitive values and
references in method arguments.
Note: Both methods in the
example below use the same name but different types of arguments.
We will discuss such method overloading
in the next section.
In main
the invoking of the method aMethod(int
j) in the class Test
will cause a copy of the value in main
to pass into the value of the j
in the method. So even though the code in aMethod(int
j)changes the value of the local j
variable, the j
back in main
remains unaffected.
We used the same name j
for both int
local variables in main
and aMethod.
However, these are completely different variables, occupying different
locations in memory. We could use different names if we wished.
We also invoke the method aMethod(String
aStr). This will send a copy of the reference pointer in
main to
the method. With this reference the method can access the same string
data as the reference in main. That is, they both point to the same
String object.
The code in aMethod(String
aStr)changes the value of the local aStr
reference variable but this does not affect the aStr
reference variable back in main().
ValRefApplet.java
(Output goes to browser's Java
console.) |
public
class ValRefApplet extends java.applet.Applet
{
public void init () {
// Create an instance of the Test
class
Test test = new Test ();
int j = 5;
test.aMethod (j);
System.out.println ("In main");
System.out.println ("j = " + j);
System.out.println ();
String aStr = new String ("A string");
test.aMethod (aStr);
System.out.println ("In main");
System.out.println ("aStr = " +
aStr);
System.out.println ();
}
// Paint message in Applet window.
public void paint (java.awt.Graphics g) {
g.drawString ("ValRefApplet", 20,
20);
}
}
/**
* Test has one constructor with a primitive
type argument
* and one with a object (String) reference argument.
**/
class Test
{
void aMethod (int j) {
System.out.println (" In aMethod
(int j)");
System.out.println (" j
= " + j);
j = 10;
System.out.println (" j
= " + j);
System.out.println ();
}
void aMethod (String aStr) {
System.out.println (" In aMethod
(String aStr)");
System.out.println (" aStr
= " + aStr);
aStr = new String ("different string");
System.out.println (" aStr
= " + aStr);
System.out.println ();
}
}
|
|
Latest update: Oct. 19, 2004
|