Dan S Dan S - 4 months ago 4x
Java Question

Java - How to Print an updated returned value from another method

I'm hoping this is an easy question where I'm missing something small.

I'm working on a project where in the main method the program reads in an integer from the user, passes the number to a second method which simply adds 1, then passes the new value back to main. Lastly, the main method prints out the updated value.

Here's what I have so far:

public static void main(String[] args) {
System.out.println("Enter an integer");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
//update value

public static int inc(int num) {
num = num+1;
return num;

Sadly, this only prints the original input value, not the value updated by the second method "int". For example, if I enter the initial value of "5" it should print "6", however, it prints "5".

How do I have the program print the updated "+1" version of the variable?


Change inc(num); into num = inc(num);. Java passes a copy of num to the inc function.

Inside the function, this is the copy that is modified, and the original value doesn't change. As you already return the new value, you have to take it into account, because else the old one won't be modified.

A useful post regarding this matter: Is Java pass-by-reference or pass-by-value ?