From the course: Oracle Java Certification: 3. Methods and Inheritance

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Pass by value vs. by reference

Pass by value vs. by reference - Java Tutorial

From the course: Oracle Java Certification: 3. Methods and Inheritance

Start my 1-month free trial

Pass by value vs. by reference

- [Instructor] In Java, parameters are always passed to methods by value. The value of each actual parameter gets copied into its respective local variable in the method. Therefore the original value cannot be changed through the copy. However, if the parameter value is of a reference type, the method can possibly change the original object via the reference. This is known as pass by reference. Let's look at an example. Here we have two update methods. The first method at line 12 takes a string object as a parameter and it assigns a new value to it. The second method at line 16 modifies a string builder object by appending a string to it. The main method attempts to use both update methods to update objects. What would this program output? At line three a string object is created. It is passed to the update method at line four and then printed to the console at line five. Will the string object stay the same or will…

Contents