Object Oriented Programming: Unit I: Introduction to OOP and Java

Methods

with Example Java Programs

Methods are nothing but the functions defined by the particular class.• Return type of the methode, • name of the method, • parameter passed to the method, • body of the method

Methods

Methods are nothing but the functions defined by the particular class.

There are four parts of the method -

• Return type of the methode

• name of the method

parameter passed to the method

• body of the method

For example

Parameter Passing

• Parameter can be passed to the function by two ways-

1. Call by value

2. Call by reference

• In the call by value method the value of the actual argument is assigned to the formal parameter. If any change is made in the formal parameter in the subroutine definition then that change does not reflect the actual parameters.

• Following Java program shows the use of parameter passing by value-

Java Program

//Program implementing the parameter passing by value

public class ParameterByVal

{

void Fun(int a,int b)

{

a=a+5;

b=b+5;

}

public static void main(String args[])

{

ParameterByVal obj1=new ParameterByVal();

int a,b;

a=10;b=20;

System.out.println("The values of a and b before function call");

System.out.println("a= "+a);

System.out.println("b= "+b);

obj1.Fun(a,b);

System.out.println("The values of a and b after function call");

System.out.println("a= "+a);

System.out.println("b= "+b);

}

}

Output

The values of a and b before function call

a= 10

b= 20

The values of a and b after function call

a= 10

b= 20

Program Explanation

•The above Java program makes use of the parameter passing by value. By this approach of parameter passing we are passing the actual values of variables a and b.

• In the function Fun we are changing the values of a and b by adding 5 to them. But these incremented values will remain in the function definition body only. After returning from this function these values will not get preserved. Hence we get the same values of a and b before and after the function call.

• On the contrary the parameter passing by reference allows to change the values after the function call. But use of variables as a parameter does not allow to pass the parameter by reference.

• For passing the parameter by reference we pass the object of the class as a parameter.

• Creating a variable of class type means creating reference to the object. If any changes are made in the object made inside the method then those changes get preserved and we can get the changed values after the function call.

Object Oriented Programming: Unit I: Introduction to OOP and Java : Tag: : with Example Java Programs - Methods