2

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.

Ty_
  • 828
  • 1
  • 11
  • 21

3 Answers3

7

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.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 2
    The usual pattern is to throw `IllegalArgumentException` from the setter when an out of range values is passed in. – Steve Kuo Oct 31 '12 at 17:49
  • Alright thanks. I'm accepting this answer since it was first and the others just confirmed what you said. – Ty_ Oct 31 '12 at 23:22
5

no, you have to manually check it in your program

ton
  • 51
  • 1
1
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

Aubin
  • 14,617
  • 9
  • 61
  • 84