bhavya joshi
bhavya joshi

Reputation: 1136

Bitwise Operator use

while doing practice question,i encountered a code:

private char[] a;
int newcap = ((a.length * 3) >> 1) + 1;

where newcap is the new capacity of array, Using ((a.length*3)+1) will be sufficient too,but instead they have used a bitwise Operator.Why ?? I know the use of bitwise operator. The code is from http://www.java2s.com/Tutorials/Java/Collection/ArrayList/Create_a_Char_Array_List_in_Java.htm

Upvotes: 1

Views: 89

Answers (2)

Laszlo Hirdi
Laszlo Hirdi

Reputation: 1150

<<n is often used instead of multiplication with (2 to the power of n)
>>n is often used instead of division by (2 to the power of n)

It is only a performance optimization for the processor which gives the same result.

Upvotes: 0

Jean-Fran&#231;ois Savard
Jean-Fran&#231;ois Savard

Reputation: 21004

It would not be the same, shifting to right of 1 bit is the same as doing a division by two.

For example, 10 >> 1 = 5.

In your example, you multiply the length by 3, then divide by two and finally add 1 to the result so "Using ((a.length*3)+1)" would not be "sufficient".

However, note that ((a.length*3) / 2 +1) would do the same.

Note that you can also multiply by two with bitwise operator, but with left shift instead of right shift.

System.out.println(10 << 1);//print 20

Upvotes: 1

Related Questions