Java brain teaser question
This is a frighteningly subtle bug I first learned about in C (Andrew Koenig's ``C Traps and Pitfalls''), but it's still with us in Java, and I assume C++ as well...
The following method looks like it should always return the absolute value of n, but every once in a while it returns the wrong answer. Spot the bug:
static int absVal(int n)
{
if (n < 0)
{
return (n * -1);
}
else
{
return (n);
}
}
bug
Solution in a couple days. Hint: The error is simple (covered in our second lecture), but not at all obvious.
ilovejava
Junior Poster in Training
77 posts since Sep 2011
Reputation Points: 10
Solved Threads: 2
you mean by running it on the smallest possible int value
-2147483648
?
stultuske
Posting Sensei
3,137 posts since Jan 2007
Reputation Points: 1,114
Solved Threads: 433
sorta so how will it be fixewd
ilovejava
Junior Poster in Training
77 posts since Sep 2011
Reputation Points: 10
Solved Threads: 2
not..
the integer (primitive) can only store the values between (borders included)
-2147483648 <-> 2147483647
so, it can impossibly contain the absolute value for -2147483648, unless you use a larger numerical type.
stultuske
Posting Sensei
3,137 posts since Jan 2007
Reputation Points: 1,114
Solved Threads: 433
yea didnt say that was the answer there is a bug find it
ilovejava
Junior Poster in Training
77 posts since Sep 2011
Reputation Points: 10
Solved Threads: 2
when I asked whether that was what you ment, you answered 'sort off', so we assumed you did mean that.
EDIT: Also, saying "it is covered in our second lecture" doesn't mean that much to us.
stultuske
Posting Sensei
3,137 posts since Jan 2007
Reputation Points: 1,114
Solved Threads: 433
This is a frighteningly subtle bug I first learned about in C (Andrew Koenig's ``C Traps and Pitfalls''), but it's still with us in Java, and I assume C++ as well...
The following method looks like it should always return the absolute value of n, but every once in a while it returns the wrong answer. Spot the bug:
static int absVal(int n)
{
if (n < 0)
{
return (n * -1);
}
else
{
return (n);
}
}
bug
Solution in a couple days. Hint: The error is simple (covered in our second lecture), but not at all obvious.
Well ....
I'm still curious into what the error in this code is.
could you enlighten us about it?
stultuske
Posting Sensei
3,137 posts since Jan 2007
Reputation Points: 1,114
Solved Threads: 433