# Thread: Bitwise logical operators in Java

1. Member
Join Date
May 2008
Posts
69

## Bitwise logical operators in Java

Hi Friends,

I am studying in second year of the Bsc(I.T). Portion of this year includes JAVA programming.The main thing is that I don't know anything about the bitwise logical operators.

Can anyone suggest me, what are the different Bitwise logical operators are available in JAVA language? What is the use of them?

2. Member
Join Date
Oct 2005
Posts
2,394

## Re: Bitwise logical operators in Java

Following are the different bitwise logical operators available in Java:

1. AND(&):1 if both bits are 1.
e.g:3 & 5 (result is 1 )

2.XOR(^):1 if both bits are different.
e.g: 5 ^7 (result is 6)

3. OR(|):1 if either bit is 1.
e.g:3 | 5 (result is 7)

4.Shift Left(<<):This operator used to Shifts the bits of n left p positions. Zero bits are shifted into the low-order positions.
e.g:3 << 2(result is 12)

3. Member
Join Date
May 2008
Posts
2,393

## Re: Bitwise logical operators in Java

According to my knowledge following Bitwise logical operators are available in the Java:

i). NOT operator(~)

ii). OR operator(|)

iii). AND operator(&)

iii). XOR operator(^)

For reference see below example of 'AND' operator:

class Bits3{
public static void main(String args[]){
System.out.println(" & OR opeartor");

// apply the AND(&) operator
int a = 21&40;
System.out.println("21&40 = "+a);
} }

4. Member
Join Date
Feb 2008
Posts
1,856

## Re: Bitwise logical operators in Java

Bitwise logical operators of java operate on individual bits of integer (long & int) values. Suppose If an operand is shorter than an int, it is promoted to int before doing the any operation.

Important use of the bitwise logical operators is to work with multiple values that have been encoded within one int. See below example of this:

int Age, Gen, Ht;
short packed_info;
. . .
// packing
packed_info = (((Age<< 1) | Gen) << 7) | Ht;
. . .
// unpacking
Ht= packed_info & 0x7f;
Gen= (packed_info >>> 7) & 1;
Age= (packed_info >>> 8);

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•