Returning a value from a method to another method

Can someone tell me why the return value is 3, not 8. Does the return xmethod operator express the addFivevalue xin the method main?

public class App {
    public static void main(String[] args) {
        int x=3;
        addFive(x);
        System.out.println("x = " + x);
    }

    private static int addFive(int x) {
        x += 5;
        return x;
    }
}
+4
source share
8 answers

You want x=addFive(x);, not just addFive(x). A call addFive(x)of its own does not apply the return value to any variable.

+6
source

You must set the return value of the variable, otherwise it will be lost, and you will get the value "x" in your main method. Do this instead to commit the return value.

   public static void main(String[] args) {
       int x=3;
       x = addFive(x);
       System.out.println("x = " + x);
   }

, System.out.println.

   public static void main(String[] args) {
       int x=3;
       System.out.println("x = " + addFive(x));

   }
+3

, . "addFive (x)" "x = addFive (x)"; "x" , .

, "x" , "x" addFive() . , . - http://www.tutorialspoint.com/java/java_variable_types.htm

+2

java, - , , . , System.out.println(addFive(x));, x, x = addFive(x);

+2

addFive(int x) x, -. , main() scope x , 3 - , . , x:

x = addFive(x);

:

System.out.println("x = " + addFive(x));
+1

, , , ? 10 , , , ? :

x = addFive(x);
+1

. x, .

- :

int y = addFive(x);
0

addFive(int x ). x addFive(int x).

The JVM creates a copy of x and sends it to the method addFive(int x). Then xchanges in the method addFive(int x). But the xin method main()remains unchanged.

If you want to get the modified value returned addFive(int x)from the main method, you can do the following -

int returnedValueFromAddFive = addFive(x)  

Hope this helps.
Many thanks.

0
source

All Articles