What does it mean to return a value?

后端 未结 3 1773
渐次进展
渐次进展 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.

    0 讨论(0)
  • 2020-12-03 13:46

    In simple terms, it means to return the value to caller of the method...

    So, in your example, the method getX would return the value of x to the caller, allowing them access to it.

    class Class1{
    
        static int x = 3;
    
        public static int getX(){
            return x;
        }
    
        public static void main(String args[]){
            int myX = Class1.getX(); // return the value to the caller...
            System.out.println(myX); // print the result to the console...
        }
    }
    
    0 讨论(0)
  • 2020-12-03 13:50

    You are just calling a method which returns an integer but you are never using/printing it. Try to use it in your code to see whether you have got the desired value as you have set in your class.

    0 讨论(0)
提交回复
热议问题