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
  • 43,666
  • 36
  • 142
  • 227
Matias Faure
  • 802
  • 9
  • 19

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
  • 172,063
  • 28
  • 262
  • 343
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
  • 657,433
  • 87
  • 1,179
  • 1,226
  • 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
  • 263,859
  • 56
  • 671
  • 702