How to make an infinite count loop in Java?

Asked

Viewed 1,037 times

-5

I am starting my studies with Java now and I would like to know how to do an infinite count I’m having difficulties, because I know that in Python it would be something like:

a = 0
while True:
    a = a + 1
    print(a)
  • 6

    Have you tried it in Java? How did it look? It was a mistake?

  • 1

    But what is the use of this loop as it is ? Or is it to try to understand loops ?

2 answers

3


Whatever the language, its "infinity" is relative to the maximum size that the data type you are going to use supports or, in the latter case, the available memory of your machine. That means an infinite Integer is well (WELL) less than the infinity of a BigInteger, for example. In other words, infinity is already in itself a conceptual mistake.

That said, a form of loop "infinite", the largest you can achieve in Java until you fill your equipment’s memory:

BigInteger infinito = BigInteger.ZERO;
for(;;) {
   infinito = infinito.add(BigInteger.ONE);
   System.out.println(infinito);
}
  • Does it fill up the memory? Because the numbers are not being saved (if you were adding in a List, For example, there’s the lottery), you just print it and then discard it, so I think the GC can hold it together. Perhaps the biggest impact is the CPU, because of all the I/O made to print all the numbers: https://stackoverflow.com/a/18585337

  • 1

    I believe that it gets to fill yes, so infer from the doc.: All of the Details in the Spec concerning overflow are Ignored, as Bigintegers are made as large as necessary to accommodate the Results of an Operation., here.

  • 1

    It’s true, I was thinking about int, but with BigInteger it will indeed fill

0

Based on the answer of the Statelessdev, it raised the idea of an infinite count (in theory). We could simplify/make the code more readable and transaprente by taking out the for(;) and leaving it with a while(true):

BigInteger contagem = BigInteger.ZERO;
while(true) {
   contagem = contagem.add(BigInteger.ONE);
   System.out.println(contagem);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.