Master the mechanics of how object references are passed into methods, copied via constructors, and returned as values in Java.
Java is strictly pass-by-value. However, when working with objects, the value being passed is the reference (memory address) to the object rather than the object's raw data itself.
When an object reference is passed to a method, a copy of the reference address is created. Both the original variable and the method parameter point to the exact same object in heap memory.
You can pass an object reference as an argument to a method, allowing the method to compare or interact with multiple objects.
// Java Program to Demonstrate Passing Objects to Methods
class ObjectPassDemo {
int a, b;
// Constructor
ObjectPassDemo(int i, int j) {
a = i;
b = j;
}
// Method that accepts an object of the same class
boolean equalTo(ObjectPassDemo o) {
return (o.a == a && o.b == b);
}
}
public class Main {
public static void main(String[] args) {
ObjectPassDemo ob1 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob2 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));
System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));
}
}
One common use case for passing objects is creating a new object initialized with the exact properties of an existing object.
class Box {
double width, height, depth;
// Constructor that takes an object of type Box
Box(Box ob) {
width = ob.width;
height = ob.height;
depth = ob.depth;
}
// Standard Constructor
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
double volume() {
return width * height * depth;
}
}
public class Main {
public static void main(String[] args) {
Box mybox = new Box(10, 20, 15);
Box myclone = new Box(mybox); // Pass mybox to create copy
System.out.println("Volume of mybox is " + mybox.volume());
System.out.println("Volume of myclone is " + myclone.volume());
}
}
Methods in Java can also return newly constructed or modified objects to the caller.
class ObjectReturnDemo {
int a;
ObjectReturnDemo(int i) {
a = i;
}
// Method returns an instance of ObjectReturnDemo
ObjectReturnDemo incrByTen() {
ObjectReturnDemo temp = new ObjectReturnDemo(a + 10);
return temp;
}
}
public class Main {
public static void main(String[] args) {
ObjectReturnDemo ob1 = new ObjectReturnDemo(2);
ObjectReturnDemo ob2;
// Method returns new object reference
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
}
}
incrByTen() creates a brand-new object on the Heap. The reference returned points to a completely distinct memory location from ob1.