Ty_
Ty_

Reputation: 848

Is there a way to set bounds on a variable in Java?

For instance can I have a variable

int x;

and tell the compiler x can never be greater than 20 or less than -20 without having to write a method to check the value every iteration through the loop? (I should mention here this is for a vector-based game's velocity variable.

Upvotes: 2

Views: 1313

Answers (3)

Aubin
Aubin

Reputation: 14853

assert  -20 < x && x < 20 : "Out of range!";

Executed with -ea argument, java will check the condition, without -ea the performance are at their best.

In case of assertion will not be verified java.lang.AssertionError will be thrown

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Only set the variables via a setter method. Inside of this method, throw an exception if it attempts to set the value out of range. Note that this won't work on the compiler side of things but rather at runtime which is where I believe this sort of check is necessary.

Upvotes: 7

ton
ton

Reputation: 51

no, you have to manually check it in your program

Upvotes: 5

Related Questions