Can I modify an object by a Java method call?

Madushika Sewwandi
3 min readApr 12, 2022

--

In programming languages there are two types of data passing, Pass-by-reference” and “pass-by-value”. Java is a “pass-by-value” language. To understand the pass-by-value mechanism we must understand 2 things, first, the scope of a variable and the second is how data is passed into a method.

Variable scope

Each variable has their scope depending on the block they have been declared within a Java class. Scope is simply the visibility of a variable. For example, a variable declared inside a method is only visible inside that method block.

Variables visible inside a method are called local variables. Those variables can be either method parameters or the variables declared inside the method. Sometimes a local variable can have a narrower scope than the method body when they are declared inside another block inside a method.

Passing data into methods

Data is passed into a method using method parameters. These method parameters can be either a primitive type or an object. Method parameters should be assigned with values when a method is called. What happens when assigning values to method parameters is that assigning the copy of the variables to the parameters. If it is a primitive type a copy of the value will be assigned and if it is an object a copy of the object reference is assigned. (Because an object variable is holding a reference to the object as the value)

After the last line the array variable is pointed to the local variable B. So once the program exits the method body, there will be no longer ant array with increased size. If you want variable A to hold the re sized array you need to return the B and assign that to A. This happened because Java is pass by value and not pass by reference and here, we have done only some reassigning of objects to reference variable. We didn’t change any object.

However, if we do any changes to an object passed into a method by its reference, that changes will persist.

To conclude, Java uses pass-by-value to get data into a method. Assigning a primitive or reference variable to a parameter doesn’t change the caller. Making changes to an object upon the calling reference does affect the caller.

--

--