These are ways of passing data in a subroutines/functions/procedures/methods

Fundamentally it boils down to

  • whether the method receives a copy of the argument’s value or
  • direct access to the argument’s storage location

Pass By Value

When an argument is passed to a subroutine by value, each parameter specified for the subroutine will hold a copy of the data from the original argument.

  • This data is held in a separate memory location and is only available to the subroutine (meaning the parameter has local scope).
  • Even if the value of the parameter is changed within the subroutine, the value of the original argument is unchanged.
    • You can modify the object’s properties (e.g., user.Name = "Alice"), and the caller will see it, because both pointers point to the same object.
    • You cannot reassign the object itself (e.g., user = new User()). This only updates the local copy of the pointer, leaving the caller’s variable unchanged.

Pass By Reference

When an argument is passed to a subroutine by reference,

  • this creates a pointer that contains the memory address of the original variable.
  • Therefore, any change to the parameter within the subroutine also affects the value of the original variable.
    • You can completely reassign the object (user = new User()), and the original variable outside the method will now point to this brand-new object.

Java is strictly Pass by Value for both primitives and objects. By default, C# passes all arguments by value unless you explicitly use modifiers like ref or out. ^2

References