Java Call By Value
In java there is only one way of calling a method, only call by value. Call by reference concept is not allowed in java because of some security concern.
Call by value is a way of calling a method by passing a value of some type.
Example:
Below program shows that calling a method by value and performing changes, does not make a change in the original value.
public class TestCallByValue {
public static void main(String[] args) {
int first = 20, second = 30;
System.out.println("values before calling method - " + first + " and " + second);
TestCovariant obj = new TestCovariant();
obj.addition(first, second);
System.out.println("values after calling method - " + first + " and " + second);
}
public void addition(int i, int j) {
i = i + 20;
j = j + 20;
System.out.println("param values in calling method = " + i + " and " + j);
}
}
Example Output
Below program shows that calling a method by object type value and performing changes, does make a change in the original value.
class Car {
int speed = 250;
}
public class TestCovariant {
public static void main(String[] args) {
TestCovariant obj = new TestCovariant();
Car car = new Car();
System.out.println("speed of car before calling method = " + car.speed);
obj.changeSpeed(car);
System.out.println("speed of car before calling method = " + car.speed);
}
public void changeSpeed(Car car) {
car.speed = 150;
System.out.println("speed of car inside method = " + car.speed);
}
}
Example Output