Skip to the page

Objects and language basics · core

Pass by value and boxed numbers

Java always passes by value. For an object, the value is a copy of the reference. Boxed numbers (Integer, Long) are objects, so == compares references and gives wrong answers for large values.

The notes

What you must know

  • Java always passes by value. For an object the value is a copy of the reference, so a method can change the object but cannot make the caller point to a different object.
  • Assigning to a primitive parameter, or to a String parameter, changes only the local copy. Strings are immutable, so note + " (updated)" makes a new String.
  • A swap method for two parameters cannot work. Return a new object instead, for example a small record.
  • Long and Integer values from -128 to 127 come from a cache, so == on two boxed values is true for small numbers and false for larger ones.
  • Compare boxed values with Objects.equals(a, b), or compare primitives. A Long compared with a primitive long is unboxed and works.
  • Unboxing a null Long throws NullPointerException. Prefer primitives unless null has a meaning.
  • The top of the Integer cache can be raised with -XX:AutoBoxCacheMax. The Long cache is fixed. This is one way tests and production can differ.
  • Tests pass when test data uses small ids. Production ids are in the lakhs, so use realistic ids in tests.

The red pen

Common traps: mistake → fix

  • Mistake: Java passes objects by reference

    Fix: Java passes a copy of the reference, always by value.

  • Mistake: Two Long objects with the same number are always ==

    Fix: only values from -128 to 127 are cached; larger ones are different objects.

  • Mistake: Changing a String parameter changes the caller's String

    Fix: Strings are immutable; the caller still points to the old one.

Easy to hard

Questions interviewers ask, easy to hard

  1. Does Java pass by value or by reference?
  2. What does this method print after it changes an object field and then reassigns the parameter?
  3. Why does a == b work for Long 100 and fail for Long 1000?
  4. How would you find this bug after a release if staging cannot reproduce it?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview