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;
}
}
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.
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With