문제

public class Demorun 
      {
    static int x=20;

    public static void change(int x){
        x=10;
        System.out.println("inside x: "+x);
    }

    public static void main(String[] args) {
        change(x);
        System.out.println("outside x: "+x);
    }
}

output

inside x: 10
outside x: 20

Since there is only one copy of the static variable then why is the value of x is still 20? Why is the change made in method change() not making a permanent change of the static variable?

도움이 되었습니까?

해결책

There's no need to pass x as an argument to change, and the fact that it's shadowing the member variable is the cause of the undesired behavior (your change function is just modifying the argument instead of the member variable).

The following code is simpler and would have the desired effect:

public class Demorun
{
    static int x = 20;

    public static void change()
    {
        x = 10;
        System.out.println("inside x: " + x);
    }

    public static void main(String[] args)
    {
        change();
        System.out.println("outside x: " + x);
    }
}

다른 팁

When you call change(x), you're passing in a copy of the variable x, not x itself. There is no pass-by-reference in Java; this is pass-by-value. If you want to change the outer x, do:

x = change(x);

and modify change(x) to:

public static  void change(int x){
    x=10;
    System.out.println("intside x: "+x);
    return x;
 }

or not pass in x at all to the change() method.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top