What is the usefulness of the ! operator in Java?

Asked

Viewed 236 times

7

In a if(!aplicaDescontoDe(valor)); in which the method aplicaDescontDe is a boolean, how it works not understood?

In that 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 the !(exclamation) in if ?

  • The operator ! functions as a negation, i.e., if it returns 1, the function will be denied and passed as 0, if it returns 0 will be denied and passed as 1.

  • @Marcelobonifazio, cannot use the operator ! (not) in integer values, when you say 1 and 0 you mean true (1) and false (0)?

  • 1

    @Fernando was an unfortunate example rs, what I meant was: if(!funcao()) if the function return is 1 or true, it will be denied, and vice versa, if the return by chance is a int, ai gives a exception(believe)

  • 1

    @Marcelobonifazio, I suspected, I only quoted because beginners can see this and get confused, and in case you try to make a denial in a whole: if(!1), for example, it will generate a build error and not run error, as can be seen here.

1 answer

16


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

bool x = !true;

is the same as

bool x = false;

Obviously just put so to illustrate, it makes no sense to use it with the literal, only in variables or expressions that result in boolean, as you used.

It can be used anywhere that accepts an expression and the unary operand is a boolean and the result must also be a boolean. It doesn’t have to be just one if.

Your example if(!aplicaDescontoDe(valor)) can be read as follows: "if no value discount applies".

In the example posted later it would be possible to do without the operator, just reverse the blocks, so:

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 curiosity, it’s taste, but I would do different:

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

I put in the Github for future reference.

Wikipedia article.

  • 1

    now I’m senior java.

  • 1

    Eeeeee no! kkk

  • 1

    Everything ! lie what he said.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.