开发者

What is the difference between & and &&? [duplicate]

开发者 https://www.devze.com 2023-04-12 14:30 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: & vs && and | vs ||
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

& vs && and | vs ||

What is the difference between & and &&?

I am getting same output for both & and &&.

Ex:

  1. &&:

    if (true && true){
        System.out.println("------if------");
    } else {
        System.out.println("------else------");
    }
    
  2. &:

    if (true & true){
        System.out.println("------if------");
    } else {
        Sy开发者_如何学Cstem.out.println("------else------");
    }
    

Output:

  1. ------if------
  2. ------if------

Can we use & and && operators in our code interchangeably?


&& short circuits the evaluation, while & always evaluates both operands.

This is a duplicate question. I'll try to dig out the link for you...

  • logical operators in java


& will force the evaluation of both the left and right operands whereas && is the short-circuit operator and doesn't check the right operand in obvious cases.

// this will evaluate both method calls even if the result
// of checkSomething() is false
boolean result = checkSomething() & checkSomethingExpensive()

// this will skip evaluation of checkSomethingExpensive() if the result of
// checkSomething() is false
boolean result = checkSomething() && checkSomethingExpensive()


  • & - bitwise AND
  • && - logical AND

You've true in both cases because in case of logical AND reason is obvious and in case of bitwise AND - true is interpreted as 1, so 1 & 1 alsays returns 1 which turns out into logical true


logical AND &&

Java operators

The bitwise & operator performs a bitwise AND operation.

Java operators2


Rule of thumb : use && when dealing with booleans, conditions, ifs, etc. I.e. most of the time. Use & in the rare cases when you need to perform bits operations.


  • &: operation, boolean true & true == true, integer 1001b & 1110b == 1000b
  • &&: comparison, boolean true & true == true, integer compiler error


That's because the following is evaluated:

I will write it in english semantic for you to understand.

For output 1: Logical AND &&

if true AND true IS TRUE.

For ouptut 2: Bitwise AND &

  • Let x = true (in other words, bit 1)
  • x = x AND true (in other words, x = 1 & 1) Bit is AND'ed
  • if (x IS TRUE) then print the if statement.


&& is a comparison while & is an operation!

0

精彩评论

暂无评论...
验证码 换一张
取 消