Java Challenge #5: Logical and Bitwise Operators

Have you mastered logical operators?

Try to sum these numbers before seeing the answer below.

logical_operators.PNG

Answer: There are some important concepts here. The first concept is the bitwise operators. They will be checked wherever the result is true or false. For example, when we use logical operators like:

/* The second condition won't be executed,
because it's not necessary, once you are
using '&&', both conditions must be 'true'
when one of them is false, JVM just ignores the rest. */
if (false && true) {

}

When we use bitwise operators:

/* The second condition will be checked,
even if the first condition is false,
 this can be useful when you want to
execute a command in every situation on your conditions. */
if (false & true) {

}

When we use the command “||” the same rule is applied here. See the example:

/* The second condition won't be
executed because once we are using "||",
if one of the conditions is 'true' the
whole condition will be true, so JVM won't
check the next condition. */
if (true || false) {

}

/* When using the bitwise operator,
both conditions will be check,
even if the first condition is 'true' */
if (true | false) {

}

We must know the incremental operator. When you use it before the variable it will increment in the line you used it. When you use the post-incremental operator it will increment the next time you use the variable. For example:

/* In the first condition, the variable
'i' will be 5 and on the other will be 6,
so both conditions will be true */
int i = 5;
if (i++ == 5 || i++ == 6) {}

/* In the first condition the variable
will be 6 and in the next will be 7,
so both conditions will be false */
int i = 5;
if (++i == 5 && ++i == 6) {}

Knowing all these concepts, now I can give the answer, it is 74! Try this challenge, debug it, and see the concepts in a practical way. This is how you master a programming language!

Written by
Rafael del Nero
Join the discussion