Java passByValue or Reference confusion

59 Views Asked by At

I was trying to play with Java references and I got an interesting situation. This following piece of code gives unpredictable output to me. I am trying to modify an array, a string and an integer in a function.

 public static void main(String[] args){
     int[] arr = {1,2,3,4,5}; 
     Integer b = 6;      
     String s = "ABC";

     fun(arr, b,s);
     for(int i : arr)
         System.out.print(i + " ");
     System.out.println();
     System.out.println("b="+b);
     System.out.println("s="+s);
 }   

 public static void fun(int[] a, Integer b, String s){
     b = b*10;       
     for(int i =0; i<a.length; i++)
     {
         a[i] = a[i]+10;
     }       
     s=s+"PIY";
 }

Now this gives following output :

11 12 13 14 15 
b=6
s=ABC

I don't understand why array is getting changed but string and integers are not getting changed inside the function.

1

There are 1 best solutions below

2
On

Array is an Object and Integer and String are immutable in Java. You cannot change immutable object by reference. You have to reinsert/reassign to see the changes. Hence the difference.

Your logic applies and correct in case of general objects which are not immutable