Why does Java use int i = 1<<4, not int i = 16?

Because it's clearly stated in the Java documentation that default initial capacity must be a power of two. If we were to see just any other integer instead of the bitwise operator, that wouldn't illustrate the limitation so well.

Thus by using a left shift operator, it is letting every developer know that it is there for us to notice a point which one should know, be it while modifying or using the HashMap class.


It provides more readability and understanding of how you arrived at a certain number to begin with. Consider the below example

final int red = 1;
final int blue = 1 << 1;
final int magenta = red | blue; // 3

Each bit in the above numbers represent a primary color, and from the code you could easily figure out why I chose 3 for magenta. It wouldn't have been easier for the reader if you directly set the value 3 in the declaration.

Tags:

Java