Showing posts with label Method parameters. Show all posts
Showing posts with label Method parameters. Show all posts

Friday 5 February 2016

Call by reference and Call by value

Java uses call by value. That means all parameters to methods are pass by value or call by value,the method gets a copy of all parameter values and the method cannot modify the contents of any parameter variables that are passed to it.
Please see sample programs below.

call by value: 
class One
{
void display(int i,int j)
{
i*=4;
j/=4;
}  
}
class Two
{
public static void main(String as[])
{
int a=10;
int b=20;
System.out.println("before calling");
System.out.println("a="+a);
System.out.println("b="+b);
One sample=new One();
sample.display(a,b);
System.out.println("after calling");
System.out.println("a="+a);
System.out.println("b="+b);
}
}
OUTPUT:
before calling
a=10
b=20
after calling
a=10
b=20

call by reference:
class One
{
int a,b;
One(int i,int j)
{
a=i;
b=j;
}
void display(One ab) //pass an object
{
ab.a*=2;
ab.b/=2;
}
}

class Two
{
public static void main(String as[])
{
One sample=new One(10,20);
System.out.println("before calling");
System.out.println("a="+sample.a);
System.out.println("b="+sample.b);
sample.display(ab);
System.out.println("after calling");
System.out.println("a="+sample.a);
System.out.println("b="+sample.b);
}
}

Output:
before calling
a=10
b=20
after calling
a=20
b=10

By above example programs hope understood the difference between call by value and call by reference.


Sunday 19 January 2014

INTRODUCING METHODS

In java,there are some fundamentals that you need to learn now so that you can begin to add methods to your classes.Although it is perfectly fine to create a class that contains only data,it rarely happens.Most of the time you will use methods to access the instance variables defined by the class.