Over a million developers have joined DZone.

Value or Reference?

DZone's Guide to

Value or Reference?

· Java Zone
Free Resource

Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale. Brought to you in partnership with Lightbend.

Death and Taxes are not the only two things that are certain in life: the regular resurgence of the “Is Java pass by value or pass by reference?” controversy comes to haunt us regularly as well. This year, it’s brought to us in the LinkedIn Java group and on TheServerSide.

Like all debates centered around words, it’s pretty hard to get a final resolution when most participants don’t agree on the meaning of these words.

This question makes for a great warm up interview question, though, but it would be pretty evil to ask it in these ambiguous terms, so instead, I simply prefer to show the candidate the two following snippets:

public void foo1(Person p) {
p = new Person("Joe");
public void foo2(Person p) {
p.name = "Joe";
and then ask them to explain what these two methods do.

The number of candidates who hesitate (and sometimes get it wrong) is pretty surprising. As is the amount of discussion that sometimes follows this question.

At any rate, the ensuing conversation is always interesting and it usually makes the candidate more comfortable for the rest of the interview.

From http://beust.com/weblog/2011/01/07/value-or-reference/

Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book. Brought to you in partnership with Lightbend.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}