Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does (int & Integer.MAX_VALUE) % int do in Java?

Tags:

java

In Java, I encountered the following line:

e.g.: (1 & Integer.MAX_VALUE) % 4
e.g.: (2 & Integer.MAX_VALUE) % 5

What does it do? I have tried the code, but I couldn't comprehend its purpose or functionality. What is the code trying to check?

Basically, it's (int & Integer.MAX_VALUE) % int.

Actual code (from Hadoop training class):

public int getPartition(StringPairWritable key, Text value, int numReduceTasks) {
    return (key.getLeft().hashCode() & Integer.MAX_VALUE) % numReduceTasks;
}
like image 467
FailedMathematician Avatar asked Oct 18 '25 08:10

FailedMathematician


1 Answers

i & Integer.MAX_VALUE does the same thing as this code:

if(i < 0) {
    i = (i + Integer.MAX_VALUE + 1);
}

The % is a regular remainder operation.

It's a quick way of ensuring that an integer is positive if you don't care about it's actual value (e.g. if you want to turn random numbers that can be both positive and negative into only positive values).

like image 92
Raniz Avatar answered Oct 19 '25 23:10

Raniz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!