Call by value in java

In java, we have only ‘Call by value’, not ‘Call by reference’. In ‘Call by reference’ the address of the value is passed in the arguments of the methods, so if any changes made to variable changes the original value.

In ‘Call by reference’ , value of variable is passed from the method. So any changes made to the variable does not change the original value of the variable.

Let’s understand with the example below. In that example, we are making changes to the variable ‘Red’. But change happens only in the local variable of the method, not in the instance variable of the class.

public class ColorCode {
	
	int Red = 3;
	
	void changeColor(int Red){
		Red = Red;
		System.out.println("Color code here "+Red);
	}

	public static void main(String[] args) {
		ColorCode code = new ColorCode();
		System.out.println("Without changing color code " + code.Red);
		code.changeColor(6);  // changing the color code to 6
		System.out.println("After changing color code " + code.Red);
	}

}
Output:
Without changing color code 3
Color code here 6
Without changing color code 3

But if we really want to change the original value , then we have to pass the object reference while calling the method and change the value directly from the object reference. That change will be done in original value as well.

public class ColorCode {
	
	int Red = 3;
	
	void changeColor(ColorCode c, int a){
		c.Red = a;
		System.out.println("Color code here "+Red);
	}

	public static void main(String[] args) {
		ColorCode code = new ColorCode();
		System.out.println("Without changing color code " + code.Red);
		code.changeColor(code,6);  // changing the color code to 6
		System.out.println("After changing color code " + code.Red);
	}

}
Output:
Without changing color code 3
Color code here 6
After changing color code 6
Ask Question
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...