Where's the safety bug in this double comparison
-
30-06-2021 - |
Frage
I was interviewed yesterday and this question arise:
public class Main {
public static void main(String[] args) {
// Code fragment must prints true if the double variables x and y are both
// strictly between 0 and 1 and false otherwise.
// Assuming args will be always correct (double) input,
// Where's the safety bug?
double x,y;
x = Double.parseDouble(args[0]);
y = Double.parseDouble(args[1]);
System.out.println( (0 < x && x < 1) && (0 < y && y < 1)? true : false );
}
}
I wrote there were no bug anywhere, I mean, code works. Back at home, tried and indeed it works. But although I did get the job, this question was my only bad one, and I can't get it out of my head (it seams fair straight simple). I believe I don't even understand what a safety bug is so, my question then is:
What's a safety bug and does this code indeed have one?
UPDATE:
After response I put some related resources:
Lösung
Judging from the comment in the source:
Assuming args will be always correct (double) input, Where's the safety bug?
There exists a case in which the program will deliver a wrong output, and there seems to be no dubious except the expression itself:
(0 < x && x < 1) && (0 < y && y < 1)
Although I haven't tested it, there may be a problem when this expression is confronted with one of the edge cases for either x or y: NaN, +/- infinity and maybe even -0.0.
Also there exist definitively valid inputs which may violate the logical expectation of the user due to the limited precision with which number are represented in a double (e.g. x = 1E-400 is greater than 0, but parses as 0, so the expression delivers false although the user would expect true).
Andere Tipps
I would go with type safety and uncaught exception if the input somewhat happens to not be double. Then the code just throws an exception.
You can set x to 0, and you can enter 0 for y. But the values must be between.
You better use strictfp. You better use 0d instead of 0.