There is an example program in my java book that makes no sense to me. Basically it passes an array reference to a method. But the outcome is that the array itself is modified even though the method doesn't have a return or something within it that indicates its doing something other than creating it's own instance of the array.
public class PassArray
{
public static void main( String[] args )
{
int[] array = { 1, 2, 3, 4, 5 };
System.out.println(
"Effects of passing reference to entire array:\n" +
"The values of the original array are:" );
for ( int value : array )
System.out.printf( " %d", value );
modifyArray( array ); // pass array reference to method modifyArray
System.out.println( "\n\nThe values of the modified array are:" );
// output the value of array (why did it change?)
for ( int value : array )
System.out.printf( " %d", value );
} // end main
// multiply each element of an array by 2
public static void modifyArray( int array2[] ) // so this accepts an integer array as an arguement and assigns it to local array array[2]
{
for ( int counter = 0; counter < array2.length; counter++ )
array2[ counter ] *= 2;
} // What hapened here? We just made changes to array2[] but somehow those changes got applied to array[]??? how did that happen?
//What if I wanted to not make any changes to array, how would implement this code so that the output to screen would be the same but the value in array would not change?
} // end class PassArray
Please explain why this is the case and also how this could be implemented somehow so that the values of array are not changed. S