& instead of % optimization?

I was doing a bit manipulation problem the other day, and realized I could replace n % 16 with n & 15

Since % is slow, and & fast, is this a good optimization, or does the compiler already do something like this, and I don’t need to bother?


There is a very tricky difference here. The same idea that you have here is sort of done when choosing a bucket in the HashMap implementation.

If your n is negative:

System.out.println(-31 % 16); // -15
System.out.println(-31 & 15); // 1

you will get different results.