Java Pass By Value and Pass By Reference

I made the following sample to test my knowledge

import java.util.Map; public class HashMap { public static Map<String, String> useDifferentMap(Map<String, String> valueMap) { valueMap.put("lastName", "yyyy"); return valueMap; } public static void main(String[] args) { Map<String, String> inputMap = new java.util.HashMap<String, String>(); inputMap.put("firstName", "xxxx"); inputMap.put("initial", "S"); System.out.println("inputMap : 1 " + inputMap); System.out.println("changeMe : " + useDifferentMap(inputMap)); System.out.println("inputMap : 2 " + inputMap); } } 

output:

 original Map : 1 {initial=S, firstName=xxxx} useDifferentMap : {lastName=yyyy, initial=S, firstName=xxxx} original Map : 2 {lastName=yyyy, initial=S, firstName=xxxx} 

this useDifferentMap method gets the map and changes the value and returns the same thing back. the changed map will contain the changed value, and its area is local to the useDifferentMap method.

My question is that if java is passed by value, this changed value should not be affected on the source map.

so java goes by value or goes by reference

thanks

+6
source share
4 answers

Java is always pass-by-value , only in this case the link to the HashMap is passed by value. valueMap refers to the same object as inputMap .

Therefore, when you add a key-value pair using valueMap , it returns back to inputMap , since both refer to the same HashMap object.

This answer from Eng.Fouad very well explains this concept.

+8
source

Java is bandwidth. But your doubt is that the link is referenced, even the link in java is passed by value.

Thus, the reference value has passed, and the card gets implemented.

You are confused with the term pass by value. pass the value in a reference accepted as a value.

+3
source

When calling useDifferentMap(inputMap) for the Map<String, String> valueMap parameter Map<String, String> valueMap assigned:

 Map<String, String> valueMap = inputMap; 

After assignment, two links inputMap and valueMap now refer to the same object in memory and, therefore, modify this object with one link, will be reflected in another link.

+3
source

Java is just a pass-byvalue. No, where is the link forwarding. inputMap and valueMap (a copy of inputMap) are links to the same hash file. Thus, we can access all the methods on the hash map using any of the links - it’s like two remote controls to the same TV.

 public static Map<String, String> useDifferentMap(Map<String, String> valueMap) { valueMap=null; } 

try it. If it were pass-by-ref, you would get NPE in the last line of the main method after calling useDifferentMap ()

+2
source

Source: https://habr.com/ru/post/958362/


All Articles