I\'m fairly new to programming, and I\'m confused about what it means exactly to return a value. At first, I thought it meant to output what value is being returned, but whe
Returning a value is a way for methods to talk to each other
public void method1() {
int value = 5 + method2(5);
System.out.println(value);
}
public int method2(int param) {
return param + 5;
}
This will print 15 (5 gets sent to method2, which adds 5 to it and returns the result to method1, which adds 5 to it and prints the result).
Java returns copies of values - in this case, it's copying the value 10 and returning it to method1. If method2 were returning an Object then it would return a copy of the object's reference. Different languages have different semantics for method returns, so be cautious when switching between languages. Java also copies the values of parameters passed to methods - in this case method1 copies the value 5 and passes it to method2.
public void method1() {
int value = 5;
method2(value);
}
public void method2(int param) {
param = param + 5;
}
The value in method1 is unaffected by method2 (value still equals 5 after method2 executes), because only a copy of value was sent as a parameter.