Home > Articles

  • Print
  • + Share This
This chapter is from the book

Bitwise and Logical Operators

Table 3.4 summarizes the operators that can be used on individual bits in integer primitives and in logical expressions. Bitwise operators are used in expressions with integer values and apply an operation separately to each bit in an integer. The term logical expression refers to an expression in which all of the operands can be reduced to boolean primitives. Logical operators produce a boolean primitive result.

Table 3.4 Bitwise and Logical Operators

Precedence

Operator

Operator Type

Description

1

~

Integral

Unary bitwise complement

1

!

Logical

Unary logical complement

4

<<

Integral

Left shift

4

>>

Integral

Right shift (keep sign)

4

>>>

Integral

Right shift (zero fill)

5

instanceof

Object, type

Tests class membership

6

==

Object

Equals (same object)

6

!=

Object

Unequal (different object)

7

&

Integral

Bitwise AND

7

&

Logical

Logical AND

8

^

Integral

Bitwise XOR

8

^

Logical

Logical XOR

9

|

Integral

Bitwise OR

9

|

Logical

Logical OR

10

&&

Logical

Logical AND (conditional)

11

||

Logical

Logical OR (conditional)

12

?:

Logical

Conditional (ternary)

13

=

Variable, any

Assignment

13

<<=

Binary

Left shift with assignment

13

>>=

Binary

Right shift with assignment

13

>>>=

Binary

Right shift, zero fill, assignment

13

&=

Binary

Bitwise AND with assignment

13

&=

Logical

Logical AND with assignment

13

|=

Binary

Bitwise OR with assignment

13

|=

Logical

Logical OR with assignment

13

^=

Binary

Bitwise XOR with assignment

13

^=

Logical

Logical XOR with assignment


Bitwise Operations with Integers

Bitwise operators change the individual bits of an integer primitive according to the familiar rules for AND, OR, and XOR (Exclusive OR) operations (as summarized in Table 3.5). The operands of the &, |, and ^ operators are promoted to int or long types, as discussed earlier under "Widening Conversions," and the result is an int or long primitive, not a boolean. Because each bit in an integer primitive can be modified and examined independently with these operators, they are frequently used to pack a lot of information into a small space.

Table 3.5 Bitwise Logic Rules

Operand

Operator

Operand

Result

1

& (AND)

1

1

1

& (AND)

0

0

0

& (AND)

1

0

0

& (AND)

0

0

1

| (OR)

1

1

1

| (OR)

0

1

0

| (OR)

1

1

0

| (OR)

0

0

1

^ (XOR)

1

0

1

^ (XOR)

0

1

0

^ (XOR)

1

1

0

^ (XOR)

0

0


In thinking about the action of bitwise operators, you may want to draw out the bit pattern for various values. To keep them straight, it helps to draw groups of four bits so the groups correspond to hexadecimal digits. Questions on the test will not require you to remember all of the powers of two, but being able to recognize the first few helps. Here is an example of the use of the & or AND operator:

short flags = 20 ; // 0000 0000 0001 0100 or 0x0014
short mask = 4 ; // 0000 0000 0000 0100 
short rslt = (short)( flags & mask ) ; 

Note that because operands are promoted to int or long, the cast to short is necessary to assign the value to a short primitive variable rslt. Applying the rule for the AND operator, you can see that the bit pattern in rslt will be "0000 0000 0000 0100", or a value of 4. C programmers who are used to checking the result of a bitwise operation in an if statement, such as line 1 in the following code, should remember that Java can use boolean values in logic statements only, as shown in line 2:

1. if( rslt ) doSomething() ; // ok in C, wrong in Java
2. if( rslt != 0 ) doSomething() ; // this is ok in both

Practicing Bitwise Operations

Unless you are very familiar with bitwise operations and binary representation of integers, we think you should get in some practice. Listing 3.1 shows a simple practice program. Type it in, compile it, and run it with some example numbers. This is important; do it now!

Listing 3.1 A Program to Experiment with Bitwise Operators

public class BitwiseTest {
 public static void main(String[] args){
  if( args.length < 2 ){
   System.out.println("expects two numbers");
   System.exit(1);
  }
  int a = Integer.parseInt( args[0] );
  int b = Integer.parseInt( args[1] );
  System.out.println( "a as binary " +
         Integer.toBinaryString( a ));
  System.out.println( "b as binary " + 
         Integer.toBinaryString( b ));
  System.out.println( "NOT a " + 
         Integer.toBinaryString( ~a ));
  System.out.println( "NOT b " + 
         Integer.toBinaryString( ~b ));
  System.out.println( "a AND b " + 
         Integer.toBinaryString( a & b ));
  System.out.println( "a OR b " + 
         Integer.toBinaryString( a | b ));
  System.out.println( "a XOR b " + 
         Integer.toBinaryString( a ^ b ));
 }
}

Wasn't that fun? As a variation on the program in Listing 3.1, you might try using the toHexString and toOctalString methods in the Integer class to show what base 10 numbers look like in hexidecimal (base 16) and octal (base 8) formats.

Table 3.6 shows the result of applying the various bitwise operators to the sample operands op1 and op2. Note that in the last line of the table, the ~, or complement, operator sets the highest order bit, which causes the integer to be interpreted as a negative number. We are using short primitives here to simplify the table, but the same principles apply to all of the integer primitives.

Table 3.6 Illustrating Bitwise Operations on Some Short Primitives (16-bit Integers)

Binary

Operation

Decimal

Hex

0000 0000 0101 0100

op1

84

0x0054

0000 0001 0100 0111

op2

327

0x0147

0000 0000 0100 0100

op1 & op2

68

0x0044

0000 0001 0101 0111

op1 | op2

343

0x0157

0000 0001 0001 0011

op1 ^ op2

275

0x0113

1111 1110 1011 1000

~op2

-238

0xFEB8


The Unary Complement Operators

The ~ operator takes an integer type primitive. If smaller than int, the primitive value will be converted to an int. The result simply switches the sense of every bit. The ! operator is used with boolean primitives and changes false to true or true to false.

The Shift Operators: <<, >>, and >>>

The shift operators work with integer primitives only; they shift the left operand by the number of bits specified by the right operand. The important point to note with these operators is the value of the new bit that is shifted into the number. For << (left shift), the new bit that appears in the low order position is always zero.

Sun had to define two types of right shift because the high order bit in integer primitives indicates the sign. The >> right shift propagates the existing sign bit, which means a negative number will still be negative after being shifted. The >>> right shift inserts a zero as the most significant bit. Table 3.7 should help you visualize what is going on. Again, if you are not comfortable with these bit manipulations, stop and write some test programs. You can modify the program from Listing 3.1 to include expressions such as a << b.

CAUTION

There is a good chance you will get at least one question that involves shift operators. Be sure you have mastered them.

Table 3.7 The Results of Some Bit-Shifting Operations on Sample 32-bit Integers

Bit Pattern

Operation

Decimal Equivalent

0000 0000 0000 0000 0000 0000 0110 0011

starting x bits

99

0000 0000 0000 0000 0000 0011 0001 1000

after x << 3

792

0000 0000 0000 0000 0000 0000 0001 1000

after x >> 2

24

1111 1111 1111 1111 1111 1111 1001 1101

starting y bits

-99

1111 1111 1111 1111 1111 1111 1111 1001

after y >> 4

-7

0000 0000 0000 1111 1111 1111 1111 1111

after y >>> 12

1048575


CAUTION

When performing bit manipulations on primitives shorter than 32 bits, remember that the compiler promotes all operands to 32 bits before performing the operation.

Two final notes on the (right shift) shift operators: If the right operand is larger than 31 for operations on 32-bit integers, the compiler uses only the five lowest order bits—values of 0 through 31, the remainder after division by 32—to control the number of bits shifted. With a 64-bit integer as the right operand, only the six lowest order bits (that is, values of 0 through 63, the remainder after division by 64) are used. Therefore, in line 1 of the following code fragment, y is shifted by only one bit; this also means that the sign bit is ignored, so in line 2, the right shift is not turned into a left shift by the minus sign:

1. x = y << 4097 ;
2. x = z >> -1 ;

Shift and Bitwise Operations with Assignment

Note that the assignment operator = can be combined with the shift and bitwise operators, just as with the arithmetic operators. The result is as you would expect.

Operators with Logical Expressions

The &, |, ^ (AND, OR, and XOR) operators used with integers also work with boolean values as expected. The compiler generates an error if both operands are not boolean. The tricky part (which you are almost guaranteed to run into) has to do with the && and || "conditional AND" and "conditional OR" operators.

When the & and | operators are used in an expression, both operands are evaluated. For example, in the following code fragment, both the ( x >= 0) test and the call to the testY method will be executed:

if(( x >= 0 ) & testY( y ) )

However, the conditional operators check the value of the left operand first and do not evaluate the right operand if it is not needed to determine the logical result. For instance, in the following code fragment, if x is -1, the result must be false. This means the testY method is never called:

if(( x >= 0 ) && testY( y ) )

Similarly, if the || operator finds the left operand to be true, the result must be true, so the right operand is not evaluated.

These conditional logical operators, also known as short circuit logical operators, are used frequently in Java programming. For example, if it is possible that a String object reference has not been initialized, you might use the following code, where the test versus null ensures that the equalsIgnoreCase method will never be called with a null reference:

// ans is declared to be a String reference
if( ans != null && ans.equalsIgnoreCase( "yes") ) {}

CAUTION

There is a very good chance you will get one or more questions that require understanding the conditional operators. These questions frequently involve the need to determine whether a reference is null.

Logical Operators with Assignment

Only the &, |, and ^ logical operators can be combined with =, producing the &=, |=, and ^= logical operators. Naturally, in a logical expression with these combined operators, the left operand must be a boolean primitive variable. Note that there are bitwise operators that look the same but that work with integer primitives.

The instanceof Operator

The instanceof operator tests the type of object the left operand refers to versus the type named by the right operand. The value returned is true if the object is of that type or if it inherits that type from a super type or interface implementation.

The right operand must be the name of a reference type, such as a class, an interface, or an array reference. Expressions using instanceof are unusual because the right operand cannot be an object. It must be the name of a reference type.

As an example of the use of instanceof, when the following code runs, both "List" and "AbstractList" are printed because the Vector class implements the List interface and descends from the AbstractList class.

  Vector v = new Vector();
  if( v instanceof List ){
   System.out.println("List") ; 
  }
  if( v instanceof AbstractList ){ 
   System.out.println("AbstractList") ;
  }

TIP

Remember that the instanceof operator can be used with interfaces and arrays as well as classes.

The Conditional Assignment Operator

The conditional assignment operator is the only Java operator that takes three operands. It is essentially a shortcut for a structure that takes at least two statements, as shown in the following code fragment (assume that x, y, and z are int primitive variables that have been initialized):

1. // long way
2. if( x > y ) z = x ;
3. else z = y ;
4. // 
5. // short way
6. z = x > y ? x : y ; 

The operand to the left of the ? must evaluate as boolean, and the other two operands must be of the same type, or convertible to the same type, which will be the type of the result. The result will be the operand to the left of the colon if the boolean is true; otherwise, it will be the right operand.

More About Assignment

You have seen the use of the = operator in simple assignments such as x = y + 3. You should also note that the value assigned can be used by a further assignment operator, such as in the following statement, which assigns the calculated value to all four variables:

a = b = c = x = y + 3 ;
  • + Share This
  • 🔖 Save To Your Account