Pregunta

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?

¿Fue útil?

Solución

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);
    }
}

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top