- /**
- * Demonstrates the difference between
passing an argument
- * into a method by reference vs.
passing by value.
- *
- * @author TK Rogers
- * @version 1/2/2011
- */
- public class PassByRefDemo {
- public static void
main ( ) {
-
int numbers [ ] = new int [ 3 ] ;
-
int x = 2 ;
-
- System.out.println (
"Original values" ) ;
- for (
int y = 0 ; y < numbers.length ; y++ ) {
-
System.out.println ( " numbers [ " +
y + " ] = " + numbers [ y ] ) ;
- }
- System.out.println (
" x = " + x +
"\n" ) ;
- alter ( numbers, x ) ;
-
- System.out.println (
"New values" ) ;
- for (
int y = 0 ; y < numbers.length ; y++ ) {
-
System.out.println ( " numbers [ " +
y + " ] = " + numbers [ y ] ) ;
- }
- System.out.println (
" x = " + x ) ;
- }
-
- // The argument x is
passed into the method by value. The array is passed
- // into the method by
reference, in other words it's starting memory
- // location.
- public static void
alter ( int array [ ] , int x ) {
- for (
int y = 0 ; y < array.length ; y++ ) {
-
array [ y ] = y + 2 ;
-
x = 27 ;
- }
- }
- }