CS101: Pass by Value and Pass by Reference

Part 7! This will be a short one. I didn’t elaborate on the difference between pass by reference and pass by value when I wrote about methods, but it’s worth revisiting. Code speaks louder than words here:

Running this will output:

Well that seems odd. We gave the method both our object and our integer, the method sets both to 0, and only the object is affected? That’s right, because primitives are always passed by value. Pass by value means that when a primitive variable is passed as an argument, we aren’t passing the variable itself- we’re passing its value.

You can think of it as Java looking at the variable, writing its value on a post-it note, and passing that note over to the method, where the method does whatever it does. Since the method just has the post-it, scribbling on the note has no effect on the variables original value.

Objects, on the other hand, are passed by reference. When you pass an object to a method, you’re passing the object itself, not just its value. Since an object can contain other objects and primitives, it’d be difficult to copy every time you pass one as an argument. If you’re familiar with C++, this is how pointers work; they’re just references to objects or variables.

There’s one more point worth covering here; Immutable Types. An immutable type is a class that, once instantiated, cannot change any of its values. There isn’t a keyword or anything for this in Java, it’s simply something that can be enforced by carefully designing your class. Immutable types tend to act more like primitive types, because any changes you make aren’t actually changing the object you passed in- they’re instantiating a new object of the same type with the new value you gave it. This happens behind the scenes thanks to a magic Java feature called autoboxing. Examples of immutable types in Java are String and the class versions of primitives- Integer, Boolean, Character, etc. As a rule of thumb, you can just treat these like they are pass by value and things will work as you expect.

Hopefully this cleared up some of the details of how methods do their thing; Thanks for reading!


Leave a Reply

Your email address will not be published / Required fields are marked *