Java Program to demonstrate, passing an object as an argument.
Objective
Write a Java program to demonstrate passing an object as an argument to a method.
Algorithm / Approach
- Create a class
Demowith an integer fieldaand a constructor to initialize it. - Create a class
Testwith a methodsquare(Demo d). This method accepts aDemoobject as a parameter. - Inside
square(), modify the object's field:d.a = d.a * d.a. - In
main, create aDemoobject passing 10. - Print the value before calling the method.
- Create a
Testobject and callsquare(), passing theDemoobject to it. - Print the value after the method call to observe the change.
Demo.java
class Demo {
int a;
Demo(int a) {
this.a = a;
}
}
class Test {
int x = 20;
void square(Demo d) {
d.a = d.a*d.a;
}
}
class Main{
public static void main(String[] a)
{
Demo d = new Demo(10);
Test t = new Test();
System.out.println("Before Call- "+d.a);
t.square(d);
System.out.print("After Call- "+d.a);
}
}
Expected Output
Before Call- 10 After Call- 100
Explanation of the Program
- In Java, primitive data types (like int, float) are passed by value, meaning the method gets a copy of the variable.
- However, objects are passed by reference (technically, the value of the reference is passed).
- This means when you pass an object to a method, the method can modify the actual original object's fields.
- This is why the value of
d.achanges permanently from 10 to 100 after the method call.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)