Reputation: 71
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?
Upvotes: 0
Views: 757
Reputation: 6540
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:
Use boolean in if statement
if (b) {
}
Avoid this statament
if (b==true) {
}
Upvotes: 0
Reputation: 94
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));
}
}
Upvotes: 0
Reputation: 1467
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.
Upvotes: 3
Reputation: 3137
You are doing assignment, not comparison
if (b=true)
You mean to use
if (b==true)
Upvotes: 4