TheWorldSoul TheWorldSoul - 27 days ago 20
Java Question

Variable from Separate Function Cannot Print in Main

public class practiceclock{

public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 5;
addTonum(x);
System.out.println(gby);
}
public static void addTonum(int gby) {
gby = gby + 1;
}
}


Why doesn't this print out 6? I'm trying to print out the integer gby from my "addTonum" function. I know it's pretty basic.

Answer

In java, when you pass a variable as an argument into a method, you are passing a copy of it, not the original instance. To fix this, you can either make the variable global, or you can have the method return the integer.

Also, use

gby +=1;

As a shortcut.

Comments