Link to home
Start Free TrialLog in
Avatar of badwolfff
badwolfffFlag for United Kingdom of Great Britain and Northern Ireland

asked on

What is the code doing exactly and what is the theoretical reason why this code is not compiling? (part 1)

Please see below some java code which I am trying to compile and run. I am fully aware that the code has an error. I also know how to fix it (as you can see from the comment just below). What I don't however know is what this code is actually doing.
Is it looping infinitely? Does it stop abruptly? What is the exact reason behind why I get a compile error?

import java.util.Random;

public class PartA {

    //loop 10 times
    private static void loop2() {
        for(;;) System.out.println("In loop");
        //for(int i = 0; i < 10; i++) System.out.println("In loop");
        System.out.println("Out of loop");
    }

        private static void runLoops() {
		loop2();
		System.out.println();
	}


	public static void main(String[] args) {
		runLoops();
	}

}

Open in new window


thanks in advance
ASKER CERTIFIED SOLUTION
Avatar of David Johnson, CD
David Johnson, CD
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
What is the exact reason behind why I get a compile error?
Because the line the compiler will indicate is not reachable because it is preceded by an infinite loop
Avatar of badwolfff

ASKER

When there are infinite loops the java compiler tells me "code taking more than 5 seconds to execute" and it kills it (compilejava.net).
Here I get a different error: Unable to execute program; could not compile!
/tmp/java_kmr4s7/PartA.java:9: error: unreachable statement
        System.out.println("Out of loop");
        ^
1 error

So is this an infinite loop or something else? And if it is an infinite loop, why? What is the stop condition that is not being met?
thanks
You're really just repeating the question, but:

When there are infinite loops the java compiler tells me "code taking more than 5 seconds to execute" and it kills it (compilejava.net).

I'm not sure why you're using compilejava.net but it isn't helping you. Why? Because you're not able to distinguish between compilation and execution, which you would be able to do if you were using standard tools (javac+java). If something is able to be killed, it must be running, which means it must have been able to be, and was, compiled.

The differences you're seeing are due to cases where the compiler knows a loop won't ever finish, such that the next statement is unreachable and cases where it doesn't know, but the loop turns out to be infinite anyway
Thanks. Got it.
Why did you accept only ONE answer, which evidently didn't answer your subsidiary questions?
Ah I didn't realize that is how it is done in experts exchange. Sorry. Will keep it in mind next time unless I can change this selection.