Friday, 29 May 2015

Java continue Statement

The general form of simple continue statement is:

continue;

The unlabeled continue statement can be used inside loops (for, while and do-while) only. It prematurely stops the current iteration of the loop body and proceeds with the next iteration, if possible.

In the case of while and do-while loops, the rest of the body is skipped and the execution continues with the loop condition. In the case of for loop, the rest of the body is skipped and the execution continues with the increment/decrement expression.

This is similar to continue statement in C/C++.

Example: The linear search program is rewritten to make use of the continue statement.

import java.util.*;

class LinearSearch

{ public static void main(String args[]) throws IOException

{ int n, x, a[]; boolean found = false; String number;

Buffered Reader in

= new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter the number of elements in the array: ");

number = in.readLine(); n = Integer.parseInt(number);

a = new int[n];

for(int i = 0; i < n; i++)// read the array elements

{ number = in.readLine();

a[i] = Integer.parseInt(number);

}

System.out.print("Enter the element to be searched in the array: ");

number = in.readLine(); x = Integer.parseInt(number);

int i = 0;

while(i < n && !found) // search the specified element

{

if(x = =  a[i]) // simple if statement

{

found = true;

continue;

}

i++;

}

if(found) // if-else statement

System.out.println("The number " + x + " is present in the list");

else

System.out.println("The number " + x + " is not in the list");
}
}

labeled continue Statement

The syntax of the labeled continue statement is as follows:

continue  <label>;

The labeled continue statement specifies the label of the enclosing loop to continue. The label need not correspond to the closest enclosing loop.

Example: The matrix search program is rewritten here to make use of the continue statement.

import java.util.*;

class SearchMatrix1

{ public static void main(String args[]) throws IOException

{

int i, j, x, row, col , matrix[][];  String number;  boolean found = false;

Buffered Reader in = new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter the number of rows in the matrix: ");

number = in.readLine(); row = Integer.parseInt(number);

System.out.print("Enter the number of columns in the matrix: ");

number = in.readLine(); col = Integer.parseInt(number);

matrix = new int[row][col];

for(i = 0; i < row; i++) //enter one element in one line

{

System.out.println("enter the elements of row " + (i+1));

for(j = 0; j < col; j++)

{ number = in.readLine();

}

}

System.out.print("Enter the element to be searched in the matrix: ");

number = in.readLine();

x = Integer.parseInt(number);

outerloop: for(i = 0; i < row && !found; i++)

{ for(j = 0; j < col; j++)

{ if(matrix[i][j] == x)

{ found = true;

continue outerloop;

}

}

}

// break will transfer control to the following statement

if(found)

System.out.println("The number "+ x + " is present in the matrix");

else

System.out.println("The number " + x + " is not in the matrix");

}

}

Java Jump Statements

Jump statements are used for breaking the control flow. Java supports the following jump statements:

  • break
  • labeled break
  • continue
  • labeled continue
  • return
Beside this the constructs used for exception handling can also be put into this category but they are discussed in a separate chapter.

break Statement

The general form of simple break statement is:

break;

The unlabeled break statement can be used inside loops (for, while and do-while) and switch statements. It terminates the containing statement and transfers the control outside the closest enclosing loop or switch statement. The rest of containing statement body is skipped and the execution continues after the containing statement.

This is similar to break statement in C/C++. Refer to examples of simple-if statement and switch statement discussed above for the use of break statement.

labeled break Statement

The syntax of the labeled break statement is as follows:

break  <label>;

The labeled beak statement is used to terminate the block whose label is specified in the break statement. Unlike simple break statement, you can terminate any block. For example, it is possible to terminate the outermost loop from inside a deeply nested for loop.

The break statement can also be used to terminate a simple block (i.e. the block need not be a loop or switch statement)

Example: The following program searches for a given element inside a matrix (2-D array) and makes use of the labeled break statement to come out of the outermost for loop as soon as the element is found.

import java.util.*;

class SearchMatrix

{ public static void main(String args[]) throws IOException

{ int i, j, x, row, col , matrix[][];

String number;

boolean found = false;

Buffered Reader in

= new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter the number of rows in the matrix: ");

number = in.readLine();

row = Integer.parseInt(number);

System.out.print("Enter the number of columns in the matrix: ");

number = in.readLine();

col = Integer.parseInt(number);

matrix = new int[ row][col];

for(i = 0; i < row; i++) //enter one element in one line

{ System.out.println("enter the elements of row " + (i+1));

for(j = 0; j < col; j++)

{ number = in.readLine();

}

}

System.out.print("Enter the element to be searched : ");

number = in.readLine();

x = Integer.parseInt(number);

outerloop: for(i = 0; i < row; i++)

matrix[i][j]= Integer.parseInt(number);

{

for(j = 0; j < col; j++)

{

if(matrix[i][j] == x)

{ found = true;

}

 break outerloop;
}

}
}
if(found)

System.out.println("The number "+ x + " is present");

else

System.out.println("The number " + x + " is not present");
}
}

The use of labeled break statement in the above program is a substitute of the labeled goto statement of C/C++. This is a better alternative, as the program is more readable hence the labeled break is referred to as the civilized form of goto statement.

Java Iteration Statements (Loop Control Structure)

The Java supports the while, do-while and for iteration/loop control statements. The syntax is similar to C/C++. With JDK1.5, a second form of for was added that implements a “for-each” style loop.

while Statement

The general form of a while statement is:

while(condition)

loop body

Loop body may contain one or more statements. If loop body contains more than one statement then they must be enclosed between braces.

Example: The following program accepts one natural number say n as command line argument and then calculates and displays the sum of first n natural numbers.

class SumNaturalNumbers

{

public static void main(String a[])

{ int n, sum=0;

n = Integer.parseInt(a[0]); //command line argument

int i = 1;

sum = 0;

while (i <= n)

{

sum = sum + i;

i  = i + 1;

}

System.out.println("Sum of first " + n + " natural numbers is " + sum);

}

}

do-while Statement

The general form of a do-while statement is:

do

{

} while (condition)

loop body

Example: The following program accepts one integer number say n as command line argument and then calculates and displays the sum of its digits.

class SumOfDigits

{ public static void main(String a[])

{ int n, m, sum, digit;

n = Integer.parseInt(a[0]); //command line argument

m = n;

if(m < 0)

m = -m;

sum = 0;

do

{ digit = m % 10;

sum = sum + digit;

m = m / 10;

}while (m > 0);

System.out.println("Sum of digits of number " + n + " is: " + sum);

}

}

for Statement

The general form of a for statement is:

for(initialization; condition; increment/decrement)

loop body

Loop body may contain one or more statements. If loop body contains more than one statement then they must be enclosed between braces.

Example: The following program accepts one natural number say n as command line argument

and then calculates and displays the sum of first n natural numbers.

class SumNaturalNumbers1

{ public static void main(String a[])

{ int i, n, sum;

n = Integer.parseInt(a[0]); //command line argument

for(i = 1, sum = 0; i <= n; i++)

{

sum = sum + i;

}

System.out.println("Sum of first " + n + " natural numbers is " + sum);
}
}


Java Selection Statements (Decision Control Structure)

Java supports the following selection statements:

  • simple if Statement
  • if-else Statement
  • nested-if Statement
  • if-else-if Ladder
  • switch Statement

The syntax of these statements is same as in C/C++ so we will be discussing in details only if there is some difference from C/C++.

Simple if Statement

The syntax of the simple if statement is:

if (condition)
Statement;

if-else Statement

The syntax of the if-else statement is

if(condition)
   Statement1;
else
   Statement2;

Example: The following program illustrates the use of simple if statement as well as if-else statement. The program reads elements in an array of type int, followed by the element to be searched in the array using the linear search method. The program then displays the suitable message according to the search result.

import java.util.*;

class LinearSearch

{ public static void main(String args[]) throws IOException

{ int n, x, a[]; boolean found = false;

String number;

Buffered Reader in

System.out.print("Enter the number of elements in the array: ");

number = in.readLine();

n = Integer.parseInt(number);

a = new int[n];

for(int i = 0; i < n; i++) // read the array elements

{ number = in.readLine(); // enter only one element in one line

}

System.out.print("Enter the element to be searched in the array: ");

number = in.readLine();

x = Integer.parseInt(number);

for(int i = 0; i < n; i++) // search the specified element

{

}

if(found) // if-else statement

else

}

}

nested-if Statement

Any type of if statement may appear in the if or else part of another if statement. The rules for nesting are same as in C/C++. The following example illustrates the use of nested-if statement.

Example: The following program finds the largest among three given numbers.

import java.util.*;

class LargestOfThree

{ public static void main(String args[]) throws IOException

{ int a,b,c,max;  String number;

Buffered Reader in

System.out.print("Enter the first number : ");

number = in.readLine(); a = Integer.parseInt(number);

System.out.print("Enter the second number : ");

number = in.readLine(); b = Integer.parseInt(number);

System.out.print("Enter the third number : ");

number = in.readLine(); c = Integer.parseInt(number);

if(a > b)

else

System.out.println("Maximum among "+a+","+b+","+c+" is:"+max);

}

}

if-else-if Ladder

The syntax of the if-else-if ladder statement is as follows:

if(condition)
  Statement;
else if (condition)
  Statement;
else if (condition)
  Statement;
else
  Statement;

Example: The following program demonstrates the use of if-else-if ladder. The program reads

the weekday as an integer and displays corresponding weekday.

import java.util.*;

class DisplayWeekDay

{ public static void main(String args[]) throws IOException

{ int weekDay;

Buffered Reader in = new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter the day of week (1 to 7) : ");

number = in.readLine(); weekDay = Integer.parseInt(number);

if (weekDay == 1)

System.out.println("Sunday");

else if(weekDay == 2)

System.out.println("Monday");

else if(weekDay == 3)

System.out.println("Tuesday");

else if(weekDay == 4)

System.out.println("Wednesday");

else if(weekDay == 5)

System.out.println("Thursday");

else if(weekDay == 6)

System.out.println("Friday");

else if(weekDay == 7)

System.out.println("Saturday");

else

System.out.println("Valid values are from 1 to 7");

}

}

switch Statement

The switch statement is a multi-way branch statement. Its syntax is as follows:

switch(expression)

{ case label-1: Statement Sequence

case label-2 : Statement Sequence

[break;]

[break;]

case label-n: Statement Sequence

default: Statement Sequence

[break;]

[break;]

}

The syntax is same as in C/C++, with the following differences:

(i) In Java, switch expression can be any integer expression except long i.e. the type of the switch expression can be byte, short, char or int. But the Java’s int is of 4 bytes which is same as size of long in C/C++.

(ii) The case labels are constant expressions as in C/C++ but the values of the case labels must be in the range of the type of the switch expression otherwise the program will not compile. For example, if switch expression is of type byte then the valid values for case labels are from –128 to 127.

Example: The following program demonstrates the use of switch statement. The program reads the weekday as an integer and displays the corresponding weekday in character form.

import java.util.*;

class DisplayWeekDay1

{ public static void main(String args[]) throws IOException

{ int weekDay;

String number;

Buffered Reader in

= new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter the day of week (1 to 7) : ");

number = in.readLine();

weekDay = Integer.parseInt(number);

switch(weekDay)

{

case 1: System.out.println("Sunday");

case 2: System.out.println("Monday");

case 3: System.out.println("Tuesday");

case 4: System.out.println("Wednesday");

case 5: System.out.println("Thursday");

case 6: System.out.println("Friday");

break;

break;

break;

break;

break;

break;

case 7: System.out.println("Saturday");

break;

default:

System.out.println("Valid values are from 1 to 7");

}
}
}

Java Control Statements

Control statements are used to change the flow of execution. Java’s control statements can be classified into three categories:

  • Selection Statements (Decision Control Structure)
  • Iteration Statements (Loop Control Structure)
  • Jump statements

Most of the statements have same syntax as the corresponding statements in C/C++. However there are some significant differences:

(i) The conditional expressions used in the if, for, while and do statements must be valid boolean expressions i.e. their values should be either true or false. You cannot use 0 (Zero) instead of false or a non-zero value instead of true that is valid in C/C++.

(ii) Java does not have any goto statement although goto is a reserved word in the language. Java provides labeled break and labeled continue statements, which are often referred to as the civilized form of goto as they are supposed to be better substitutes of goto statement.