Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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){
  test = true;
}
foo2(Boolean test){
  if(test)
   //Doesn't go in here
}

I noticed that in foo2, the boolean test does not change and thereby doesn't go into the if statement. How would I go about changing it then? I looked into Boolean values but I couldn't find a function that would "set" test from true to false. If anyone could help me out that would be great.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
151 views
Welcome To Ask or Share your Answers For Others

1 Answer

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...