How useful the operator! in Java?

6

In if(!aplicaDescontoDe(valor)); in which the aplicaDescontDe method is a boolean, how does it work I did not understand?

In this Example:

public boolean aplicaDescontoDe(double porcentagem) {
        if(porcentagem >0.3) { //se desconto for maior que 30%
            return false;
        }
        this.valor -= this.valor * porcentagem;
        return true;
    }

...

if(!livro.aplicaDescontoDe(0.3)) {
          System.out.println("Desconto no livro nao pode ser maior que 30%");
      } else {
          System.out.println("Valor no livro com desconto: " + livro.getValor());
      }

Why do I need ! (exclamation) in if ?

    
asked by anonymous 01.08.2015 / 00:39

1 answer

15

It is the logical negation operator (known as not ) and it only applies even to boolean data. That is, if it receives a true it turns into false and vice versa. Then:

bool x = !true;

is the same as

bool x = false;

Obviously I just put it like this to illustrate, it does not make sense to use it with the literal, only in variables or expressions that result in Boolean, as you used it.

It can be used anywhere that accepts an expression and operating unary is a Boolean and the result must also be a Boolean. It does not have to be just a if .

Your example if(!aplicaDescontoDe(valor)) can be read like this: "if value discount does not apply".

In the example posted later it would be possible to do without the operator, it would be enough to invert the blocks, like this:

if(livro.aplicaDescontoDe(0.3)) {
    System.out.println("Valor no livro com desconto: " + livro.getValor());
} else {
    System.out.println("Desconto no livro nao pode ser maior que 30%");
}

The result would be the same. As a curiosity, it's like, but I'd do it differently:

System.out.println(livro.aplicaDescontoDe(0.3) ? 
          "Valor no livro com desconto: " + livro.getValor() :
          "Desconto no livro nao pode ser maior que 30%");

Wikipedia article .

    
01.08.2015 / 00:46