和 有什么区别?和&&在Java中?

发布于 2024-10-30 20:30:43 字数 291 浏览 8 评论 0原文

我一直认为Java中的&&运算符是用来验证它的两个布尔操作数是否为true的,而&运算符是用于对两个整数类型进行按位运算。

最近我发现 & 运算符也可以用来验证它的两个布尔操作数是否为 true,唯一的区别是它检查 RHS 操作数,即使 LHS 操作数也是如此操作数为假。

Java中的&运算符内部是否重载?或者这背后还有其他什么概念吗?

I always thought that && operator in Java is used for verifying whether both its boolean operands are true, and the & operator is used to do Bit-wise operations on two integer types.

Recently I came to know that & operator can also be used verify whether both its boolean operands are true, the only difference being that it checks the RHS operand even if the LHS operand is false.

Is the & operator in Java internally overloaded? Or is there some other concept behind this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

已下线请稍等 2024-11-06 20:30:44
boolean a, b;

Operation     Meaning                       Note
---------     -------                       ----
   a && b     logical AND                    short-circuiting
   a || b     logical OR                     short-circuiting
   a &  b     boolean logical AND            not short-circuiting
   a |  b     boolean logical OR             not short-circuiting
   a ^  b     boolean logical exclusive OR
  !a          logical NOT

short-circuiting        (x != 0) && (1/x > 1)   SAFE
not short-circuiting    (x != 0) &  (1/x > 1)   NOT SAFE
boolean a, b;

Operation     Meaning                       Note
---------     -------                       ----
   a && b     logical AND                    short-circuiting
   a || b     logical OR                     short-circuiting
   a &  b     boolean logical AND            not short-circuiting
   a |  b     boolean logical OR             not short-circuiting
   a ^  b     boolean logical exclusive OR
  !a          logical NOT

short-circuiting        (x != 0) && (1/x > 1)   SAFE
not short-circuiting    (x != 0) &  (1/x > 1)   NOT SAFE
落叶缤纷 2024-11-06 20:30:44

这取决于参数的类型...

对于整数参数,单个与号(“&”)是“按位 AND”运算符。除了两个布尔参数之外,没有为任何内容定义双与号(“&&”)。

对于布尔参数,单个 & 符号构成(无条件)“逻辑 AND”运算符,而双 & 符号(“&&”)是“条件逻辑 AND”运算符。也就是说,单 & 符号始终计算两个参数,而双 & 符号仅在第一个参数为 true 时计算第二个参数。

对于所有其他参数类型和组合,应该发生编译时错误。

It depends on the type of the arguments...

For integer arguments, the single ampersand ("&")is the "bit-wise AND" operator. The double ampersand ("&&") is not defined for anything but two boolean arguments.

For boolean arguments, the single ampersand constitutes the (unconditional) "logical AND" operator while the double ampersand ("&&") is the "conditional logical AND" operator. That is to say that the single ampersand always evaluates both arguments whereas the double ampersand will only evaluate the second argument if the first argument is true.

For all other argument types and combinations, a compile-time error should occur.

人间不值得 2024-11-06 20:30:44

&&是一个短路运算符,而 &是 AND 运算符。

试试这个。

    String s = null;
    boolean b = false & s.isEmpty(); // NullPointerException
    boolean sb = false && s.isEmpty(); // sb is false

&& is a short circuit operator whereas & is a AND operator.

Try this.

    String s = null;
    boolean b = false & s.isEmpty(); // NullPointerException
    boolean sb = false && s.isEmpty(); // sb is false
旧伤还要旧人安 2024-11-06 20:30:44

我想我的回答可以更容易理解:

&&&之间有两个区别。

如果它们用作逻辑AND

&&&可以是逻辑AND,当&&&左右表达式结果均为true,则整个运算结果可为true。

&&&作为逻辑AND时,有一个区别:

当使用&&时> 作为逻辑AND,如果左边的表达式结果为假,右边的表达式将不会执行。

举个例子:

String str = null;

if(str!=null && !str.equals("")){  // the right expression will not execute
        
}

如果使用 &

String str = null;

if(str!=null & !str.equals("")){  // the right expression will execute, and throw the NullPointerException 
        
}

另一个例子:

int x = 0;
int y = 2;
if(x==0 & ++y>2){
    System.out.print(“y=”+y);  // print is: y=3
}

int x = 0;
int y = 2;
if(x==0 && ++y>2){
    System.out.print(“y=”+y);  // print is: y=2
}

&可以用作位运算符

& 可以用作按位AND 运算符,&& 不能。

按位与“&”运算符产生 1 当且仅当两个位都在
它的操作数是 1。但是,如果两个位都是 0 或两个位都不同,则该运算符产生 0。更精确地说,按位 AND“&”如果两个位都为 1,则运算符返回 1;如果任何位为 0,则返回 0。

从维基页面:

http://www.roseindia.net /java/master-java/java-bitwise-and.shtml

I think my answer can be more understandable:

There are two differences between & and &&.

If they use as logical AND

& and && can be logical AND, when the & or && left and right expression result all is true, the whole operation result can be true.

when & and && as logical AND, there is a difference:

when use && as logical AND, if the left expression result is false, the right expression will not execute.

Take the example :

String str = null;

if(str!=null && !str.equals("")){  // the right expression will not execute
        
}

If using &:

String str = null;

if(str!=null & !str.equals("")){  // the right expression will execute, and throw the NullPointerException 
        
}

An other more example:

int x = 0;
int y = 2;
if(x==0 & ++y>2){
    System.out.print(“y=”+y);  // print is: y=3
}

int x = 0;
int y = 2;
if(x==0 && ++y>2){
    System.out.print(“y=”+y);  // print is: y=2
}

& can be used as bit operator

& can be used as Bitwise AND operator, && can not.

The bitwise AND " &" operator produces 1 if and only if both of the bits in
its operands are 1. However, if both of the bits are 0 or both of the bits are different then this operator produces 0. To be more precise bitwise AND " &" operator returns 1 if both of the two bits is 1 and it returns 0 if any of the bits is 0. 

From the wiki page:

http://www.roseindia.net/java/master-java/java-bitwise-and.shtml

骷髅 2024-11-06 20:30:44

它如 JLS ( 15.22.2)

当 a &、^ 或 | 的两个操作数时运算符的类型为 boolean 或 Boolean,则按位运算符表达式的类型为 boolean。在所有情况下,操作数都需要根据需要进行拆箱转换(第 5.1.8 节)。

对于 &,如果两个操作数都为 true,则结果值为 true;否则,结果为 false。

对于^来说,如果操作数的值不同,结果值为true;否则,结果为 false。

对于|,如果两个操作数的值都为假,则结果值为假;否则,结果为 true。

“技巧”在于 & 是一个整数位运算符以及一个布尔逻辑运算符。那么为什么不呢,将此视为运算符重载的示例是合理的。

it's as specified in the JLS (15.22.2):

When both operands of a &, ^, or | operator are of type boolean or Boolean, then the type of the bitwise operator expression is boolean. In all cases, the operands are subject to unboxing conversion (§5.1.8) as necessary.

For &, the result value is true if both operand values are true; otherwise, the result is false.

For ^, the result value is true if the operand values are different; otherwise, the result is false.

For |, the result value is false if both operand values are false; otherwise, the result is true.

The "trick" is that & is an Integer Bitwise Operator as well as an Boolean Logical Operator. So why not, seeing this as an example for operator overloading is reasonable.

病女 2024-11-06 20:30:44

'&&' : - 是逻辑 AND 运算符,根据其参数的逻辑关系生成布尔值 true 或 false。

例如: - Condition1 && Condition2

如果 Condition1 为 false,则 (Condition1 && Condition2) 将始终为 false,这就是该逻辑运算符也称为短路运算符的原因,因为它不计算另一个条件。如果 Condition1 为 false ,则无需评估 Condtiton2。

如果 Condition1 为 true,则计算 Condition2,如果为 true,则总体结果为 true,否则为 false。

'&' : - 是按位与运算符。如果两个输入位均为 1,则它会在输出中生成一 (1)。否则它会产生零 (0)。

例如:

-int a=12; // 12 的二进制表示为 1100

int b=6; // 6 的二进制表示为 0110

int c=(a & b); // (12 & 6) 的二进制表示为 0100

c 的值为 4。

作为参考,请参阅此 http://techno-terminal.blogspot.in/2015/11/difference- Between-operator-and-operator.html

‘&&’ : - is a Logical AND operator produce a boolean value of true or false based on the logical relationship of its arguments.

For example: - Condition1 && Condition2

If Condition1 is false, then (Condition1 && Condition2) will always be false, that is the reason why this logical operator is also known as Short Circuit Operator because it does not evaluate another condition. If Condition1 is false , then there is no need to evaluate Condtiton2.

If Condition1 is true, then Condition2 is evaluated, if it is true then overall result will be true else it will be false.

‘&’ : - is a Bitwise AND Operator. It produces a one (1) in the output if both the input bits are one. Otherwise it produces zero (0).

For example:-

int a=12; // binary representation of 12 is 1100

int b=6; // binary representation of 6 is 0110

int c=(a & b); // binary representation of (12 & 6) is 0100

The value of c is 4.

for reference , refer this http://techno-terminal.blogspot.in/2015/11/difference-between-operator-and-operator.html

思念绕指尖 2024-11-06 20:30:44

&&|| 称为短路运算符。使用它们时,对于 || - 如果第一个操作数的计算结果为 true,则不会计算其余操作数。对于 && - 如果第一个操作数的计算结果为 false,则其余操作数根本不会被计算。

因此,在本例中,如果 a 为 true,则 if (a || (++x > 0)) 变量 x 不会递增。

&& and || are called short circuit operators. When they are used, for || - if the first operand evaluates to true, then the rest of the operands are not evaluated. For && - if the first operand evaluates to false, the rest of them don't get evaluated at all.

so if (a || (++x > 0)) in this example the variable x won't get incremented if a was true.

著墨染雨君画夕 2024-11-06 20:30:44

对于布尔值,两者之间没有输出差异。您可以交换 &&和&或||和 |它永远不会改变你表达的结果。

差异在于处理信息的场景背后。当您将表达式“(a != 0) & ( b != 0)”右为 a= 0 且 b = 1 时,会发生以下情况:

left side: a != 0 --> false
right side: b 1= 0 --> true
left side and right side are both true? --> false
expression returns false

当您编写表达式 (a != 0) & & ( b != 0) 当 a= 0 且 b = 1 时,会发生以下情况:

a != 0 -->false
expression returns false

步骤更少,处理更少,编码更好,尤其是在执行许多布尔表达式或复杂参数时。

With booleans, there is no output difference between the two. You can swap && and & or || and | and it will never change the result of your expression.

The difference lies behind the scene where the information is being processed. When you right an expression "(a != 0) & ( b != 0)" for a= 0 and b = 1, The following happens:

left side: a != 0 --> false
right side: b 1= 0 --> true
left side and right side are both true? --> false
expression returns false

When you write an expression (a != 0) && ( b != 0) when a= 0 and b = 1, the following happens:

a != 0 -->false
expression returns false

Less steps, less processing, better coding, especially when doing many boolean expression or complicated arguments.

微凉徒眸意 2024-11-06 20:30:44

除了&&和 ||由于短路,混合两种形式时还要考虑运算符优先级。
我认为每个人都不会立即意识到 result1 和 result2 包含不同的值。

boolean a = true;
boolean b = false;
boolean c = false;

boolean result1 = a || b && c; //is true;  evaluated as a || (b && c)
boolean result2 = a  | b && c; //is false; evaluated as (a | b) && c

Besides && and || being short circuiting, also consider operator precedence when mixing the two forms.
I think it will not be immediately apparent to everybody that result1 and result2 contain different values.

boolean a = true;
boolean b = false;
boolean c = false;

boolean result1 = a || b && c; //is true;  evaluated as a || (b && c)
boolean result2 = a  | b && c; //is false; evaluated as (a | b) && c
唠甜嗑 2024-11-06 20:30:44

&是一个按位运算符 plus,用于检查两个条件,因为有时我们需要评估两个条件。
但是&&当第一个条件为真时,逻辑运算符转到第二个条件。

& is a bitwise operator plus used for checking both conditions because sometimes we need to evaluate both condition.
But && logical operator go to 2nd condition when first condition give true.

沙与沫 2024-11-06 20:30:44

所有答案都很好,而且似乎不需要更多答案需要
但我只是想指出有关 && 运算符的一些内容,称为 dependent condition

在使用运算符 && 的表达式中,一个条件 - 我们将其称为 < code>依赖条件——可能需要另一个条件为真,依赖条件的评估才有意义。

在这种情况下,依赖条件应放在 && 之后。操作员以防止错误。

考虑表达式 (i != 0) && (10 / i == 2)。依赖条件 (10 / i == 2) 必须出现在 && 运算符之后,以防止被零除的可能性。

另一个例子 (myObject != null) && (myObject.getValue() == somevaluse)

和另一件事: &&|| 被称为 短路评估,因为第二个参数仅在 第一个<时执行或评估/code> 参数不足以确定表达式

参考:Java™ 如何编程(早期对象),第十版

all answers are great, and it seems that no more answer is needed
but I just wonted to point out something about && operator called dependent condition

In expressions using operator &&, a condition—we’ll call this the dependent condition—may require another condition to be true for the evaluation of the dependent condition to be meaningful.

In this case, the dependent condition should be placed after the && operator to prevent errors.

Consider the expression (i != 0) && (10 / i == 2). The dependent condition (10 / i == 2) must appear after the && operator to prevent the possibility of division by zero.

another example (myObject != null) && (myObject.getValue() == somevaluse)

and another thing: && and || are called short-circuit evaluation because the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression

References: Java™ How To Program (Early Objects), Tenth Edition

℉絮湮 2024-11-06 20:30:44

对于AND和OR运算符,Java有两种评估类型,即短路评估和完全评估。

<代码>&& || 短路求值

短路求值使您能够不求值 AND 和 OR 表达式的右侧,当总体结果可以从左侧值预测。

int numberOne = 1;
int numberTwo = 2;
boolean result = false;

// left-side is false so the the overall result CAN be predicted without evaluating the right side.
// numberOne will be 1, numberTwo will be 2, result will be false
result = (numberOne > numberTwo) && (++numberOne == numberTwo);

System.out.println(numberOne); // prints 1
System.out.println(numberTwo); // prints 2
System.out.println(result);    // prints false


// left-side is true so the the overall result CAN NOT be predicted without evaluating the right side.
// numberOne will be 2, numberTwo will be 2, result will be true
result = (numberTwo > numberOne) && (++numberOne == numberTwo);

System.out.println(numberOne); // prints 2
System.out.println(numberTwo); // prints 2
System.out.println(result);    // prints true

<代码>& | ^ 全面评估

虽然在某些情况下可以预测结果,但有必要评估右侧。

int numberOne = 1;
int numberTwo = 2;
boolean result = false;

// left-side is false so the the overall result will be false BUT the right side MUST be evaluated too.
// numberOne will be 2, numberTwo will be 2, result will be false
result = (numberOne > numberTwo) & (++numberOne == numberTwo);

System.out.println(numberOne); // prints 2
System.out.println(numberTwo); // prints 2
System.out.println(result);    // prints false

注意:

  1. 请注意,对于 XOR (^) 来说,没有短路,因为始终需要双方来确定总体结果。
  2. 请注意,短路评估的其他可能名称是最小评估McCarthy评估
  3. 不重新开始在同一个表达式中混合布尔逻辑和动作
  4. & 还可以充当按位与运算符,非常学术,可以在密码学中使用。当两位都为 1 时,结果为 1,或者其中一位不为 1 时,结果为 0。(查看以下代码)

AND 按位示例:

byte a = 5;              // 00000101
byte b = 3;              // 00000011
byte c = (byte) (a & b); // 00000001 (c is 1)

In respect of the AND and OR operators, Java has got two types of evaluation namely Short-Circuit evaluation and full evaluation.

&& || Short-Circuit Evaluation

Short-Circuit evaluation enables you to not evaluate the right-hand side of AND and OR expressions, when the overall result can be predicted from the left-side value.

int numberOne = 1;
int numberTwo = 2;
boolean result = false;

// left-side is false so the the overall result CAN be predicted without evaluating the right side.
// numberOne will be 1, numberTwo will be 2, result will be false
result = (numberOne > numberTwo) && (++numberOne == numberTwo);

System.out.println(numberOne); // prints 1
System.out.println(numberTwo); // prints 2
System.out.println(result);    // prints false


// left-side is true so the the overall result CAN NOT be predicted without evaluating the right side.
// numberOne will be 2, numberTwo will be 2, result will be true
result = (numberTwo > numberOne) && (++numberOne == numberTwo);

System.out.println(numberOne); // prints 2
System.out.println(numberTwo); // prints 2
System.out.println(result);    // prints true

& | ^ Full Evaluation

Although in some cases it is possible to predict the result, It is necessary to evaluate the right-hand side.

int numberOne = 1;
int numberTwo = 2;
boolean result = false;

// left-side is false so the the overall result will be false BUT the right side MUST be evaluated too.
// numberOne will be 2, numberTwo will be 2, result will be false
result = (numberOne > numberTwo) & (++numberOne == numberTwo);

System.out.println(numberOne); // prints 2
System.out.println(numberTwo); // prints 2
System.out.println(result);    // prints false

Notice:

  1. Notice that for XOR (^) there is no short-circuit, because both sides are always required to determine the overall result.
  2. Notice that other possible names for Short-Circuit evaluation are minimal evaluation and McCarthy evaluation.
  3. It is not recommenced to mix boolean logic and actions in the same expression
  4. & can also act as a Bitwise AND operator which is very academic and can be used in cryptography. When both bits are 1, the result is 1, or either of the bits is not 1, the result is 0. (Check the following code)

AND Bitwise example:

byte a = 5;              // 00000101
byte b = 3;              // 00000011
byte c = (byte) (a & b); // 00000001 (c is 1)
昔日梦未散 2024-11-06 20:30:44

所有答案都很好地涵盖了几乎每个比较点。我只想添加一个例子。演示输出如何根据我们使用的运算符而变化。考虑下面的示例

int a = 10;
if(++a==10 & ++a==12) {
    ++a;
}
System.out.println(a); //12

在上面的代码中,我们使用按位 &操作员。因此,无论单个结果如何,它都会评估两个参数(左和右)。

因此,a 将在 if 条件 内增加 2 倍。但由于条件不会变为真,因此不会进入 if 循环内部,并且不会发生第三次增量。所以在这种情况下 a 的最终值将变为 12。

现在假设,在上面的同一示例中,如果我们使用短路 &&操作员。然后在将 ++a==10 评估为 false 后,它不会去检查第二个参数。因此,最终的值可能是 11。

int a = 10;
if(++a==10 && ++a==12) {
    ++a;
}
System.out.println(a); //11

基于此,我们可以说按位 & 的性能是 11。与短路 && 相比,运算符相对较低操作员。因为按位运算符将计算两个参数,而不管第一个参数的结果如何。而&&如果第一个参数的结果为 false,则运算符将停止计算第二个参数。

这两者之间的另一个区别是,Bitwise &运算符适用于布尔类型和整数类型。同时短路&&运算符仅适用于布尔类型。

我们可以这样写,

System.out.println(4 & 5); // 4

但是如果我们尝试这样写,

System.out.println(4 && 5);

那么它会给出一个错误,

二元运算符“&&”的操作数类型错误

Almost every point of comparison is very well covered in all the answers. I just want to add one example. To demonstrate how the output changes based on which operator we use. Consider the below example

int a = 10;
if(++a==10 & ++a==12) {
    ++a;
}
System.out.println(a); //12

In the above code, We are using bitwise & operator. So It will evaluate both the arguments(left and right) irrespective of the individual result.

so a will increment 2 times within if condition. But as the condition will not become true, It will not enter inside the if-loop and 3rd increment will not happen. So the final value of a would become 12 in this case.

Now suppose, in the same above example If we use short-circuit && operator. then after evaluating ++a==10 to false, It will not go to check the second argument. And Hence the final value of a would-be 11.

int a = 10;
if(++a==10 && ++a==12) {
    ++a;
}
System.out.println(a); //11

Based on this, We can say that performance of bitwise & operator is relatively low compare to the short-circuit && operator. As bitwise operator will go to evaluate both the arguments irrespective of the result of the first argument. While && operator will stop evaluating the second argument if the first argument's result is false.

One more difference between these two is, Bitwise & operator is applicable for boolean as well as integral types. While short-circuit && operator is applicable only for the boolean type.

We can write

System.out.println(4 & 5); // 4

But if We try to write like ,

System.out.println(4 && 5);

Then it will give an error saying,

bad operand types for binary operator '&&'

旧人哭 2024-11-06 20:30:43

& <-- 验证两个操作数
&& <-- 如果第一个操作数计算结果为 false,则停止计算,因为结果将为 false

(x != 0) & (1/x > 1) <-- 这意味着评估 (x != 0) 然后评估 (1/x > 1) then做&。问题是,对于 x=0 这将引发异常。

<代码>(x != 0) && (1/x > 1) <-- 这意味着评估 (x != 0) 并且只有当这是 true 时才评估 (1/x > 1 ) 因此,如果 x=0 那么这是完全安全的,如果 (x != 0) 计算结果为 false,则不会抛出任何异常,整个事情直接计算为 false,而不计算 (1/ x>1)。

编辑:

exprA | exprB <-- 这意味着先评估 exprA,然后评估 exprB,然后执行 |

exprA || exprB <-- 这意味着评估 exprA 并且只有当它为 false 时才评估 exprB 并执行 | |。

& <-- verifies both operands
&& <-- stops evaluating if the first operand evaluates to false since the result will be false

(x != 0) & (1/x > 1) <-- this means evaluate (x != 0) then evaluate (1/x > 1) then do the &. the problem is that for x=0 this will throw an exception.

(x != 0) && (1/x > 1) <-- this means evaluate (x != 0) and only if this is true then evaluate (1/x > 1) so if you have x=0 then this is perfectly safe and won't throw any exception if (x != 0) evaluates to false the whole thing directly evaluates to false without evaluating the (1/x > 1).

EDIT:

exprA | exprB <-- this means evaluate exprA then evaluate exprB then do the |.

exprA || exprB <-- this means evaluate exprA and only if this is false then evaluate exprB and do the ||.

梦中楼上月下 2024-11-06 20:30:43

除了不通过评估两个操作数来成为惰性评估器之外,我认为按位运算符的主要特征会比较操作数的每个字节,如下例所示:

int a = 4;
int b = 7;
System.out.println(a & b); // prints 4
//meaning in an 32 bit system
// 00000000 00000000 00000000 00000100
// 00000000 00000000 00000000 00000111
// ===================================
// 00000000 00000000 00000000 00000100

Besides not being a lazy evaluator by evaluating both operands, I think the main characteristics of bitwise operators compare each bytes of operands like in the following example:

int a = 4;
int b = 7;
System.out.println(a & b); // prints 4
//meaning in an 32 bit system
// 00000000 00000000 00000000 00000100
// 00000000 00000000 00000000 00000111
// ===================================
// 00000000 00000000 00000000 00000100
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文