What is parameter passing in Java and how is it implemented?
sobes.tech AI
Answer from AI
Java uses pass-by-value for parameter passing. This means that a copy of the variable's value is passed to the method.
Let's consider two scenarios:
-
Passing primitive types (int, boolean, float, etc.): A copy of the actual value is passed. Changing this value inside the method does not affect the original variable outside the method.
// Example with a primitive type void changeValue(int num) { num = num + 10; // Only the copy is changed } // Usage int x = 5; changeValue(x); // x will still be 5 -
Passing reference types (objects): A copy of the reference to the object is passed. The reference itself is copied, but it still points to the same object in memory. Changing the object's fields inside the method will reflect on the original object, as both references point to the same instance. However, if inside the method you assign a new reference (for example, create a new object), it will not affect the original reference outside the method.
// Example with a reference type class MyObject { int value = 0; } void changeObjectValue(MyObject obj) { obj.value = 10; // Changes the field of the original object } void assignNewObject(MyObject obj) { obj = new MyObject(); // The variable obj now references a new object obj.value = 20; } // Usage MyObject myObj = new MyObject(); // Create object 1 changeObjectValue(myObj); // myObj.value is now 10 MyObject anotherObj = new MyObject(); // Create object 2 assignNewObject(anotherObj); // anotherObj still references object 2 with value 0
Thus, in Java, a copy of something is always passed: either a copy of a primitive value or a copy of a reference. This is the "pass-by-value" concept. There is no classic "pass-by-reference" where a method could modify the reference itself outside its scope.