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.

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.

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
Encapsulation in java
String in java
Shekhar Sharma

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...

Leave a Reply

Your email address will not be published. Required fields are marked *