TheWorldSoul TheWorldSoul - 1 year ago 113
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;
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download