Java Reference
In-Depth Information
The values for n1 and n2 are
swapped, but it does not affect
num1 and num2.
The values of num1 and num2 are
passed to n1 and n2 .
Space required for the
swap method
Space required for the
swap method
temp:
temp:
n2: 2
n1: 1
n2: 1
n1: 2
Space required for the
main method
Space required for the
main method
Space required for the
main method
Space required for the
main method
Stack is empty
num2: 2
num1: 1
num2: 2
num1: 1
num2: 2
num1: 1
num2: 2
num1: 1
The swap method
is finished.
The main method
is invoked.
The swap method
is invoked.
The swap method
is executed.
The main method
is finished.
F IGURE 5.4
The values of the variables are passed to the method's parameters.
Note
For simplicity, Java programmers often say passing x to y , which actually means passing
the value of argument x to parameter y .
5.11
How is an argument passed to a method? Can the argument have the same name as its
parameter?
Check
Point
5.12
Identify and correct the errors in the following program:
1 public class Test {
2 public static void main(String[] args) {
3 nPrintln( 5 , "Welcome to Java!" );
4 }
5
6 public static void nPrintln(String message, int n) {
7 int n = 1 ;
8 for ( int i = 0 ; i < n; i++)
9 System.out.println(message);
10 }
11 }
5.13
What is pass-by-value? Show the result of the following programs.
public class Test {
public static void main(String[] args) {
int max = 0 ;
max( 1 , 2 , max);
System.out.println(max);
public class Test {
public static void main(String[] args) {
int i = 1 ;
while (i <= 6 ) {
method1(i, 2 );
i++;
}
}
public static void max(
int value1, int value2, int max) {
if (value1 > value2)
max = value1;
else
max = value2;
}
public static void method1(
int i, int num) {
for ( int j = 1 ; j <= i; j++) {
System.out.print(num + " " );
num *= 2 ;
}
}
}
System.out.println();
}
}
(a)
(b)
Search WWH ::




Custom Search