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.

1

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

so how to access an 'a' instance variable from modify()? You can't use 'this' in static context right?
@jarosik You can qualify it. Main.a.
Other valid solution I came up with: you can just rename the method argument to: modify (int b) or anything else than 'a' and the plain 'a++' would work.
@jarosik The concept is known as scope.
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++;

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.