Reputation: 63
I have to create a code that displays the squares of the first 100000 numbers and measure the amount of time the program takes to display each number. During my results, the numbers sometimes go negative and then go positive again. Why is this? How should I change my code so that my results are not negative? (This does not happen with the first 1000 square numbers or 10000).
package assignment.pkg5;
import java.util.Calendar;
public class LoopsLab1000001b {
public static void main(String[] args) {
long time_start, time_finish;
time_start = time();
int count = 1;
while (count <= 100000) {
System.out.println(count * count);
count++;
}
time_finish = time();
System.out.println(time_finish - time_start + " milli seconds");
}
public static long time() {
Calendar cal = Calendar.getInstance();
return cal.getTimeInMillis();
}
}
Upvotes: 4
Views: 199
Reputation: 31161
Integer overflow. See wiki, and specifically:
In some situations, a program may make the assumption that a variable always contains a positive value. If the variable has a signed integer type, an overflow can cause its value to wrap and become negative. This overflow violates the program's assumption and may lead to unintended behavior.
Upvotes: 1