First value of the local var: 7 First value of the parameter: 7 Second value of the parameter: 100 Second value of the local var: 7
Once a value has been copied into an invoked method
(in the example, print()
)
the invoked method can use the copy or change the copy.
But the changes do not affect the caller.
How can a method send a value back to the caller?
Examine the following:
class SimpleClassTwo { public int twice( int x ) { return 2*x; } } class SimpleTesterTwo { public static void main ( String[] args ) { int var = 7; int result = 0; SimpleClassTwo simple = new SimpleClassTwo(); System.out.println("First value of result: " + result ); result = simple.twice( var ); System.out.println("Second value of result: " + result ); } }
To return a single value to the caller,
an invoked method can use the return
statement
along with the value to be returned.
Now what is the output of the program?