Is it possible in Java to use syntax like (i++
, ++i
) for boolean logic operators?
I have a boolean variable that is true only for the first iteration of a foreach
loop. That iteration has to be skipeed.
Full syntax is
for (...)
{
if (bool)
{
bool &= false;
continue;
}
}
I wonder if there is any way to shorten the syntax without using AtomicBoolean
. For example construct if (bool &= false)
is syntactically correct but I think it will compare the final result and not the original value.
Google is not my friend because the search query is misleading
A boolean variable in Java can be created using the boolean keyword. Unlike C++, a numerical value cannot be assigned to a boolean variable in Java – only true or false can be used. The strings “true” or “false” are displayed on the console when a boolean variable is printed.
Typically, you use == and != with primitives such as int and boolean, not with objects like String and Color. With objects, it is most common to use the equals() method to test if two objects represent the same value.
The compare() method of Boolean class is a built in method in Java which is used to compare two boolean values. It is a static method, so it can be called without creating any object of the Boolean class i.e. directly using the class name.
The Boolean logical operators are : | , & , ^ , ! , || , && , == , != . Java supplies a primitive data type called Boolean, instances of which can take the value true or false only, and have the default value false.
Personally I would simplify your current code to:
for (...)
{
if (bool)
{
bool = false;
continue;
}
// Rest of code
}
... but if you really want to do it in the if
condition as a side-effect, you could use:
for (...)
{
if (bool && !(bool = false))
{
continue;
}
// Rest of code
}
Here the first operand of the &&
operator covers subsequent operations, and !(bool = false)
will always evaluate to true
and set bool
to false.
Another option, from comments:
for (...)
{
if (bool | (bool = false))
{
continue;
}
// Rest of code
}
This performs the assignment on each iteration, but it still gives the right result each time.
I really, really wouldn't use either of these last two options though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With