+ 5

Java Loop help

Maybe a more advanced learner can help me with this problem: public class WhileLoop { public static void main(String[] args) { int r = 1; int i = 1; while(i < 65) { r = r*2; i++; } System.out.println(r); } } //Why is the output 0???

12th Mar 2018, 11:42 AM
Psycho
3 Answers
+ 19
That's because result is out of int range (also result is out of long range). You need BigInteger to resolve this problem : https://code.sololearn.com/cKKLqJ24bjhu/?ref=app
12th Mar 2018, 2:36 PM
LukArToDo
LukArToDo - avatar
+ 7
Correcting the line : System.out.println(r); Mathematically answer is 2^64. But as java cannot store such a big number. Output will be something different maybe 0.
12th Mar 2018, 12:23 PM
cHiRaG GhOsH
cHiRaG GhOsH - avatar
+ 6
your doubling the previous value of r each loop like @cHiRag said its such a big number. You could always limit your while loop say too i<20 ?
12th Mar 2018, 2:08 PM
D_Stark
D_Stark - avatar