I have searched a lot and every where found that java is pass by value but still I am not satisfied with the answers.
Below is the code. Here if i am passing the object of HashMap
then I am getting its updated value while in case of integer it is not like that. What is the difference between these both.
How pass by value is working in both cases-
public static void main(String[] args) {
HashMap hm = new HashMap();
System.out.println(hm.size()); //Print 0
operation(hm);
System.out.println(hm.size()); //Print 1 ; Why it's updating the HashMap.
Integer c = new Integer(3);
System.out.println(c); //Print 3
getVal(c);
System.out.println(c); //Print 3: Why it's not updating the integer like HashMap.
}
public static void operation(HashMap h) {
h.put(“key”, “java”);
}
public static void getVal(Integer x) {
x = x + 2;
System.out.println(x);
}