Java is Both Pass-By-Reference and Pass-By-Value, However

java logo

Yes you heard that right, Java works on Pass-By-Reference and Pass-By-Value but there is a twist and this makes a lot of confusion.

Before I start trying to prove that Java is both, lets start this by understanding these two concepts.
Pass-By-Reference – the caller and callee shares the same variable.
A good explanation from Post
Pass-By-Value – the method caller and callee does not shares the same variable.

Here, we will try to examine to understand both and know the confusing part.

In Java, pass-by-reference can be observed when you instantiate a class and pass it to multiple objects. In this example, foo1.setBars() method sets the Foo class bars property from the local localBars variable. We modified the foo1 bars using foo1.getBars().put(“Hello1”, “World2”); and the result, it prints two “Hello1” from both Foo’s. In this example, we can see that both foo1 and foo2 is referenced to the same localBars as seen in the output#3 and #4.

In this pass-by-value example below, we set the bar value using Foo’s method setBar(String) using local variable lbar1. Here we can see that setting the local variable lbar1 after calling setBar() method does not affect the foo1’s and foo2’s bar variable.

The confusing part is that, both example doesn’t have any difference except for the local variable type. The localBars is a Map<String,String> while the lbar1 is a String. We modified both variable after calling the Foo’s methods and display their values.

Below is the complete java class example used in this post.

If you find this article helpful, just put your comments below.

Leave a Reply

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