Presentation is loading. Please wait.

Presentation is loading. Please wait.

Parameter Passing in Java

Similar presentations


Presentation on theme: "Parameter Passing in Java"— Presentation transcript:

1 Parameter Passing in Java
CS 239

2 General Rule In Java, all parameters are passed by value
Value of actual parameter is copied into the formal parameter. The formal parameter holds a copy of the actual parameter

3 Specifics When the formal parameter is a primitive type, the formal parameter acts as a local variable. This means that changes made to the formal parameter inside the method do not affect the actual parameter. When the formal parameter is an object, what is copied in to it is not a value but an address. This means that changes made to the formal parameter inside the method may affect the actual parameter.

4 Clarification of Previous Slide
Suppose you have a swap method which interchanges the two parameters where, for the moment type is not specified. public void swap (type x, type y) { type temp; temp = x; x = y; y = temp; }

5 When type is a primitive type
public void swap (int x, int y) { int temp; temp = x; x = y; y = temp; } The formal parameters x and y hold copies of the actual parameter values and act as local variables. Changes made to formal parameters x and y do not affect the actual parameters.

6 When type is a simple object
public void swap (Integer x, Integer y) { Integer temp; temp = x; x = y; y = temp; } Since x and y are objects, the formal parameters x and y hold copies of the actual parameter addresses which act as local variables. This swap locally swaps the addresses stored in x and y. Changes made to formal parameters x and y do not affect the values stored in the actual parameters.

7 When type is a object public void swap (Int [] numbers, int x, int y)
{ int temp; temp = numbers[x]; numbers[x] = numbers[y]; numbers[y] = temp; } Here, formal parameters x and y have local copies of values which represent positions in an array. Nothing is being done to them. Formal parameter numbers holds the address of an array which holds int values. When you access numbers[x], you are asking for that value stored there. Thus swapping numbers[x] and numbers[y] swaps the values stored in those positions in the actual parameter corresponding to numbers.


Download ppt "Parameter Passing in Java"

Similar presentations


Ads by Google