0

Say I have a method:

public void method(int i) {
    this.value =+ i;
}

How can I restrict i to a value greater than x? I understand this can be done outside the method but I would prefer to condition it in the constructor. Would it be something like:

public void method(int i; i > x){...};

Sorry for not testing this myself, I came up with it as I wrote my query.

Raedwald
  • 46,613
  • 43
  • 151
  • 237
Matias Faure
  • 822
  • 1
  • 9
  • 20

3 Answers3

9

There is no syntax in Java that can restrict the range of a parameter. If it takes an int, then all possible values of int are legal to pass.

You can however test the value with code in the method and throw an IllegalArgumentException if i is not greater than x.

rgettman
  • 176,041
  • 30
  • 275
  • 357
7

You document the method, and throw an exception if the caller doesn't respect the contract.

/**
 * Does something cool.
 * @param i a value that must be > x
 * @throws IllegalArgumentException if i <= x
 */
public void method(int i) {
    if (i <= x) {
        throw new IllegalArgumentException("i must be > x");
    }
    this.value += i;
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • I would do it throw new IllegalArgumentException(i + " must be > " + x"); – Andreas L. Nov 25 '14 at 19:00
  • 1
    That would make it less clear, IMO: 4 must be > 5: what does that mean? But I agree having the values would be helpful: `throw new IllegalArgumentException("i (whose value is " + i + ") must be > x (whose value is " + x + ")");` – JB Nizet Nov 25 '14 at 19:04
2

That are no built-in preconditions for method (or constructor) arguments. Either check them at the calling site or within the method (or constructor). You have two options: throw an exception within the method or don't call the method.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724