3

I was just watching a video on YouTube about the history of loops in programming and it was mentioned that in FORTRAN there was a maximum number of nested loops the compiler would allow. Is there a codified limit for this with Java?

user207421
  • 305,947
  • 44
  • 307
  • 483
Ryan H.
  • 43
  • 2
  • 9
  • 1
    I'm not sure there is a limit since for loops are just `JUMP` codes in bytecode. Methods on the other hand... the stack limit is configurable – killjoy Jun 01 '18 at 22:58
  • Only inasmuch as you don't exceed the compilers memory, and you can always extend that, so.... No. – Andreas Jun 01 '18 at 22:59
  • 1
    @Andreas I suppose there is a maximum size of 64 KB per method given from the Java Virtual Machine Specification. So, as long as you are within that bounds, there should be any number of nested loops allowed. – Glains Jun 01 '18 at 23:06
  • 1
    In theory, you might eventually run into limits on the size that your class/method can be, but that wouldn't be specific to nested loops. Read more here: https://stackoverflow.com/questions/42294998/what-is-the-maximum-size-of-a-java-class-file – mypetlion Jun 01 '18 at 23:06
  • Lmao "a video on youtube" just say Computerphile sent you, everyone will understand your urge to know the answer – Matt Smeets Oct 09 '18 at 19:32
  • is this the video https://www.youtube.com/watch?v=HXNhEYqFo0o? (Computerphile is one of my favorite YouTube channel) – asdru Mar 28 '21 at 23:37

2 Answers2

3

I'm confident that there is no limit on the amount of nested loop you can have in Java. However, Java does have a limit on the size of the methods in Java. A method in Java can be up to a maximum of 64KB. So, you can have as many nested loops as long as they are under the 64KB of memory.

3

There is no limit as such, however there is a limit to the size of a method.

This can be a good read.

Complexity is determined by the number of decision points in a method plus one for the method entry. The decision points are 'if', 'while', 'for', and 'case labels'. Generally, 1-4 is low complexity, 5-7 indicates moderate complexity, 8-10 is high complexity, and 11+ is very high complexity.

Also you can use this code to test your code.

Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
  • I would not be surprised if the maximum number of nested loops has a practical limit due to compiler implementations which often process nested constructs using recursion. Compare with [the maximum number of nested method invocation expressions](https://stackoverflow.com/a/31112260/2711488). – Holger Oct 16 '18 at 16:32