Lab # 7 Pass Object As Parameter: Objective
Lab # 7 Pass Object As Parameter: Objective
LAB # 7
OBJECTIVE:
To Study Pass Objects As Parameter To Methods.
THEORY:
then the Sphere object that the variable ball refers to will die when the
variable ball goes out of scope. This will be at the end of the block containing
this declaration. Where an instance variable is the only one referencing an
object, the object survives as long as the instance variable owning the object
survives.
As you can see, the equals( ) method inside Test compares two objects for
equality and returns the result. That is, it compares the invoking object with
the one that it is passed. If they contain the same values, then the method
returns true. Otherwise, it returns false. Notice that the parameter o in
equals( ) specifies Test as its type. Although Test is a class type created by
the program, it is used in just the same way as Java’s built-in types.
In general, there are two ways that a computer language can pass an
argument to a subroutine. The first way is call-by-value, the second way an
argument can be passed is call-by-reference.
Passed By Value
class Test {
void meth(int i, int j) {
i *= 2;
j /= 2;
}
}
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " +
a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " +
a + " " + b);
}
}
Passed By Reference
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// pass an object
void meth(Test o) {
o.a *= 2;
o.b /= 2;
}
}
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " +
ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " +
ob.a + " " + ob.b);
}
}
This program generates the following output:
Returning Objects:
A method can return any type of data, including class types that you create.
For example, in the following program, the incrByTen( ) method returns an
object in which the value of a is ten greater than it is in the invoking object.
Returning an object
class Test {
int a;
Test(int i) {
a = i;
}
Test incrByTen() {
As you can see, each time incrByTen( ) is invoked, a new object is created,
and a reference to it is returned to the calling routine
LAB TASK
1. Write a program to take two values from the user and swap those
values by using the concept of arguments passing by reference.
Sample Output:
Before swapping:
First value: 15
Second value: 20
After Swapping:
First value: 20
Second value: 15
2. Write a program to take a value from the user and print next 5 values
that should be the increment of 10 from the previous value using the
concept of returning object
Sample Output:
5 15 25 35 45