What's up with the break statement?

Fredrik Warg warg@ce.chalmers.se
Thu Nov 25 06:02:00 GMT 1999


Hi all,

I've found a problem with the break statement
in nested for loops. I wonder whether this is
already known/fixed (I'm using gcj/libgcj 2.95.1
at the moment) or not?

The following two programs should both
generate the output "01234" (and does so with
the Sun JDK). But only the latter one works
correctly with gcj, the first one gives the output
"0" only.

------------------------------------------------

public class Main {
    public static void main(String argv[]) {
      int i, j;
      for (i=0; i<5; i++)
	  for (j=0; j<2; j++)
	      {
		  if (j==1) break;
		  System.out.print(i);
	      }
    }
}

The break statement exits both for-loops (not just
the inner one as it should) when the outer loop body
is not enclosed in curly brackets.

-------------------------------------------

public class Main2 {
    public static void main(String argv[]) {
      int i, j;
      for (i=0; i<5; i++)
	  {
	      for (j=0; j<2; j++)
		  {
		      if (j==1) break;
		      System.out.print(i);
		  }
	  }
    }
}

Adding curly brackets to the outer for-loop fixes the problem,
but it shouldn't be needed...

What say The Masters?


/Fredrik

-------------------------------------
Fredrik Warg -- [warg@ce.chalmers.se]
http://www.ce.chalmers.se/staff/warg/



More information about the Java mailing list