Call by reference
It can be used to pass the instance of the class to the method which can be handled entire class in the method.
example:
import java.awt.Dimension;
public class A {
public static void main(String[] args)
{
A a =new A();
Dimension d = new Dimension(10,20);
System.out.println(d.height);
a.getvalue(d);
System.out.println(d.height);
}
void getvalue(Dimension dim)
{
dim.height = dim.height+1;
}
}
output:
20
21
The example for call by value:
public class B {
public static void main(String[] args)
{
int a=5;
B b =new B();
System.out.println(a);///output will be 5
b.modify(a); //output will be 6
System.out.println(a); //output will be 5
}
void modify(int x)
{
x=x+1;
System.out.println(x);
}
}
It can be used to pass the instance of the class to the method which can be handled entire class in the method.
example:
import java.awt.Dimension;
public class A {
public static void main(String[] args)
{
A a =new A();
Dimension d = new Dimension(10,20);
System.out.println(d.height);
a.getvalue(d);
System.out.println(d.height);
}
void getvalue(Dimension dim)
{
dim.height = dim.height+1;
}
}
output:
20
21
- The value which can modified by the method continued the same value in upcoming method also.
- It can replace the original value
The example for call by value:
public class B {
public static void main(String[] args)
{
int a=5;
B b =new B();
System.out.println(a);///output will be 5
b.modify(a); //output will be 6
System.out.println(a); //output will be 5
}
void modify(int x)
{
x=x+1;
System.out.println(x);
}
}
- The value modify can be used in particular method
- Again the original value can be used in the main method.
No comments:
Post a Comment