In Delphi I can do the following with a boolean variable:
If NOT bValue then
begin
//开发者_如何学编程do some stuff
end;
Does the equivalent in Java use the !?
If !(bValue) {
//do some stuff
}
You're close; the proper syntax is:
if (!bValue) {
//do some stuff
}
The entire conditional expression must be inside the parenthesis; the condition in this case involve the unary logical complement operator !
(JLS 15.15.6).
Additionally, Java also has the following logical binary operators:
- JLS 15.22.2 Boolean Logical Operators
&
,^
and|
- casually "and", "xor" and "or"
- JLS 15.23 Conditional-and
&&
and JLS 15.24 Conditional-or||
- the much more frequently used short-circuiting "and" and "or"
There are also compound assignment operators (JLS 15.26.2) &=
, |=
, ^=
.
Other relevant questions on stackoverflow:
- Shortcut "or-assignment" (|=) operator in Java
- Why doesn’t Java have compound assignment versions of the conditional-and and conditional-or operators? (&&=, ||=)
- What’s the difference between | and || in Java?
- Cleanest way to toggle a Boolean variable in Java?
- Getting confused in with == and = in “if” statement
- There are plenty of similar questions on stackoverflow due to accidental boolean assignment instead of comparison
- You never need to write
== true
and== false
- Omit explicit comparison with
true
andfalse
- use
!
when necessary
- Omit explicit comparison with
Yes, but inside the bracket:
if (!bValue) {
}
You'd normally not use any sort of data type prefix in Java as well, so it would more likely be something like:
if (!isGreen) { // or some other meaningful variable name
}
if (!bValue) {
// do some stuff
}
精彩评论