Machine-translated by Google. Questions are authored in English.
Top

Discussion

What is the expected output of the following Java code?

public class operators {
  public static void main(String[] args)
  {
    int a = 5;
    int b = 7;
    System.out.println("a&b = " + (a & b));
  }
}

  • A.a&b = 5
  • B.a&b = 7
  • C.a&b = 35
  • D.a&b = 2

Answer: A

The output is a&b = 5. The string "a&b = " is printed as it is, and the expression (a & b) uses the bitwise AND operator on 5 and 7. \[ 5 = 0101_2,\quad 7 = 0111_2 \] \[ 0101_2 \;\&\; 0111_2 = 0101_2 = 5 \] A bit is 1 only where both operands have a 1. The value 7 would be the result of OR, 35 of multiplication, and 2 does not come from either. In Java, the operator & on integers is bitwise AND, and on booleans it is a logical AND, so 5 & 7 gives the number 5 here.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.