Changing a variable permanently in a static method

Let's say I have a public class with static methods, one of them, for example:

 public static void test(boolean b){
   b = !b;
 }

      

Let's say this is the name of the Test class. From another class where I have a boolean variable a = false, I call

 Test.test(a);

      

How can I make it constantly change and not just change it in the scope of static methods?

+3


source to share


6 answers


It seems to me that you are looking for Mutable Boolean

, the simplest of which is AtomicBoolean .



private void changeIt(AtomicBoolean b) {
    b.set(!b.get());
}

public void test() {
    AtomicBoolean b = new AtomicBoolean(false);
    changeIt(b);
    System.out.println(b);
}

      

0


source


The only way to make the change permanent is to give the method a return value and assign it to a variable:



public static boolean test(boolean b){
   return !b;
}

a = Test.test(a);

      

+2


source


Use a static field:

public static boolean flag;

public static void test(boolean b){
    flag = !b;
}

      

Then:

boolean a = true;
Test.test(a);

System.out.println( Test.flag); // false

      

0


source


in the class Test

you can define boolean variable as static

public static boolean a;

      

and outside of the change or access class with Test.a=false;

ora=Test.a

and if you need to use methods, you can hide the static method with inheritance:

public class HideStatic {     
public static void main(String...args){  
    BaseA base = new ChildB();  
    base.someMethod();        
}  
}  

class BaseA {         
    public static void someMethod(){  
        System.out.println("Parent method");  
    }  
}  

class ChildB extends BaseA{  
    public void someMethod(){  
        System.out.println("Child method");  
    }  
}

      

0


source


You can pass an instance to a method and use setters to change multiple variables at the same time.

public static void updateData(MyClass instance) {
    instance.setX(1);
    instance.setY(2);
}

      

0


source


I think you are asking to call the link . You can get this in Java using arrays:

public static void test(boolean[] b){
b[0] = !b[0];
}

boolean[] param = new boolean[] {a};
test(param);
a=param[0];
//a changed

      

It works, but it's ugly. If you need to return more than one value, look at the Pair or Tuple structures .

0


source







All Articles