New Rich Text Document
New Rich Text Document
modify(box);
System.out.println("After: " + box.value); // Output: 100 (Modified)
}
}
✔ Here, box is passed by value, but since it holds a reference to the object, the method modifies
the actual object.
✔ The modify() method creates a new Box object and returns it. To retain changes, we assign
the returned object back.
modify(numbers);
System.out.println("After: " + numbers[0]); // Output: 99 (Modified)
}
}
✔ The method modifies the contents of the array, but not the reference itself.
class Box {
int value;
}
modify(ref);
System.out.println("After: " + ref.get().value); // Output: 300 (New
Object)
}
}
Conclusion
✅ Java only supports pass-by-value, but you can simulate pass-by-reference by:
🔸 Since Java passes a copy of x, changing num inside modify() does not affect x.
🔸 Here, box holds a reference to an object, and a copy of this reference is passed to
modify().
🔸 Both references still point to the same object, so modifying its state inside the method reflects
outside.
🔸 The modify() method creates a new object, but since Java passes a copy of the reference,
the original reference remains unchanged.
Conclusion
Java always uses pass by value.
For primitives, Java passes a copy of the value (no changes outside the method).
For objects, Java passes a copy of the reference (changes inside the object are
reflected, but reassigning a new object does not affect the original reference).
void nonStaticMethod() {
System.out.println("This is a non-static method.");
}
🔹 Summary
Allowed in Static
Element Reason
Method?
Local variables ✅ Yes Defined inside the method
Static variables ✅ Yes Shared across all instances
Static methods ✅ Yes Can call other static methods
Instance
❌ No (needs object) Belongs to objects, not the class
variables
Instance
❌ No (needs object) Requires an instance to call
methods
Refers to an instance, but static methods belong to
this / super ❌ No
the class
🔹 Final Notes
Static methods are used when the logic does not depend on instance variables.
Best suited for utility methods (e.g., Math.pow(), Collections.sort()).
Cannot override static methods (but can hide them in subclasses).