0

I thought static primitive variables in java should work differently than non-static when passed to a method:

public class Main {

    private static int a;

    public static void main(String[] args) {
        modify(a);
        System.out.println(a);
    }

    static void modify(int a){ 
        a++;
    }
}

The output is 0 which is understandable for primitives passed by value, but why static doesn't mean anything here? I would expect 1 as an output.

Maybe a silly question but I am confused.

jarosik
  • 4,136
  • 10
  • 36
  • 53

3 Answers3

2

The name a in your modify method is referring to the local method parameter, not the static variable.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
0

You are having a shadowing variable in your static method when a++ get executed it will increase the value of that method local variable by 1

static variable default value is 0 and will not get affect.

if you want that to be changed use

Main.a++;
0

If you really want to, you could solve this by an int wrapper, like AtomicInteger:

public class Main {

    private static final AtomicInteger a = new AtomicInteger(0);

    public static void main(String[] args) {
        modify(a);
        System.out.println(a);
    }

    static void modify(AtomicInteger  a){ 
        a.getAndIncrement(); // "eqvivalent" of a++
    }
}

Your current code, takes an int, and because how Java works, it recieves a copy of your static a, and has no effect on your static field.

Balázs Édes
  • 13,452
  • 6
  • 54
  • 89