How to interpret operators in Java

1

Today reviewing some things of the operators I have found something like this:

public class Pruebas {
  public static void main(String[] args) {
    boolean a=false;
    boolean b=false;
    boolean c=true;

    System.out.println(!a|b&&(c||b)&&c?(a?1:2):3);
  }
}

Running it throws 2

Well, I'd like to know a bit how to interpret the following line, in what order I should do it to understand why that throws 2 . If possible, tell me step by step.

!a|b&&(c||b)&&c?(a?1:2):3
    
asked by NeoChiri 07.06.2016 в 20:07
source

2 answers

3

You have to divide that line into parts:

  • Part 1: !a|b&&(c||b)&&c
  • Part 2: (?a?1:2):3

Analysis of Part 1:

First the operators with precedence are executed, which in this case is the negation! The expression can be written like this:

(!a) | b && (c||b) && c

Now, you have to directly evaluate the expression. For this, it is convenient to replace the Boolean values with the variables, so you have the following:

(!false) | false && (true || false) && true

We solve the elements in parentheses first, and you get:

true | false && true && true

We execute the operators one by one. The result of true | false is false :

true && true && true

When only operators && remain, the result of this expression will be true .

Part 2 Analysis:

Once we have the result of part 1, it is easier to evaluate part 2. We replace the variables by their values:

true ? (false ? 1 : 2) : 3

The ternary operator ? is like a if , so the code could be understood like this:

if (true) {
    if (false) {
        return 1;
    } else {
        return 2;
    }
} else {
    return 3;
}

By following the execution of this code, you can see that the result is 2.

    
answered by 07.06.2016 / 21:33
source
1

First let's review the definition of the operators:

! Logical denial. It is used to invert the logical state of your operand.

editing ... ()

We also have a ternary Operator ? : , also known as a conditional operator.

Ternary operator has three operands and is commonly used to evaluate boolean expressions. The objective of this operator is to decide what value is assigned to the variable. Example:

variable a = (expresión a evaluar) ? valor si es verdadero. : valor si es falso.

Having as initial values,

boolean a = false;
boolean b = false;
boolean c = true;

We will carry out the evaluation by parts

!a|b => true
c||b => true
a?1:2 => 2

Reducing the original sentence !a|b&&(c||b)&&c?(a?1:2):3 we have:

  true&&true&&c?(2):3

therefore evaluating true&&true&&c we have:

true&&true&&true

That when we evaluate this expression we have

true&&true&&true => true

In the end we only have the ternary operation true?(2):3 that results in:

true?(2):3 => 2
    
answered by 07.06.2016 в 21:59