I wrote the following code to test how long it takes for java to perform the simple task of counting from 0 to a huge number:
public static void main( String[] args )
{
for( long k = 0 ; k <= 1000000000000000000L /* 18 zeros */ ; k++ )
;
System.out.println( "Finished" );
}
I ran the program and waited for hours. After waiting so long I had no way other than referring to some calculations to estimate this running time, and with a simple calculation I convinced that it can take even more than 100 years (depending on the CPU) for the program to finally print the message "Finished"!
But after trying the following code which appears to take just as much time as the above code to finish, I unexpectedly saw that the message "Finished" was printed in a fraction of a second after I ran the program!
public static void main( String[] args )
{
int j;
for( int i = 0 ; i <= 1000000000 /* 9 zeros */ ; i++ )
for( j = 0 ; j <= 1000000000 /* 9 zeros */ ; j++ )
;
System.out.println( "Finished" );
}
What is the difference of java's behavior with these two pieces of code? There must actually be some difference between java's behavior with int numbers, and its behavior with integer types other than int.