Questionaries.org
Login
Register
Questions
Unanswered
Tags
Users
Ask a Question
Welcome to Questionaries, where you can ask questions and receive answers from other members of the community.
Let us know at info@questionaries.org
Why is Java not telling me when I can’t use Integer?
12
like
0
dislike
Hello
For a small project (Problem 10 Project Euler) i tried to sum up all prime numbers below 2 millions. So I used a brute force method and iterated from 0 to 2'000'000 and checked if the number is a prime. If it is I added it to the sum:
private int sum = 0;
private void calculate() {
for (int i = 0; i < 2000000; i++) {
if (i.isPrime()) {
sum = sum + i;
}
}
sysout(sum)
}
The result of this calculation is 1179908154, but this is incorrect. So i changed int to BigInteger and now i get the correct sum 142913828922. Obviously the range of int was overflowed. But why can't Java tell me that? (e.g. by an exception)
asked
2 years
ago
by
pollard
(
41,990
points)
java
math
project-euler
2 Answers
2
like
0
dislike
Best answer
Because it's conceivable that you might want it to behave in the traditional Integer fashion. Exceptions are reserved for things that are definitely and irrevocably wrong.
ETA: From the language spec:
"The built-in integer operators do not indicate overflow or underflow in any way. The only numeric operators that can throw an exception (§11) are the integer divide operator / (§15.17.2) and the integer remainder operator % (§15.17.3), which throw an ArithmeticException if the right-hand operand is zero."
(
http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html)
answered
2 years
ago
by
william
(
91,210
points)
4
like
0
dislike
Because our profession values performance over correctness. ;(
Using BigInteger by default, and only reasoning whether it is acceptable, to use long or int if performance is a real problem, would help to avoid such problems.
answered
2 years
ago
by
biswaskeran
(
70,430
points)
Related questions
4
like
0
dislike
1
answer
Why can't I say just abs() or sin() instead of Math.abs() and Math.sin()?
asked
1 year
ago
by
DBA-boss
(
120,990
points)
java
register
11
like
0
dislike
1
answer
Can not open ports in iptables on CentOS 5?? [closed]
asked
2 years
ago
by
DBA-boss
(
120,990
points)
design
vss2005
mode
open
math
13
like
0
dislike
0
answers
Given two lines on a plane, how to find integer points closest to their intersection?
asked
2 years
ago
by
biswaskeran
(
70,430
points)
algorithm
problem-solving
math
12
like
1
dislike
0
answers
Given two lines on a plane, how to find integer points closest to their intersection?
asked
2 years
ago
by
biswaskeran
(
70,430
points)
algorithm
problem-solving
math
5
like
0
dislike
1
answer
How does Java handle integer overflows and underflows?
asked
1 year
ago
by
sr_webmaster
(
21,000
points)
java
handle
integer
overflows
underflows