Reputation: 39
trying to verify range of long in java.. why is this program not working? it gives infinite loop (probably). i'm not getting output at the command line and the cursor keeps blinking.
class range
{
public static void main(String [] args)
{
long i;
for(i=0;;i++)
{
long c= (long)(i+1);
if(i>c) //upper_limit+1=lower_limit
break; // hence, at i=upper_limit c(=i+1) < i
}
System.out.println("upper ="+i);
for(i=-1;;i--)
{
long c=(long)(i-1);
if(i<c) //lowerlimit-1=upperlimit
break; //hence at i=lowerlimit c(=i-1)>i
}
System.out.println("lower ="+i);
}
}
Upvotes: 1
Views: 353
Reputation: 3743
There is no reason to start at 0 or -1.
If you want to verify MIN/Max values, try it like this:
class range
{
public static void main(String [] args)
{
long i;
for(i=Long.MAX_VALUE;;i++)
{
long c= (long)(i+1);
if(i>c) //upper_limit+1=lower_limit
break; // hence, at i=upper_limit c(=i+1) < i
}
System.out.println("upper ="+i);
for(i=Long.MIN_VALUE;;i--)
{
long c=(long)(i-1);
if(i<c) //lowerlimit-1=upperlimit
break; //hence at i=lowerlimit c(=i-1)>i
}
System.out.println("lower ="+i);
}
}
Upvotes: 0
Reputation: 9559
You can use Long.MAX_VALUE and Long.MIN_VALUE
It will take lots of time to enumerate all 2^64 possible long values
Upvotes: 0
Reputation: 70989
Why do you think your program is not correct? It simply will take a long while - until long overflows(about 2^63 iterations). I suggest that you use Long.MIN_VALUE
and Long.MIN_VALUE
or if you want to avoid this solution use binary search for when overflow happens.
Also you may consider using the same program for short
to verify it is correct, simply very time consuming.
Upvotes: 1
Reputation: 1502246
Your program will work eventually - but it's got to perform 263 iterations (in each direction) first. That's going to take a very long time. Long.MAX_VALUE
and Long.MIN_VALUE
are rather simpler ways of finding this out. Or just look at JLS 4.2.1:
The values of the integral types are integers in the following ranges:
...
For
long
, from -9223372036854775808 to 9223372036854775807, inclusive
If you want to see your program finding the right values, just start it closer to the final result:
for(i=Long.MAX_VALUE - 10;;i++)
...
for(i=Long.MIN_VALUE + 10;;i--)
That quickly ends with output of:
upper =9223372036854775807
lower =-9223372036854775808
Upvotes: 7