0

I am pretty new to Java and one topic just blew my mind. Passing array to a java function. Code is as follows:

private void PassArray(){
String[] arrayw = new String[4]; //populate array
PrintA(arrayw);
}

private void PrintA(String[] a){
//do whatever with array here
}

They say in java arrays are passed by reference. But it looks so much similar to "Call by Value" in C:

#include <stdio.h>

/* function declaration */
double getAverage(int arr[], int size);

int main ()
{
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
double avg;

/* pass pointer to the array as an argument */
avg = getAverage( balance, 5 ) ;

/* output the returned value */
printf( "Average value is: %f ", avg );

return 0;
}

double getAverage(int arr[], int size)
{
int    i;
double avg;
double sum;

for (i = 0; i < size; ++i)
{
sum += arr[i];
}

avg = sum / size;

return avg;
}

Please explain the difference between them in terms of value,reference and memory allocations. Any further links will be appreciated.

H D
  • 77
  • 1
  • 10
  • 5
    "*They say in java arrays are passed by reference*" => *They* are wrong: [Java is "pass by value"](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value?rq=1). – assylias Jun 22 '15 at 17:16
  • Consider and try the case where `PrintA` actually modifies the array. – nanofarad Jun 22 '15 at 17:16
  • 3
    Who are "they"? Because they are wrong - there is no pass by reference in Java. – RealSkeptic Jun 22 '15 at 17:17
  • @assylias usually this is just a simplification given to new Java users. It achieves a similar outcome to pass by reference by passing the value of the reference. To clarify what "they" mean: "There's no conceptual difference between 'passing a reference' and 'passing the value of a reference', assuming that you mean 'the value of the internal pointer to the object'" (Credit to a comment on the answer for http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – River Jun 22 '15 at 17:18
  • 1
    "They" are wrong. Java is pass-by-value. See http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – Andy Turner Jun 22 '15 at 17:18
  • I say.. nuke "them"...all in favour? Raise hands (please) :-) – Sourav Ghosh Jun 22 '15 at 17:19
  • I was unaware you could pass arrays without pointers in C – Snappawapa Jun 22 '15 at 17:21
  • Java may be pass by value, but you pass reference objects by value. The semantics are similar to passing C pointers, i.e. you get a local copy of something that refers to an external entity. In C, a function parameter `T[]` is actually the same as a pointer, `T*`. So you're passing pointers to the 1st element of an array. This is quite a broad topic, which is why I post this as a comment rather than an answer. There's too much to cover in one post. – juanchopanza Jun 22 '15 at 18:16

3 Answers3

2

Arrays in C are "pass-by-reference" and not "pass-by-value". Please look at the following program:-

    void print_array (int array[], int len)
    {
        printf("Printing the array: ");
        int i;

        for (i = 0; i < len; ++i) {
            printf("%d ", array[i]);
        }

        printf("\n");
    }

    void populate_array (int array[], int len)
    {
        printf("Populating the array....\n ");
        int i;

        for (i = 0; i < len; ++i) {
            array[i] = i;
        }
    }


    int main() 
    {
        int array[5];
        memset(array, 0, sizeof(int) * 5);  

        print_array(array, 5);  
        populate_array(array, 5);
        print_array(array, 5);  

        return(0);
    }

    Output:-
    GAGUPTA2-M-40UT:Desktop gagupta2$ ./a.out 
    Printing the array: 0 0 0 0 0 
    Populating the array....
    Printing the array: 0 1 2 3 4 

So once you pass arrays as parameters to functions, it is no longer "pass-by-value" mechanism in C. It is "pass-by-reference". Hence, prior to calling populate_array(), the contents of the array were all zeros and after calling populate_array() they had some value.

In Java you will observe something similar. Putting a similar Java code below:-

    public class Test 
    {
        public static void print_array (String[] array)
        {
            System.out.println("Printing the array");

            for (int i = 0; i < array.length; ++i) {
                System.out.print(array[i] + " ");
            }

            System.out.println();
        }

        public static void populate_array (String[] array)
        {
            System.out.println("Populating the array");

            for (int i = 0; i < array.length; ++i) {
                array[i] = new String("init_array");    
            }
        }

        public static void main (String[] args) 
        {
            String[] array = new String[5];

            print_array(array);
            populate_array(array);
            print_array(array);
        }
    }

Output:-
GAGUPTA2-M-40UT:Desktop gagupta2$ java Test
Printing the array
null null null null null 
Populating the array
Printing the array

In java the primitive data types like int, float, double, boolean etc are always passed by value but when you pass non-primitive types like arrays, string and objects, the address of the object gets passed. See Is Java "pass-by-reference" or "pass-by-value"? for more details.

Community
  • 1
  • 1
gaurav gupta
  • 137
  • 3
0

Arrays are allocated on the heap and they will be passed by reference. Compared to C they look like automatic variables and handling also looks like handling of automatic variable in C. Simply try to change array in method (function) and see what is happening. On the other side integer is allocated on the stack and is passed by value. Here are some typical manipulations, passing array as parameter to function and returning it from function.

public static void main(String[] args) {
  int[] arr = {0, 0, 0, 0};
  print(arr);
  load(arr);
  print(arr);
  print(generate(5));
  long s = 0;
  System.out.println("long is " + s);
}

void willItChange(long param){
  param = 3;
}
static int[] generate(int size){
  int[] arr = new int[size];
  for(int i = 0; i<size; i++)
    arr[i] = i + 1;
  return arr;
}

static void load(int[] arr){
  for(int i = 0; i<arr.length; i++)
    arr[i] = i + 1;
}

static void print(int[] arr){
  for(int i = 0; i<arr.length; i++)
    System.out.print(arr[i] + " ");
  System.out.println();
}

Execution should produce the following output

0 0 0 0 
1 2 3 4 
1 2 3 4 5 
long is 0

Arrays are passed by reference and long is passed by value.

Filip Bulovic
  • 1,530
  • 12
  • 10
0

In C:

In a sense, you cannot "pass arrays" in C, because it is impossible for a function to have a parameter of array type. The standard states that a function declaration containing a parameter declared to be of "array of T" type will be "adjusted" to be a parameter of "pointer to T" type. In your example above, the parameter arr has type int * (pointer to int).

So what happens in the call expression getAverage( balance, 5 ) where balance is an array (int [5])? The compiler sees that the function expects a pointer type (int *) for that parameter, and then applies the implicit conversion from an array value into a pointer rvalue (a pointer to the first element of the array) before passing this pointer (to the parameter which expects a pointer). As you can see, there is no passing of "arrays".

Also, everything in C is pass-by-value. There is no pass-by-reference in C. The pointer-to-int you are passing is passed by value, i.e. its value (what it points to) is copied into a local copy in the function.

In Java:

In Java, arrays are objects and objects in Java are not values and cannot be "passed" (there are no "object types" in Java; only primitive types and reference types). Arrays, like all objects, can only be manipulated through "references" (pointers to objects).

Everything in Java is pass-by-value. There is no pass-by-reference in Java. In your example, you have a parameter a of type String[], which is a reference type that can hold pointers to array-of-String objects. The pointer to array you are passing is passed by value, i.e. its value (what it points to) is copied into a local copy in the function.

newacct
  • 110,405
  • 27
  • 152
  • 217