You are on page 1of 8

IT@GEP

PARAMETRS PASSING IN JAVA

By
PRUDVI RAJ CHEEKATI DEPT: COMPUTER SCIENCE AND ENGINEERING

IT@GEP

Parameter Passing
int plus (int a, int b) { return a+b; }

formal parameters function body actual parameters (arguments)

int x = plus(1,2);

function call

Page 2 of 8

IT@GEP

A Closer Look at Argument Passing


In general, there are two ways that a computer language can pass an argument to a subroutine.

Parameter Passing Primitive Type The first way is call-by-value.


y

Java passes all parameters to a method by value. The actual parameters (the values that are passed in) are assigned to the formal parameters (declared in the method header). This means that the value of the actual parameter is copied into the formal parameter. Therefore, changes made to the parameter of the subroutine have no effect on the argument.

PAGE 3 Of 8

IT@GEP

Parameter Passing Reference Type




The second way an argument can be passed is call-by-reference. When an object is passed to a method, Java passes a reference to that object. The value that is copied is the address of the actual object. Therefore it is important to understand that when a formal parameter object is used it modifies the actual object state permanently. When a simple type is passed to a method, it is done by use of call-by-value. Objects are passed by use of call-by-reference

Page 4 of 8

I T@GEP
//Example CALL BY VALUE. class Test { void meth(int i, int j) { i *= 2; j /= 2; }} class CallByValue { public static void main(String args[]) { Test ob = new Test(); int a = 15, b = 20; System.out.println("a and b before call: " + a + " " + b); ob.meth(a, b); System.out.println("a and b after call: " + a + " " + b); } } The output from this program is shown here: a and b before call: 15 20 a and b after call: 15 20
PAGE 5 Of 8

IT@GEP //Example CALL BY REFERENCE class Test { int a, b; Test(int i, int j) { a = i; b = j; } // pass an object void meth(Test o) { o.a *= 2; o.b /= 2; } } class CallByRef { public static void main(String args[]) { Test ob = new Test(15, 20);
PAGE 6 Of 8

IT@GEP

System.out.println("ob.a and ob.b before call: " +ob.a + " " + ob.b); ob.meth(ob); System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b); } } This program generates the following output: ob.a and ob.b before call: 15 20 ob.a and ob.b after call: 30 10

PAGE 7 Of 8

IT@GEP

Thank you.

Page 8 of 8

You might also like