- Forward


Parameter Passing Mechanisms
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • So Far:
    • We've invoked methods and passed them parameters, but not considered what happens "under the hood"
  • Now:
    • In order to understand what is and isn't possible in methods, we need to consider the details
  • Why Did We Wait Until Now?
    • You need to understand references before you can understand parameter passing
Common Parameter Passing Mechanisms
Back SMYC Forward
  • Call by Value:
    • A copy of the contents of the actual parameter is made and assigned to the formal parameter
  • Call by Reference:
    • A reference to the actual parameter is assigned to the formal parameter (which makes the formal parameter an alias for the actual parameter)
Parameter Passing in Java
Back SMYC Forward
  • The Rule:
    • All parameters are passed by value
  • The Confusion:
    • For primitive types the parameter is a copy of the value
    • For class types the parameter is a copy of the reference (and, hence, an alias)
Passing Value Types
Back SMYC Forward

Trying to Swap Two Values

javaexamples/basics/ParameterPassingExample1.java (Fragment: 0)
 
Parameter Reference Types (cont.)
Back SMYC Forward

Swapping the Attributes of Two Objects

javaexamples/basics/Pair.java (Fragment: 0)
 
javaexamples/basics/ParameterPassingExample1.java (Fragment: 1)
 
Parameter Reference Types (cont.)
Back SMYC Forward

Trying to Swap Two Objects

javaexamples/basics/Pair.java (Fragment: 0)
 
javaexamples/basics/ParameterPassingExample1.java (Fragment: 2)
 
Parameter Reference Types (cont.)
Back SMYC Forward

Swapping Two Elements of an Array

javaexamples/basics/ParameterPassingExample1.java (Fragment: 3)
 
Parameter Reference Types (cont.)
Back SMYC Forward

Trying to Swap Two Arrays

javaexamples/basics/ParameterPassingExample1.java (Fragment: 4)
 
There's Always More to Learn
Back -