How do I clamp values in Java?


Calling increaseContrast subtracts 16 from pixels with 0 <= value <= 127 and adds 16 to pixels with 128 <= value <= MAXVAL. Do not allow pixel values to overflow MAXVAL or become negative, i.e. clamp the pixels to 0 when subtracting and MAXVAL when adding.


public void increaseContrast() {


Edit: I apologize for not specifying what I have written under the method, but I can't post my personal program/code because my university will penalize me for plagiarism.


  • Clamping means that you limit your value to a certain range.

    You can either manually check if your value exceeds the upper or lower limit and set that limit as new value or you simply use min and max.

    int minimum = 5;
    int maximum = 10;
    int value = 29;
    if (value < minimum){
      value = minimum;
    else if (value > maximum){
      value = maximum;

    Or you simply do something like this:

    value = Math.min(maximum, Math.max(minimum, value));