0

I know java is pass by value But here How the array[i] is changing the value of arr[i].The below program is arranging zeros and ones in order

Is there any special case for Array-Pass by value

class GFG { 
      
    // function to segregate 0s and 1s 
    static void segregate0and1(int arry[], int n) 
    { 
        int count = 0; // counts the no of zeros in arr 
      
        for (int i = 0; i < n; i++) { 
            if (array[i] == 0) 
                count++; 
        } 
  
        // loop fills the arr with 0 until count 
        for (int i = 0; i < count; i++) 
            array[i] = 0; 
  
        // loop fills remaining arr space with 1 
        for (int i = count; i < n; i++) 
            array[i] = 1; 
    } 
      
    // function to print segregated array 
    static void print(int arr[], int n) 
    { 
        System.out.print("Array after segregation is "); 
        for (int i = 0; i < n; i++) 
            System.out.print(arr[i] + " ");     
    } 
      
    // driver function 
    public static void main(String[] args) 
    { 
        int arr[] = new int[]{ 0, 1, 0, 1, 1, 1 }; 
        int n = arr.length; 
  
        segregate0and1(array, n); 
        print(array, n); 
          
    } 
} 
  • 5
    Please re-read the answers to [Is Java pass-by-reference or pass-by-value](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value?rq=1). Arrays are treated like objects. – Federico klez Culloca Dec 01 '20 at 10:33
  • 6
    Does this answer your question? [Is Java "pass-by-reference" or "pass-by-value"?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – Skgland Dec 01 '20 at 10:34
  • 1
    Hint: consider what's being passed. It's not "the array", it's "a reference to the array". (That reference is passed by value though.) – Jon Skeet Dec 01 '20 at 10:38
  • 2
    There is no "special case" here. *"How the array[i] is changing the value of arr[i]."* - Because the value that passed is a reference. Just the same as when any object is passed by value. And you are *mutating* that array, just like you can mutate any other (mutable) object passed to a method. – Stephen C Dec 01 '20 at 10:38
  • I have the address of my house on a note in my hands. I copy the note and give the copy to you. You read the address on the note, go to the address, walk into the house and paint the walls yellow. Did you change *my* note? No. Did you change my house? Yes. Java is pass-by-value. I did not give you my note, I copied my note instead to give to you. – MC Emperor Dec 01 '20 at 11:17
  • See also [this answer](https://stackoverflow.com/a/54373107/507738). It has pictures of balloons. – MC Emperor Dec 01 '20 at 11:23

0 Answers0