This discussion is archived
2 Replies Latest reply: Oct 29, 2012 8:48 AM by rp0428 RSS

Java code statement help

970974 Newbie
Currently Being Moderated
What does:

<<~

mean in Java?
  • 1. Re: Java code statement help
    EJP Guru
    Currently Being Moderated
    Nothing by itself, but
    a = b << ~c;
    would mean 'b shifted left the complement of c'.
  • 2. Re: Java code statement help
    rp0428 Guru
    Currently Being Moderated
    Welcome to the forum!
    >
    byte b = (byte) 0x55; //01010101;
    byte c = (byte) ~b;
    >
    Time for you to download The Java Language Specification and start your way through it. You should also take time to review The Java Tutorials - Start with the 'Getting Started' link on this page
    http://docs.oracle.com/javase/tutorial/

    The '<<' is the left shift operator

    See section 15.19 Shift Operators in the Java Language Specification
    http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.19
    >
    15.19. Shift Operators
    The operators << (left shift), >> (signed right shift), and >>> (unsigned right shift) are called the shift operators. The left-hand operand of a shift operator is the value to be shifted; the right-hand operand specifies the shift distance.
    . . .
    >
    So 'm << 3' shifts the value in m three binary places to the left. The original leftmost three bits are lost and the rightmost three bits become zero.

    The '~' is the Bitwise Complement Operator. See Section 15.15.5 of the same doc
    http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.15.5
    >
    15.15.5. Bitwise Complement Operator ~
    The type of the operand expression of the unary ~ operator must be a type that is convertible (§5.1.8) to a primitive integral type, or a compile-time error occurs.

    Unary numeric promotion (§5.6.1) is performed on the operand. The type of the unary bitwise complement expression is the promoted type of the operand.

    At run-time, the value of the unary bitwise complement expression is the bitwise complement of the promoted value of the operand. In all cases, ~x equals (-x)-1.
    >
    So if byte b = 01010101 then ~b = 10101010; every bit is complemented - a one bit becomes a zero bit and a zero bit becomes a one bit.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points