Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operation to "Get and AND" boolean variable in Java

Tags:

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

like image 884
usr-local-ΕΨΗΕΛΩΝ Avatar asked Jul 20 '15 10:07

usr-local-ΕΨΗΕΛΩΝ


People also ask

How do you boolean a variable in Java?

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.

Can you use == for boolean in Java?

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.

Can you compare two boolean values in Java?

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.

Which Java operators can be used with boolean variables?

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.


1 Answers

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.

like image 73
Jon Skeet Avatar answered Oct 21 '22 05:10

Jon Skeet