简体   繁体   中英

java - why does this code print the output it is supposed to print if a Boolean is true but the Boolean was declared to false?

I have the following code:

import java.util.*;
public class Test {
   public static void main(String[] args) {
   boolean b = false;
   if (b=true) 
      System.out.println("one. b = false");
   if (b)
      System.out.println("two. b = false");
   }
}

The output is:

one. b = false
two. b = false

I set b equal to false so why does it print the statement for when b is true?

You are doing assignment, not comparison

if (b=true)

You mean to use

if (b==true)

You need to use.

if (b) {
      System.out.println("one. b = true");
} else {
      System.out.println("two. b = false");
}

If you need to check equality then you need to use "==". But since you are using boolean you don't need to check equality instead you can use the value.

Please check below:

import java.util.*;
public class Test {
   public static void main(String[] args) {
       boolean b = false;
       if (b==true) 
          System.out.println("one. b = " + Boolean.toString(b));
       if (b)
          System.out.println("two. b = " + Boolean.toString(b));
   }
}

The problem is that in the if statement b=true you are not comparing. I meant you are not telling to java if b is equal to true , what you are really doing here is setting true to b. For that reason you can print two System.out.print statements. Because in both cases the value is true.

Take into account this:

  • Set value true to b: boolean b = true;
  • Use boolean in if statement

     if (b) { } 

Avoid this statament

if (b==true) {
}

不要尝试(b=true)而是(b==true)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM