Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate, passing an object as an argument.

Java Code Example — OOP Programs

ADVERTISEMENT

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

  1. Create a class Demo with an integer field a and a constructor to initialize it.
  2. Create a class Test with a method square(Demo d). This method accepts a Demo object as a parameter.
  3. Inside square(), modify the object's field: d.a = d.a * d.a.
  4. In main, create a Demo object passing 10.
  5. Print the value before calling the method.
  6. Create a Test object and call square(), passing the Demo object to it.
  7. 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.a changes permanently from 10 to 100 after the method call.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT