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

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Java: how to limit argument’s values that can be passed to a method without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.

We are here to answer your question about Java: how to limit argument’s values that can be passed to a method - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji