What is the function of the operator "!" (exclamation)?

Asked

Viewed 4,966 times

6

In this method:

public boolean aplicaDescontoDe(double porcentagem) {
    if(porcentagem > 0.3) {
        return false;
    } else {
        this.valor -= valor * porcentagem;
        return true;
    }
}

What the operator means ! there in the code if:

if(!livro.aplicaDescontoDe(0.1)) {
    System.out.println("Desconto nao pode ser maior que 30%");
} else {
    System.out.println("Valor com desconto: " + livro.valor);
}
  • It is a negation, ie is denying (or reversing the result) the result of the method aplicaDescontoDe

  • In this MSDN link there is a complete explanation, with examples: Negation Operator - MSDN

  • I have a small impression that this question is duplicated.

  • deusculpa did not know.

  • 1

    @user38537 no need to apologize, even if it is duplicate is good for the site. More chance of someone finding the answers, because they are linked. Suddenly someone searches the Internet and finds his first.

  • @Wallacemaxters he didn’t say it wasn’t to close.

Show 1 more comment

3 answers

9


In Java, the operator ! is an unary operator used to invert the value of a boolean expression. Thus, if a Boolean expression is evaluated for True, the operator !, if applied to it, it will invert the value to False.

In the question example, it will invert the value returned by the function aplicaDescontoDe. If the function returns True, then the operator ! will invert the value to False.

One way to read the code of the question is: "If nay The discount of 0.1, then ...". (This is exactly how I read this type of code)

It’s the same as doing:

if (livro.aplicaDescontoDe(0.1) == false)...

2

The operator ! serves to deny.

That is, if the line: livro.aplicaDescontoDe(0.1)return true, prior to the operator ! he becomes falsa and vice versa.

public class HelloWorld{
    public static void main(String []args){
        boolean verdade = true;

        System.out.println(verdade); // imprime true
        System.out.println(!verdade); // imprime false
    }
}

1

! It is a negation, that is, it is denying (or reversing the result) of the method aplicaDescontoDe

Browser other questions tagged

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