[go: up one dir, main page]

0% found this document useful (0 votes)
63 views20 pages

File 4

This document discusses using break and continue statements in Java loops. It provides examples of using break to terminate a loop early, including nested loops and labeled breaks. It also discusses using continue to skip the remaining code in the current loop iteration. Labeled breaks allow breaking out of an outer loop by specifying a label. The break statement affects only the innermost loop it appears in, while continue skips to the next iteration of the current loop.

Uploaded by

shekharc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views20 pages

File 4

This document discusses using break and continue statements in Java loops. It provides examples of using break to terminate a loop early, including nested loops and labeled breaks. It also discusses using continue to skip the remaining code in the current loop iteration. Labeled breaks allow breaking out of an outer loop by specifying a label. The break statement affects only the innermost loop it appears in, while continue skips to the next iteration of the current loop.

Uploaded by

shekharc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

JAVA for Beginners

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;");

System.out.println("} while (condition);");

break;

Riccardo Flask 61 | P a g e
JAVA for Beginners

Using Break to Terminate a Loop

One can use the ‘break’ command to terminate voluntarily a loop. Execution will continue from the
next line following the loop statements,

e.g. 1 Automatic termination (hard-coded)

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.

e.g. 2 Termination via user intervention

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

// Using break with nested loops

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:

Outer loop count: 0


Inner loop count: 0 1 2 3 4 5 6 7 8 9
Outer loop count: 1
Inner loop count: 0 1 2 3 4 5 6 7 8 9
Outer loop count: 2
Inner loop count: 0 1 2 3 4 5 6 7 8 9
Loops complete.

Terminating a loop with break and use labels to carry on execution

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.

// Using break with labels.

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

System.out.println("After block three."); three


}
System.out.println("After block two."); two
}
System.out.println("After block one."); one
}

//the following statement executes on termination of the


for loop
System.out.println("After for.");
}
}

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:

class BreakErr { This break cannot


public static void main(String args[]) {
one: for(int i=0; i<3; i++) {
continue from the
System.out.print("Pass " + i + ": "); assigned label since it
} is not part of the same
for(int j=0; j<100; j++) {
if(j == 10) break one; block
System.out.print(j + " ");
}
}
}

Use of Continue (complement of Break)

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:

Outer loop pass 1, Inner loop: 1234


Outer loop pass 2, Inner loop: 1234
Outer loop pass 3, Inner loop: 1234
Outer loop pass 4, Inner loop: 1234
Outer loop pass 5, Inner loop: 1234
Outer loop pass 6, Inner loop: 1234
Outer loop pass 7, Inner loop: 1234
Outer loop pass 8, Inner loop: 1234
Outer loop pass 9, Inner loop: 1234

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

Mini-Project 3 Java Help System (Help3.java)


This project puts the finishing touches on the Java help system that was created in the previous
projects. This version adds the syntax for ‘break’ and ‘continue’. It also allows the user to request the
syntax for more than one statement. It does this by adding an outer loop that runs until the user
enters ‘q’ as a menu selection.

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 {

public static void main(String args[])

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");

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');

if(choice == 'q') break;

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(" case constant:");

System.out.println(" statement sequence");

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.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;");

System.out.println("} while (condition);");

break;

case '6':

System.out.println("The break:\n");

System.out.println("break; or break label;");

break;

case '7':

System.out.println("The continue:\n");

System.out.println("continue; or continue label;");

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).

The Vehicle Class


The following is a class named ‘Vehicle’ having three attributes, ‘passengers’ – the number of
passengers the vehicle can carry, ‘fuelcap’ – the fuel capacity of the vehicle and ‘mpg’ – the fuel
consumption of the vehicle (miles per gallon).

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:

Vehicle minivan = new Vehicle ();

To set the values of the parameters we use the following syntax:

minivan.fuelcap = 16; //sets value of fuel capacity to 16

Riccardo Flask 72 | P a g e
JAVA for Beginners

Note the general form of the previous statement: object.member

Using the Vehicle class


Having created the Vehicle class, let us create an instance of that class:

class VehicleDemo {

public static void main(String args[]) {

Vehicle minivan = new Vehicle();

int range;

// assign values to fields in minivan

minivan.passengers = 7;

minivan.fuelcap = 16;

minivan.mpg = 21;

Till now we have created an instance of Vehicle called ‘minivan’ and assigned values to passengers,
fuel capacity and fuel consumption. Let us add some statements to work out the distance that this
vehicle can travel with a tank full of fuel:

// compute the range assuming a full tank of gas

range = minivan.fuelcap * minivan.mpg;

System.out.println("Minivan can carry " +


minivan.passengers + " with a range of " + range);
}
}

Creating more than one instance


It is possible to create more than one instance in the same program, and each instance would have
its own parameters. The following program creates another instance, sportscar, which has different
instance variables and finally display the range each vehicle can travel having a full tank.

class TwoVehicles {
public static void main(String args[]) {
Vehicle minivan = new Vehicle();
Vehicle sportscar = new Vehicle();

int range1, range2;


// assign values to fields in minivan
minivan.passengers = 7;
minivan.fuelcap = 16;
minivan.mpg = 21;

Riccardo Flask 73 | P a g e
JAVA for Beginners

// assign values to fields in sportscar


sportscar.passengers = 2;
sportscar.fuelcap = 14;
sportscar.mpg = 12;

// compute the ranges assuming a full tank of gas


range1 = minivan.fuelcap * minivan.mpg;
range2 = sportscar.fuelcap * sportscar.mpg;
System.out.println("Minivan can carry " +
minivan.passengers +
" with a range of " + range1);
System.out.println("Sportscar can carry " +
sportscar.passengers +
" with a range of " + range2);
}
}

Creating Objects
In the previous code, an object was created from a class. Hence ‘minivan’ was an object which was
created at run time from the ‘Vehicle’ class – vehicle minivan = new Vehicle( ) ; This statement
allocates a space in memory for the object and it also creates a reference. We can create a
reference first and then create an object:

Vehicle minivan; // reference to object only


minivan = new Vehicle ( ); // an object is created

Reference Variables and Assignment


Consider the following statements:

Vehicle car1 = new Vehicle ( );

Vehicle car2 = car 1;

We have created a new instance of type Vehicle named car1. However note that car2 is NOT
another instance of type Vehicle. car2 is the same object as car1 and has been assigned the same
properties,

car1.mpg = 26; // sets value of mpg to 26

If we had to enter the following statements:

System.out.println(car1.mpg);

System.out.println(car2.mpg);

The expected output would be 26 twice, each on a separate line.

Riccardo Flask 74 | P a g e
JAVA for Beginners

car1 and car2 are not linked. car2 can be re-assigned to another data type:

Vehicle car1 = new Vehicle();

Vehicle car2 = car1;

Vehicle car3 = new Vehicle();

car2 = car3; // now car2 and car3 refer to the same object.

Methods
Methods are the functions which a particular class possesses. These functions usually use the data
defined by the class itself.

// adding a range() method

class Vehicle {

int passengers; // number of passengers

int fuelcap; // fuel capacity in gallons

int mpg; // fuel consumption in miles per gallon

// Display the range.

void range() {

System.out.println("Range is " + fuelcap * mpg);

Note that ‘fuelcap’ and ‘mpg’ are called directly without the dot (.) operator. Methods take the
following general form:

ret-type name( parameter-list ) {

// body of method

‘ret-type’ specifies the type of data returned by the method. If it does not return any value we write
void. ‘name’ is the method name while the ‘parameter-list’ would be the values assigned to the
variables of a particular method (empty if no arguments are passed).

class AddMeth {

public static void main(String args[]) {

Riccardo Flask 75 | P a g e
JAVA for Beginners

Vehicle minivan = new Vehicle();

Vehicle sportscar = new Vehicle();

int range1, range2;

// assign values to fields in minivan

minivan.passengers = 7;

minivan.fuelcap = 16;

minivan.mpg = 21;

// assign values to fields in sportscar

sportscar.passengers = 2;

sportscar.fuelcap = 14;

sportscar.mpg = 12;

System.out.print("Minivan can carry " +


minivan.passengers + ". ");

minivan.range(); // display range of minivan

System.out.print("Sportscar can carry " +


sportscar.passengers + ". ");

sportscar.range(); // display range of sportscar.

}
}

Returning from a Method


When a method is called, it will execute the statements which it encloses in its curly brackets, this is
referred to what the method returns. However a method can be stopped from executing completely
by using the return statement.

void myMeth() {

int i;

for(i=0; i<10; i++) {

if(i == 5) return; // loop will stop when i = 5

System.out.println();

}
}

Riccardo Flask 76 | P a g e
JAVA for Beginners

Hence the method will exit when it encounters the return statement or the closing curly bracket

There can be more than one exit point in a method depending on particular conditions, but one
must pay attention as too many exit points could render the code unstructured and the program will
not function as desired (plan well your work).

void myMeth() {

// ...

if(done) return;

// ...

if(error) return;

Returning a Value
Most methods return a value. You should be familiar with the sqrt( ) method which returns the
square root of a number. Let us modify our range method to make it return a value:

// Use a return value.

class Vehicle {

int passengers; // number of passengers

int fuelcap; // fuel capacity in gallons

int mpg; // fuel consumption in miles per gallon

// Return the range.

int range() {

return mpg * fuelcap; //returns range for a


particular vehicle

Please note that now our method is no longer void but has int since it returns a value of type
integer. It is important to know what type of variable a method is expected to return in order to set
the parameter type correctly.

Riccardo Flask 77 | P a g e
JAVA for Beginners

Main program:

class RetMeth {

public static void main(String args[]) {

Vehicle minivan = new Vehicle();

Vehicle sportscar = new Vehicle();

int range1, range2;

// assign values to fields in minivan

minivan.passengers = 7;

minivan.fuelcap = 16;

minivan.mpg = 21;

// assign values to fields in sportscar

sportscar.passengers = 2;

sportscar.fuelcap = 14;

sportscar.mpg = 12;

// get the ranges

range1 = minivan.range();

range2 = sportscar.range();

System.out.println("Minivan can carry " +


minivan.passengers + " with range of " + range1 + "
Miles");

System.out.println("Sportscar can carry " +


sportscar.passengers + " with range of " + range2 +
" miles");

Study the last two statements, can you think of a way to make them more efficient, eliminating the
use of the two statements located just above them?

Riccardo Flask 78 | P a g e
JAVA for Beginners

Methods which accept Parameters:


We can design methods which when called can accept a value/s. When a value is passed to a
method it is called an Argument, while the variable that receives the argument is the Parameter.

// Using Parameters.
The method accepts a
class ChkNum { value of type integer, the
parameter is x, while the
// return true if x is even argument would be any
value passed to it
boolean isEven(int x) {

if((x%2) == 0) return true;

else return false;

class ParmDemo {

public static void main(String args[]) {

ChkNum e = new ChkNum();

if(e.isEven(10)) System.out.println("10 is even.");

if(e.isEven(9)) System.out.println("9 is even.");

if(e.isEven(8)) System.out.println("8 is even.");

Predicted Output:

10 is even.

8 is even.

A method can accept more than one parameter. The method would be declared as follows:

int myMeth(int a, double b, float c) {

// ...

Riccardo Flask 79 | P a g e
JAVA for Beginners

The following examples illustrates this:

class Factor {

boolean isFactor(int a, int b) { Note that these


statements are validating
if( (b % a) == 0) return true; ‘x’, and print the correct
else return false; statement.

class IsFact {

public static void main(String args[]) {

Factor x = new Factor();

if(x.isFactor(2, 20)) System.out.println("2 is a


factor.");

if(x.isFactor(3, 20)) System.out.println("this won't be


displayed");

Predicted Output:

2 is a factor.

If we refer back to our ‘vehicle’ example, we can now add a method which works out the fuel
needed by a particular vehicle to cover a particular distance. One has to note here that the result of
this method, even if it takes integers as parameters, might not be a whole number.

Therefore one has to specify that the value that the method returns, in this case we can use
‘double’:

double fuelneeded(int miles) {

return (double) miles / mpg;


}

Riccardo Flask 80 | P a g e

You might also like