Home > Articles

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 ;

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020