Java: how to limit argument’s values that can be passed to a method

Suppose I have a method that takes one int as a argument,

suppose the method expects only the values 0, 1, 2 and not other int.

Is there a way to “force” the method to accept only 0, 1, 2?

Answer

You would have to create a custom data type that can only take the values 0, 1 and 2. You can’t use an ordinary int.

In this case you could use an enum:

enum ZeroOneOrTwo {
    ZERO(0),
    ONE(1),
    TWO(2);
    public final int val;
    private ZeroOneOrTwo(int val) {
        this.val = val;
    }
}

and use it as follows:

void myMethod(ZeroOneOrTwo arg) {
    System.out.println("Int value: " + arg.val);
}

If you’re forced to take an int as argument (if you’re implementing an interface for instance) you can resort to throwing an IllegalArgumentException if the given value is out of range. But generally you would want to let the compiler catch the problem rather than having to deal with it at runtime.

Leave a Reply

Your email address will not be published. Required fields are marked *