0

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?

0

5 Answers 5

4

You are doing assignment, not comparison

if (b=true) 

You mean to use

if (b==true) 
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

0

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

Comments

0

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

Comments

-2

Try not (b=true) but (b==true).

2 Comments

b is a primitive, it has no toString() method
Java is not C# in other words :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.