2

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.

BlackBeard
  • 10,246
  • 7
  • 52
  • 62
thatman
  • 333
  • 3
  • 14
  • 2
    Notice there's a `b=` and `s=` but no `a=`? That's because you're modifying `a`, not reassigning it. – shmosel Aug 24 '17 at 05:22

1 Answers1

3

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

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307