In this exercise, you will exercise the concept of pass by reference. Please not that primitive type parameters are passed by value while reference type parameters are passed by reference. An array is considered a reference type even though the entries it contains are primitive type.
Steps to follow:
1. Write TestPassByReference.java as shown in Code 9.5 below. (You are welcome to do this work using either command line tools or NetBeans. The instruction here is given using command line tools. In general, using NetBeans is highly recommended.)
* cd \myjavaprograms
* jedit TestPassByReference.java
public class TestPassByReference {
public static void main(String[] args){
System.out.println("main: start");
int [] ages = {10, 11, 12};
for (int i=0; i
}
System.out.println("main: before calling the test method");
test(ages);
System.out.println("main: after calling the test method");
for (int i=0; i
}
System.out.println("main: end");
}
public static void test(int[] arr){
System.out.println("test: start");
for (int i=0; i
}
System.out.println("test: end");
}
}
Code-9.5: TestPassByReference..java
2. Compile and run the code
* javac TestPassByReference.java
* java -cp . TestPassByReference
3. Verify the result is as following.
* C:\myjavaprograms>java -cp . TestPassByReference
main: start
10
11
12
main: before calling the test method
test: start
test: end
main: after calling the test method
50
51
52
main: end
Homework: (Optional)
I made this homework as an optional homework. It is because in order to do this homework right, you would need to create your own class, which we will learn in the Class #5. (in the future offerings of this course, I will move this homework to some place else.)
If you still want to do it, please do the homework as following:
1. Modify TestPassByReference.java as following. Compile and run the application.
* Pass the second reference type parameter to the test(..) method - you will have to create your own class and object instance of it. The class should have a private field and getter and setter method of the field.
* Set the value of the field of the object instance using setter method before calling the test(..) method. And change the value of the field of the object instance using setter method within the test(..) method as you did with the first parameter in Code-9.5 above.
* Modify the System.out.println(..) methods in the Code-9.5 above to display the values of both the first parameter and second parameter.
No comments:
Post a Comment