Pass-by-value Pass-by-reference

suggest change

Java passes every argument by value. When the argument is an object, the copied value is a reference, so the method can change that object's fields. Assigning the parameter does not change the caller's variable. The C++ examples show a copy, a pointer, and a reference. The Java examples show what those ideas become in Java.

C++ Example (complete code)

// passes a COPY of the object
static void passByCopy(PassIt obj) {
   obj.i = 22;  // only a "local" change
}

// passes a pointer
static void passByPointer(PassIt* ptr) {
   ptr->i = 33;
   ptr = 0; // better to use nullptr instead of 0
}

// passes an alias (aka reference)
static void passByAlias(PassIt& ref) {
   ref.i = 44;
}

// This is an old-school way of doing it.
// Check out std::swap for the best way to do this
static void swap(PassIt** pptr1, PassIt** pptr2) {
   PassIt* tmp = *pptr1;
   *pptr1 = *pptr2;
   *pptr2 = tmp;
}

Java Example (complete code)

// The parameter is a copy of the value. Reassigning it does not change the caller.
public static void passByCopy(int copy) {
   copy = 33;  // only a "local" change
}

// No such thing as pointers in Java
/*
public static void passByPointer(PassIt *ptr) {
   ptr->i = 33;
   ptr = 0; // better to use nullptr instead of 0
}
*/

// The parameter is a copy of the reference. Field changes are visible to the caller.
public static void passByAlias(PassIt ref) {
   ref.i = 44;
}

// The parameters are copies of the references, so this swaps field values.
// Assigning ref1 or ref2 would not swap the caller's variables.
public static void swap(PassIt ref1, PassIt ref2) {
   PassIt tmp = new PassIt(ref1);
   ref1.copy(ref2);
   ref2.copy(tmp);
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents