What does it mean to return a value?

后端 未结 3 1792
渐次进展
渐次进展 2020-12-03 12:56

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

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-03 13:38

    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.

提交回复
热议问题