Is there an elegant way in java to check if an int is equal to, or 1 larger/smaller than a value.
For example, if I check x to be around 5. I want to return true on 4, 5 and 6, because 4 and 6 are just one away from 5.
Is there a build in function to do this? Or am I better off writing it like this?
int i = 5;
int j = 5;
if(i == j || i == j-1 || i == j+1)
{
//pass
}
//or
if(i >= j-1 && i <= j+1)
{
//also works
}
Of course the above code is ugly and hard to read. So is there a better way?
Find the absolute difference between them with
Math.absBased on @GregS comment about overflowing if you give
Math.absa difference that will not fit into an integer you will get an overflow valueBy casting one of the arguments to a long
Math.abswill return a long meaning that the difference will be returned correctlySo with this in mind the method will now look like: