DEV Community

bosiarquitetura
bosiarquitetura

Posted on

Basic Java logical operators

Coming from a philosophical background, one of the main parts of a language that I'm always curious is how they implement logical operators. Java doesn't do anything new on the logic field, but give us some powerful basic logic calculators.

The basic logical operators on Java are & (and), | (inclusive or), and ^ (exclusive or). The & operator does the classical test to see if both sides of the calculation are true, while the inclusive or (|) test if any of both sides are true, and the exclusive or (^) tests if only one side of the operation is true. The table bellow show the possible outputs for each different value:

Screen Shot 2020-10-21 at 22.58.46

However, there are some other calculators that enhances the power of the basic & and the |. If you add another of the same character to both operators, getting && and ||, the JVM will consider the full operation a conditional calculation, where it'll only calculate the second part of the operation if it can't assume the full boolean value using only the first part of the operation.

This type of operator can give you more control over calculations like: boolean y = (x >= 7) || (++x <= 9); where, if x is bigger or equal to 7, the second part of the operation isn't computed. However, if x isn't bigger or equal to 7, it'll get incremented, changing its value. With this, we can create complex logical structures.

On the example that I gave, a simple inclusive "or" gives a shape for an "if and only if structure" too. To fully understand it, we can't only read it as "x is bigger or equal to or x plus one is less than or equal to 9)" but also as "X will be incremented if and only if X isn't bigger or equal to 7". This can create a complex code that is difficult to read (as any Clean Code guide would say to you), but it also demonstrate how powerful a programming language like java can be and how it mimics the logical propositions.

Top comments (0)