Actually I know the declaration of array in java but here I am unable to understand the use of this syntax:
int a[] = new int[3 << 1];
In place of a size for the array, here <<
this symbol is used for?
Actually I know the declaration of array in java but here I am unable to understand the use of this syntax:
int a[] = new int[3 << 1];
In place of a size for the array, here <<
this symbol is used for?
<<
is the left shift operator and belongs to the bitwise and bit shift operators. For a detailed explanation of how each bitwise and bit shift operator works, please refer to this answer by @DerekPark. Thus, 3 << 1
is an arthmetic expression that gets evaluated before the array is created. 3 << 1
evaluates to 6
, thus an int[]
of size 6
gets created.
The <<
symbol is known as the "left shift operator." As you can probably guess, it gets its name from shifting bit positions to the left.
There's a good example posted by another user at the following:
Right shift and left shift operators shift your number to the right of left in their binary representation. If you left shift by one the number 3 3<<1
this would mean that:
The binary for 3 which is 011
gets shifted to the left(basically a 0 is added in the front) 0110
and now your number is 6.
The opposite thing would happen with right shift: If you have the number 3 011
and you right shift it by 1 3>>1
the first bit will get chopped off 01
and you'll end up with the number 1.
Shift operators are useful for multiplying or dividing by powers of 2, and it's a bit faster than just saying 3*2.
<<
is the bitwise left shift operator and is often used for efficiently multiplying for specific powers of two, as bitwise operators tend to be faster. x << n
is usually equivalent to x*2n
, except for cases involving int overflow.
3
in binary is represented as 11
and after shifting to the left by one, it becomes 110
, which is 6
in decimal. It can be seen intuitively that shifting by n
places to the left is equivalent to multiplying by two n
times, as each shift adds a binary digit to the right, which increases the value of every other digit by a factor of 2.