Reputation: 848
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
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
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