1. Introduction
1.绪论
In Java’s if-else statements we can take a certain action when an expression is true, and an alternative when it is false. In this tutorial, we’ll learn about how to reverse the logic using the not operator.
在 Java 的 if-else 语句中,当表达式为true时,我们可以采取某种行动,而当表达式为false时,则采取另一种行动。在本教程中,我们将学习如何使用not操作符来逆转逻辑。
2. The if-else Statement
2.if-else S语句
Let’s start with a simple if-else statement:
让我们从一个简单的if-else语句开始。
boolean isValid = true;
if (isValid) {
System.out.println("Valid");
} else {
System.out.println("Invalid");
}
What if our program only needs to handle the negative case? How would we re-write the above example?
如果我们的程序只需要处理负数情况呢?我们将如何重写上面的例子?
One option is to simply remove the code in the if block:
一种选择是简单地删除if块中的代码。
boolean isValid = true;
if (isValid) {
} else {
System.out.println("Invalid");
}
However, an empty if block looks like it might be incomplete code, and seems a long-winded way of handling only the negative condition. We might instead try testing if our logical expression evaluates to false:
然而,一个空的if块看起来可能是不完整的代码,而且似乎是一种只处理负面条件的啰嗦方式。我们可以尝试测试我们的逻辑表达式是否评估为false。
boolean isValid = true;
if (isValid == false) {
System.out.println("Invalid");
}
The above version is relatively easy to read, though it might be harder to do if the logical expression were more complex. Java has an alternative for us, though, in the form of the not operator:
上面的版本相对容易阅读,尽管如果逻辑表达式更复杂的话,可能更难做到。不过,Java为我们提供了一个替代方案,即not操作符的形式。
boolean isValid = true;
if (!isValid) {
System.out.println("Invalid");
}
3. The not Operator
3.not操作符
The not operator is a logical operator, represented in Java by the ! symbol. It’s a unary operator that takes a boolean value as its operand. The not operator works by inverting (or negating) the value of its operand.
not操作符是一个逻辑操作符,在Java中用!符号表示。它是一个单数运算符,以一个布尔值作为操作数。not操作符的作用是反转(或否定)其操作数的值。
3.1. Applying the not Operator to a Boolean Value
3.1.将not操作符应用于布尔值
When applied to a boolean value, the not operator turns true to false and false to true.
当应用于布尔值时,not操作符将true变成false,false变成true。
For example:
比如说。
System.out.println(!true); // prints false
System.out.println(!false); // prints true
System.out.println(!!false); // prints false
3.2. Applying the not Operator to a Boolean Expression
3.2.将not操作符应用于布尔表达式
Since not is a unary operator, when you want to not the outcome of an expression, you need to surround that expression in parenthesis to get the right answer. The expression in the parenthesis is evaluated first and then the not operator inverts its outcome.
由于not是一个单数运算符,当你想not一个表达式的结果时,你需要用小括号包围该表达式以获得正确的答案。小括号中的表达式首先被评估,然后not运算符将其结果倒置。
For example:
比如说。
int count = 2;
System.out.println(!(count > 2)); // prints true
System.out.println(!(count <= 2)); // prints false
boolean x = true;
boolean y = false;
System.out.println(!(x && y)); // prints true
System.out.println(!(x || y)); // prints false
We should note that when negating an expression, De Morgan’s laws come into play. In other words, each term in the expression is negated and the operator is reversed. This can help us to simplify harder to read expressions.
我们应该注意,在否定一个表达式时,De Morgan定律会发挥作用。换句话说,表达式中的每一个词都被否定了,而且运算符被颠倒过来。这可以帮助我们简化难以阅读的表达式。
For example:
比如说。
!(x && y) is same as !x || !y
!(x || y) is same as !x && !y
!(a < 3 && b == 10) is same as a >= 3 || b != 10
4. Some Common Pitfalls
4.一些常见的陷阱
Using the not operator can sometimes compromise the readability of our code. Negatives can be harder to understand than positives. Let’s look at some examples.
使用not操作符有时会影响到我们代码的可读性。负数可能比正数更难理解。让我们看看一些例子。
4.1. Double Negatives
4.1.双重底片
Because the not operator is a negation operator, using it with variables or functions that have a negative name, can result in hard to read code. This is similar to natural languages, where double negatives are often considered hard to understand.
因为not操作符是一个否定操作符,将其用于具有否定名称的变量或函数,会导致代码难以阅读。这与自然语言类似,在自然语言中,双重否定词通常被认为是难以理解的。
For example:
比如说。
if (product.isActive()) {...}
reads better than
读起来比
if (!product.isNotActive()) {...}
While our API may not provide an isActive method, we can create one to aid readability.
虽然我们的API可能没有提供一个isActive方法,但我们可以创建一个方法来帮助阅读。
4.2. Complex Conditions
4.2.复杂条件
The not operator can sometimes make an already complex expression even more difficult to read and understand. When this happens, we can simplify the code by reversing the condition or by extracting methods. Let’s look at some examples of conditions made complex by the not operator and how we can simplify them by reversing the condition:
not操作符有时会使已经很复杂的表达式更加难以阅读和理解。当这种情况发生时,我们可以通过反转条件或提取方法来简化代码。让我们看看一些被not操作符弄得复杂的条件的例子,以及我们如何通过反转条件来简化它们。
if (!true) // Complex
if (false) // Simplified
if (!myDate.onOrAfter(anotherDate)) // Complex
if (myDate.before(anotherDate)) // Simplified
if (!(a >= b)) // Complex
if (a < b) // Simplified
if (!(count >= 10 || total >= 1000)) // Complex
if (count < 10 && total < 1000) // Simplified
5. Conclusion
5.总结
In this article, we discussed the not operator and how it can be used with boolean values, expressions and in if-else statements.
在这篇文章中,我们讨论了not操作符以及如何将其用于布尔值、表达式和if-else语句中。
We also looked at some common pitfalls, caused by writing expressions in their inverse and how to fix them.
我们还研究了一些常见的陷阱,这些陷阱是由表达式的逆向书写造成的,以及如何解决这些问题。
As always the source code for the examples used in this article is available over on GitHub.
像往常一样,本文所使用的例子的源代码是在GitHub上提供的。