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

6

In this method:

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

What does the ! operator mean in the if code:

if(!livro.aplicaDescontoDe(0.1)) {
    System.out.println("Desconto nao pode ser maior que 30%");
} else {
    System.out.println("Valor com desconto: " + livro.valor);
}
    
asked by anonymous 18.01.2016 / 20:42

3 answers

9

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

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

One way to read the question code is: "If no applies the discount of 0.1, then ...". (That's exactly how I read this kind of code)

It's the same thing to do:

if (livro.aplicaDescontoDe(0.1) == false)...
    
18.01.2016 / 20:49
2

The ! operator is for deny.

That is, if the line: livro.aplicaDescontoDe(0.1) returns true , when it precedes the ! operator, it 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
    }
}
    
18.01.2016 / 20:44
1

! This is a negation, ie it is denying (or reversing the result) method aplicaDescontoDe

    
18.01.2016 / 20:46