Change boolean Values?

后端 未结 5 1747
礼貌的吻别
礼貌的吻别 2020-12-11 16:40

I have a question about boolean values in Java. Let\'s say I have a program like this:

boolean test = false;
...
foo(test)
foo2(test)

foo(Boolean test){
  t         


        
5条回答
  •  伪装坚强ぢ
    2020-12-11 16:55

    You're passing the value of a primitive boolean to your function, there is no "reference". So you're only shadowing the value within your foo method. Instead, you might want to use one of the following -

    A Holder

    public static class BooleanHolder {
      public Boolean value;
    }
    
    private static void foo(BooleanHolder test) {
      test.value = true;
    }
    
    private static void foo2(BooleanHolder test) {
      if (test.value)
        System.out.println("In test");
      else
        System.out.println("in else");
    }
    
    public static void main(String[] args) {
      BooleanHolder test = new BooleanHolder();
      test.value = false;
      foo(test);
      foo2(test);
    }
    

    Which outputs "In test".

    Or, by using a

    member variable

    private boolean value = false;
    
    public void foo() {
      this.value = true;
    }
    
    public void foo2() {
      if (this.value)
        System.out.println("In test");
      else
        System.out.println("in else");
    }
    
    public static void main(String[] args) {
      BooleanQuestion b = new BooleanQuestion();
      b.foo();
      b.foo2();
    }
    

    Which, also outputs "In test".

提交回复
热议问题