0

I am trying to understand how the following code works:

    ArrayList<String> aInt = new ArrayList<String>();
    Object[] bInt = null;

    aInt.add("1a");
    aInt.add("2b");
    aInt.add("3c");
    aInt.add("4d");

    bInt = new String[aInt.size()];

    aInt.toArray(bInt);

    for(int i=0; i < bInt.length; i++){
        System.out.println(bInt[i]);
    }

I understand everything except for the line aInt.toArray(bInt); My question is how is bInt actually being updated using this if you never do bInt = aInt.toString()? I thought java only passes items by value and not reference so I this has me stumped.

I did confirm that the System.out.println statement does print out 1a, 2b, 3c, and 4d.

Thank you for your help

xCasper
  • 123
  • 9
  • An object's name is actually its reference. – Mohammed Aouf Zouag Nov 20 '15 at 22:03
  • Java does only pass by value, but what's often being passed is the object reference. Think of it as passing a pointer. – azurefrog Nov 20 '15 at 22:03
  • What do you think `toArray` does? What did you think the output should be? Why? – Sotirios Delimanolis Nov 20 '15 at 22:04
  • If you don't understand what a method is doing, start by reading its documentation: ["If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list."](http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#toArray-T:A-) – azurefrog Nov 20 '15 at 22:06
  • JDev - Thank you, I didnt realize that was how it was working. Azurefrog - Thank you, that is how I am going to think of it from now on! Sotirios Delimanolis - I expected to have to set the bInt to aInt in order to get the values stored in bInt. In c++ I know you can do these things but in Java I thought you could not without actually setting one equal to another AzureFrog - I did read the documentation but since it was being returned and not set I was confused as to how the returned values were being stored in the object – xCasper Nov 20 '15 at 22:17

1 Answers1

1

Java does only pass-by-value, but the value for any object, including those reprensenting primitive values (such as String and Integer) are actualling passing the value of a reference.

So, objects are logically always pass-by-reference even though technically you could argue the code passes-by-value.

For example, if you pass an object reference into another method from a local variable, the local variable from the original method will not change (i.e. it will still refer to the same object after the call), even though the objet to which it refers may be modified. Hence part of the great value of immutable objects (like String).

ash
  • 4,078
  • 1
  • 17
  • 29
  • Ah ok. Thank you for your detailed response. I never realized that is how it worked. That makes sense. – xCasper Nov 20 '15 at 22:17