“||”在Java中是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24919880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does " || " mean in Java?
提问by Alan Hirales
When studying my Java courses, these two signs ||
appeared but I still can't find their function or meaning. Can someone clear this up for me?
在学习Java课程时,||
出现了这两个标志,但我仍然找不到它们的功能或含义。有人可以帮我解决这个问题吗?
回答by Keppil
回答by jhobbie
It is the boolean operator or. That means it will take two terms and compare them, and if either one or both are true, it will return true. However, if neither are true, it will return false. Example:
它是布尔运算符或。这意味着它将采用两个术语并将它们进行比较,如果其中一个或两个为真,它将返回真。但是,如果两者都不为真,它将返回假。例子:
return (true || false);
will return true.
将返回真。
回答by Jo?o
It means Logical-ORor simply OR--- A or B
这意味着逻辑或或简单地或--- A 或 B
A || B
A B A||B
T F T
T T T
F T T
F F F
T = true
F = false
If A is true, it doesn't evaluate B. A || B in this case it is automatically true.
如果 A 为真,则不评估 B。 A || B 在这种情况下,它自动为真。
回答by Vishwas
It is a logical operator used in java.It is usually known as OR operator. for example `
它是java中使用的逻辑运算符,通常称为OR运算符。例如`
if(a==1 || b==1) System.out.println("Something");
if(a==1 || b==1) System.out.println("Something");
` if the value of variable 'a' is 1 or value of variable 'b' is 1 it will print "Something".If one of the value is true it will print Something.If both the values are false it will not print anything.
` 如果变量 'a' 的值为 1 或变量 'b' 的值为 1 它将打印“Something”。如果其中一个值为真,它将打印Something。如果两个值都为假,则不会打印任何内容.
回答by ajb
It means OR, but with the additional feature that if the left operand is TRUE, it doesn't try to figure out the right one. This is called a short-circuiting operation(or sometimes a McCarthy operation). This is very important, because there are times when trying to evaluate the right operand will throw an exception. If s
is a String
:
这意味着 OR,但具有附加功能,即如果左操作数为 TRUE,则不会尝试找出正确的操作数。这称为短路操作(或有时称为麦卡锡操作)。这非常重要,因为有时尝试评估正确的操作数会引发异常。如果s
是String
:
if (s.length() == 0 || s.charAt(0) == ' ')
If s
is ""
and thus has length 0, s.charAt(0)
will throw an exception and abort your program if it isn't caught. But since ||
is short-circuiting, the left side will be true
if s
is ""
, and therefore it will never try to compute s.charAt(0)
.
如果s
是""
,因此长度为 0,s.charAt(0)
将抛出异常并中止您的程序,如果它没有被捕获。但由于||
是短路,左侧将是true
if s
is ""
,因此它永远不会尝试计算s.charAt(0)
。
回答by Aniket Thakur
||
is a logical OR operator in Java. In addition to above answers one important point to keep in mind for using ||
is short circuit evaluation.
||
是 Java 中的逻辑 OR 运算符。除了上述答案之外,使用时要记住的一个重要点||
是短路评估。
So if you have expression1 || expression2
expression2 will not be evaluated if expression1 is evaluated to be true.
所以如果你有expression1 || expression2
expression2 将不会被评估,如果 expression1 被评估为真。