Saturday, 10 January 2015

Java break Statement

The Java break statement allows you to terminate a loop. Here are a couple of examples:

andrew@UBUNTU:~/Java$ cat prog78.java
public class prog78
{
public static void main (String args[])
  {
  for (int a=1;a<10;a++)
    {
    System.out.println("a = " + a);
    if (a > 4)
      {
      System.out.println("BREAK");
      break;
      }
    }
  int b=0;
  while (true)
    {
    System.out.println("b = " + b);
    b++;
    if (b > 3)
      {
      System.out.println("BREAK");
      break;
      }
    }
  }
}
andrew@UBUNTU:~/Java$ javac prog78.java
andrew@UBUNTU:~/Java$ java prog78
a = 1
a = 2
a = 3
a = 4
a = 5
BREAK
b = 0
b = 1
b = 2
b = 3
BREAK
andrew@UBUNTU:~/Java$