File 06
File 06
System.out.print("for(init; condition;
iteration)");
System.out.println(" statement;");
break;
case '4':
System.out.println("The while:\n");
System.out.println("while(condition)
statement;");
break;
case '5':
System.out.println("The do-while:\n");
System.out.println("do {");
System.out.println(" statement;");
break;
Riccardo Flask 61 | P a g e
JAVA for Beginners
One can use the ‘break’ command to terminate voluntarily a loop. Execution will continue from the
next line following the loop statements,
class BreakDemo {
public static void main(String args[]) {
int num;
num = 100;
for(int i=0; i < num; i++) {
if(i*i >= num) break; // terminate loop if i*i >= 100
System.out.print(i + " ");
}
System.out.println("Loop complete."); When i = 10, i*i = 100. Therefore
} the ‘if’ condition is satisfied and
}
the loop terminates before i = 100
Expected Output:
0 1 2 3 4 5 6 7 8 9 Loop complete.
class Break2 {
public static void main(String args[])
throws java.io.IOException {
char ch;
for( ; ; ) {
ch = (char) System.in.read(); // get a char
if(ch == 'q') break;
}
System.out.println("You pressed q!");
}
}
In the above program there is an infinite loop, for( ; ; ) . This means that the program will
never terminate unless the user presses a particular letter on the keyboard, in this case ‘q’.
If we have nested loops, i.e. a loop within a loop, the ‘break’ will terminate the inner loop. It is not
recommended to use many ‘break’ statement in nested loops as it could lead to bad programs.
However there could be more than one ‘break’ statement in a loop. If there is a switch statement in
a loop, the ‘break’ statement will affect the switch statement only. The following code shows an
example of nested loops using the ‘break’ to terminate the inner loop;
Riccardo Flask 62 | P a g e
JAVA for Beginners
class Break3 {
public static void main(String args[]) {
for(int i=0; i<3; i++) {
System.out.println("Outer loop count: " + i);
System.out.print(" Inner loop count: ");
int t = 0;
while(t < 100) {
if(t == 10) break; // terminate loop if t is 10
System.out.print(t + " ");
t++;
}
System.out.println();
}
System.out.println("Loops complete.");
}
}
Predicted Output:
Programmers refer to this technique as the GOTO function where one instructs the program to jump
to another location in the code and continue execution. However Java does not offer this feature but
it can be implemented by using break and labels. Labels can be any valid Java identifier and a colon
should follow. Labels have to be declared before a block of code, e.g.
class Break4 {
public static void main(String args[]) { One, two and three are
int i; labels
for(i=1; i<4; i++) {
one: {
two: {
three: {
System.out.println("\ni is " + i);
if(i==1) break one;
if(i==2) break two;
if(i==3) break three;
// the following statement is never executed
System.out.println("won't print");
}
Riccardo Flask 63 | P a g e
JAVA for Beginners
Predicted Output:
i is 1
After block one.
i is 2
After block two.
After block one.
i is 3
After block three.
After block two.
After block one.
After for.
Interpreting the above code can prove to be quite tricky. When ‘i’ is , execution will break after the
first ‘if’ statement and resume where there is the label ‘one’. This will execute the statement
labelled ‘one’ above. When ‘i’ is , this time execution will resume at the point labelled ‘two’ and
hence will also execute the following statements including the one labelled ‘one’.
The following code is another example using labels but this time the label marks a point outside the
loop:
class Break5 {
public static void main(String args[]) {
done:
for(int i=0; i<10; i++) {
for(int j=0; j<10; j++) {
for(int k=0; k<10; k++) {
System.out.println(k);
if(k == 5) break done; // jump to done
}
System.out.println("After k loop"); // skipped
}
System.out.println("After j loop"); // skipped
}
System.out.println("After i loop");
}
}
Riccardo Flask 64 | P a g e
JAVA for Beginners
Predicted Output:
0
1
2
3
4
5
After i loop
The ‘k’ loop is terminated when ‘k’ . However the ‘j’ loop is skipped since the break operation
cause execution to resume at a point outside the loops. Hence only the ‘i’ loop terminates and thus
the relevant statement is printed.
The next example shows the difference in execution taking care to where one puts the label:
class Break6 {
public static void main(String args[]) {
int x=0, y=0;
stop1: for(x=0; x < 5; x++) {
for(y = 0; y < 5; y++) {
if(y == 2) break stop1;
System.out.println("x and y: " + x + " " + y);
}
}
System.out.println();
for(x=0; x < 5; x++)
stop2: {
for(y = 0; y < 5; y++) {
if(y == 2) break stop2;
System.out.println("x and y: " + x + " " + y);
}
}
}
}
In the first part the inner loop stops when ‘y’ = 2. The
Predicted Output: break operation forces the program to skip the outer
x and y: 0 0 ‘for’ loop, print a blank line and start the next set of
x and y: 0 1 loops. This time the label is placed after the ‘for’ loop
declaration. Hence the break operation is only
x and y: 0 0
x and y: 0 1 operating on the inner loop this time. In fact ‘x’ goes
x and y: 1 0 all the way from 0 to 4, with ‘y’ always stopping
x and y: 1 1
x and y: 2 0
when it reaches a value of 2.
x and y: 2 1
x and y: 3 0
x and y: 3 1
x and y: 4 0
x and y: 4 1
Riccardo Flask 65 | P a g e
JAVA for Beginners
The break – label feature can only be used within the same block of code. The following code is an
example of misuse of the break – label operation:
The ‘continue’ feature can force a loop to iterate out of its normal control behaviour. It is regarded
as the complement of the break operation. Let us consider the following example,
class ContDemo {
public static void main(String args[]) {
int i;
for(i = 0; i<=100; i++) {
if((i%2) != 0) continue;
System.out.println(i);
}
}
}
Predicted Output:
100
The program prints on screen the even numbers. This happens since whenever the modulus results
of ‘i’ by are not equal to ‘ ’, the ‘continue’ statement forces loop to iterate bypassing the following
statement (modulus refers to the remainder of dividing ‘i’ by ).
Riccardo Flask 66 | P a g e
JAVA for Beginners
In ‘while’ and ‘do-while’ loops, a ‘continue’ statement will cause control to go directly to the
conditional expression and then continue the looping process. In the case of the ‘for’ loop, the
iteration expression of the loop is evaluated, then the conditional expression is executed, and then
the loop continues.
Continue + Label
It is possible to use labels with the continue feature. It works the same as when we used it before in
the break operation.
class ContToLabel {
public static void main(String args[]) {
outerloop:
for(int i=1; i < 10; i++) {
System.out.print("\nOuter loop pass " + i +
", Inner loop: ");
for(int j = 1; j < 10; j++) {
if(j == 5) continue outerloop;
System.out.print(j);
}
}
}
}
Predicted Output:
Note that the inner loop is allowed to execute until ‘j’ is equal to . Then loop is forced to outer loop.
Riccardo Flask 67 | P a g e
JAVA for Beginners
1. Copy all the code from Help2.java into a new file, Help3.java
2. Create an outer loop which covers the whole code. This loop should be declared as infinite but
terminate when the user presses ‘q’ (use the break)
3. Your menu should look like this:
do {
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. for");
System.out.println(" 4. while");
System.out.println(" 5. do-while");
System.out.println(" 6. break");
System.out.println(" 7. continue\n");
System.out.print("Choose one (q to quit): ");
do {
choice = (char) System.in.read();
} while(choice == '\n' | choice == '\r');
} while( choice < '1' | choice > '7' & choice != 'q');
4. Adjust the switch statement to include the ‘break’ and ‘continue’ features.
Complete Listing
class Help3 {
throws java.io.IOException {
char choice;
for(;;) {
do {
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. for");
System.out.println(" 4. while");
Riccardo Flask 68 | P a g e
JAVA for Beginners
System.out.println(" 5. do-while");
System.out.println(" 6. break");
System.out.println(" 7. continue\n");
do {
} while( choice < '1' | choice > '7' & choice != 'q');
System.out.println("\n");
switch(choice) {
case '1':
System.out.println("The if:\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;");
break;
case '2':
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
break;
case '3':
Riccardo Flask 69 | P a g e
JAVA for Beginners
System.out.println("The for:\n");
System.out.println(" statement;");
break;
case '4':
System.out.println("The while:\n");
System.out.println("while(condition) statement;");
break;
case '5':
System.out.println("The do-while:\n");
System.out.println("do {");
System.out.println(" statement;");
break;
case '6':
System.out.println("The break:\n");
break;
case '7':
System.out.println("The continue:\n");
break;
System.out.println();
Riccardo Flask 70 | P a g e
JAVA for Beginners
Nested Loops
A nested loop is a loop within a loop. The previous examples already included such loops. Another
example to consider is the following:
class FindFac {
public static void main(String args[]) {
for(int i=2; i <= 100; i++) {
System.out.print("Factors of " + i + ": ");
for(int j = 2; j < i; j++)
if((i%j) == 0) System.out.print(j + " ");
System.out.println();
}
}
}
The above code prints the factors of each number starting from 2 up to 100. Part of the output is as
follows:
Factors of 2:
Factors of 3:
Factors of 4: 2
Factors of 5:
Factors of 6: 2 3
Factors of 7:
Factors of 8: 2 4
Factors of 9: 3
Factors of 10: 2 5
Can you think of a way to make the above code more efficient? (Reduce the number of iterations in
the inner loop).
Riccardo Flask 71 | P a g e
JAVA for Beginners
Class Fundamentals
Definition
A class is a sort of template which has attributes and methods. An object is an instance of a class,
e.g. Riccardo is an object of type Person. A class is defined as follows:
class classname {
// declare instance variables
type var1;
type var2;
// ...
type varN;
// declare methods
type method1(parameters) {
// body of method
}
type method2(parameters) {
// body of method
}
// ...
type methodN(parameters) {
// body of method
}
}
The classes we have used so far had only one method, main(), however not all classes specify a main
method. The main method is found in the main class of a program (starting point of program).
class Vehicle {
int passengers; //number of passengers
int fuelcap; //fuel capacity in gallons
int mpg; //fuel consumption
}
Please note that up to this point there is no OBJECT. By typing the above code a new data type is
created which takes three parameters. To create an instance of the Vehicle class we use the
following statement:
Riccardo Flask 72 | P a g e