Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning a value from a method to another method

Tags:

java

Can somebody tell me why the value returned is 3 and not 8. Doesn't the return x statement from the addFive method change the value of x in the main method?

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;
    }
}
like image 759
flutter Avatar asked Nov 28 '22 23:11

flutter


2 Answers

You want x=addFive(x); rather than just addFive(x). Calling addFive(x) on it's own does not apply the returned value to any variable.

like image 135
Jud Avatar answered Dec 04 '22 12:12

Jud


You have to set the returned value to a variable, otherwise it is lost and you are retrieving the value of "x" in your main method. Do this instead to capture the return value.

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

If you only want to see the returned value and not store it, you can even put the function call inside the System.out.println.

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

   }
like image 38
Evan Bechtol Avatar answered Dec 04 '22 13:12

Evan Bechtol