Java – Jump Statements

break statement

In several instances, such as an error or incorrect input from the user, it may be necessary for the flow of control to exit from a loop statement. To accomplish this, Java provides a jump statement called break statement.

The break statement forces the control to come out from a switch statement, a while loop, a do-while loop or a for loop. After the control moves out of a switch statement or any loop statement, it moves to the statement after the loop or switch statement.

SYNTAX:

break;

The break statement is written as break; without any expression.

Example

Consider a program that prints the value stored in a variable until the specified condition is false. The program ends when the value becomes equal to the value stored in another variable.

'break' statement example

The break statement has been used to enable the program to end when the value in the i variable becoes equal to the value in the num variable. If the value in the i variable is less than 10, the flow of control enters the for loop. When the code is executed, the program displays the numbers from 0 to 3.

Labelled Brake statement

In a nested loop, the break statement used in an inner loop transfers the flow of control to the immediate outer loop. In certain situations, you may also want the flow of control to exit the outer loop. In this case, you use the break statement with the label identifier.

SYNTAX:

break label_name;

The label identifier is used to group a loop statement that contains another loop statement or a switch statement and to specify the name for the group. The label identifier is specified just before a loop statement without any expression like ‘label_name: ‘.

Example

label1:

For example, to name the loop statement label1, you write label1: in the line preceding the loop statement.

When the brake statement is used with the label_name, the flow of control is transferred to the statement after the labeled loop.

Labelled Brake Statement - Example

Consider the code displayed above. that displays the value stored in variable ‘i’ until the condition specified in either of the for loops becomes false. The program terminates if the value of ‘i’ becomes equal to that of ‘num’. In the code shown above, a label statement, ‘label1:’ has been used to group the two for loops.

When the value of the ‘i’ variable becomes equal to the value of the ‘num’ variable, the program executes the labeled brake statement. This transfers the flow of control outside label1. Therefore, the print statement outside the nested for statement is not executed.

HINT: You cannot use the break statement without a switch statement or a loop statement.

Java – Iterative Flow Control

While Statement

Java provides certain loop statements, which you can use to perform an action repeatedly. These statements are called Iterative Statements. One of the loop statements is the while statement.

SYNTAX:

while (condition) {
loopbody
}

The ‘while’ statement contains a condition and a loopbody. The condition is enclosed within parentheses. All the variables used in the condition of the while statement must be initialized before the while loop. The values of the variables used in the condition must be changed in the loopbody. Otherwise, the condition may always remain true and the loop may never end. You change the values of the variables by performing various operations on the variables. You can write a single statement or multiple statements in the loopbody. Multiple statements should be enclosed within braces. Otherwise, the code may generate an unexpected output.

How ‘While’ Works

How While Statement works

Before the loopbody is executed, the condition of the while statement is evaluated. The loopbody is executed only when the condition evaluates to true. Therefore, the while loop is also called a top tested loop. After the loopbody is executed, the while condition is evaluated again. The sequence of the evaluating the condition and executing the loopbody continues until the while condition becomes false.

Example

Lets see a example program that stores two numbers in the variables [Lets say num and n]. The output should display the numbers from 0 to the number stored in the num variable.

In the code displayed below, the while statement specifies the condition that the value of n should be less than or equal to the value of num. Line 1 and Line 5 contain the opening and closing braces of the while loop. In Line 3, the value of n is printed on the screen. In Line 4, the value of n is incremented by 1.

When the program is executed, it displays the numbers from 0 to 5.

In Line 1, the condition is that the value of n should be less than or equal to the value of the variable num. The value of the variable num is 5. The initial value of n is 0, which is less than the value of num. Therefore, the condition is true and the flow of control moves inside the while loop. Inside the loop, the value of the variable n is displayed in the first row. This value is 0. Next, the flow control executes Line 4. As a result, the value of the variable n becomes 1. The flow of control moves back to Line 1, where the value of the variable n is again compared with the value of num. The value of the variable n is 1. Therefore, it is still less than the value of num, which is 5. The condition in Line 1 evaluates again to true, and the flow of control again moves inside the while loop. The value of the variable n is printed in Line 3. This looping continues until the value of n becomes 6. The flow of control moves out of the while loop, and the program terminates.

Infinite While Loops

If a semicolon is added after the condition in the while statement in a program, the program may result in an infinite loop. This is because the control never comes out of the while statement.

For Example:

If we modify the Line 1 of example program like this

while (n <= num); {

the program will result in an infinite loop.

do-while statement

The do-while statement is a loop statement similar to the while statement provided by Java. It is used to perform certain repetitive actions depending on a condition.

SYNTAX:

do {
loopbody
} while (condition);

The do-while statement begins with the ‘do’ keyword followed by the loopbody. In the loopbody, you can write a single statement or multiple statements enclosed within braces. The while statement is written after the closing brace. The while statement contains the condition enclosed in parentheses. In the do-while statement, you add a semicolon after the condition. The semicolon indicates the end of the do-while loop.

How ‘do-while’ Works

The major difference between the do-while statement and the while statement is that in the while statement, the loopbody is executed only when the condition stated in the statement is true. In contrast, the do-while statement in the loopbody is executed at least once, regardless of the condition evaluating to true or false.

'do-while' flow

After the loopbody is executed once, the condition in the do-while statement is checked. If the condition evaluates to true, the loopbody is executed until the condition becomes false. Therefore do-while loop is also called a bottom-tested loop.

You can use the do-while loop in situations where an action must be performed at least once without evaluating the condition.

Example

Consider a program that stores a number in a variable. The program displays all the numbers in descending order starting from the number stored in the variable until it encounters the number 0.

do-while example

The program shown above displays the do keyword and further decrements the value of the count variable that is added. After the count variable is decremented, we specify the condition to check whether the value is equal to 0 like this [while (count != 0);]. The closing brace of the main function and the class declaration is added.

Upon compilation and execution, the output displays all the number from 1 to 4 in descending order.

For Statement

Java provides the for statement to manage iterative actions as an efficient alternative to the while statement. The for statement creates a loop in which a set of statements is repeatedly executed until the specified condition becomes false.

SYNTAX:

for (initialization expressions; test condition; update expressions) {
loopbody;
}

The for statement starts with the ‘for’ keyword. This statement has three elements enclosed within parentheses. The first element of the for statement consists of initialization expressions. This element is an assignment statement. The assignment is done only once before the for statement begins execution. The second element, test condition, is evaluated before each iteration of the for statement. This element determines whether the execution of the for loop should continue or terminate. The third element in the for statement consists of the update expressions. These expressions change the values of the variables used in the test condition. Update expressions are executed at the end of each iteration after the loopbody is executed. The elements of a for statement are seperated by semicolons. You can use multiple statements in the initialization and update expressions of the for statement by seperating them with the comma operator. The multiple statements are evaluated from left to right.

EXAMPLE: Multiple initialization and update expression

for (x = 1, y = 2; test condition; x++, y++) {
loopbody;
}

Another Form

In the for statement, you can omit the initialization expressions and update expressions elements but you must provide two semicolons in the parentheses.

If you are not including the initialization and update expressions elements in the for statement, you must specify the initialization expressions element before the for statement. The update expressions element must then be specified inside the for loop.

SYNTAX:

initialization expressions;

for (; test condition;) {
update expressions;
loopbody;
}

Infinite For Loop

The test condition must be provided in the for statement. If you omit the test condition from the for statement, the program results in an infinite loop when executed. The program will also result in an infinite loop if none of the expressions is specified in the for loop.

SYNTAX:


for (initialization expressions; ; update expressions) {
loopbody;
}

for (;;) {
loopbody;
}

How ‘For’ Works

for (j = 2; j <= 10; j++) {
System.out.println(j);
}

How 'For' Works

In the for loop, the variable j is initialized to 2. Next, the value of j is compared with 10. If the test condition is true, the value of j is displayed on the screen. Next, the value of j is incremented by one. After the value of j is incremented, the test condition is evaluated again. If the test condition evaluates to true, the print function is executed again. If the test condition evaluates to false, the flow of control comes out of the for loop. The for statement creates a loop that is identical in function to the while statement. For loops are more useful when you have a fixed number of iterations and you need a counter. The for loop is also more compact. You can use the for statement to reduce the size of code.

HowTo: Personal Folders in Outlook Express

Outlook Personal Folders can be used to provide additional storage for emails, in order to free up space in your Exchange mailbox on the server.

Remember that the Personal Folders file is stored on your hard disk, so it is your responsibility to back it up regularly, in the same way that you would back up any other file on your computer. They can get very large, so you will probably need to backup to CD.

Installing the Java Development Kit

Java – Conditional Flow Control

If Statement

In certain solutions, it may be necessary to write code to perform various actions based on a user’s inout or certain criteria. To perform these actions, Java provides certain decision-making statements such as the if statement.

You may want to write a program to accept numbers from 0 through 9 from a user. If the number typed is from 0 through 9, it is to be displayed on the screen. Otherwise, a message stating that the typed number is invalid is to be displayed. To perform these actions, you use the if statement.

SYNTAX:

if (expression) {
if_body;
}

The if statement is used to enable the selective execution of statements in a program. The if statement has three forms: the simple if form, the if-else form.

The execution of the if statement involves the evaluation of the specified condition. The evaluated result of the condition is a boolean expression. If the condition evaluates to true, the if_body part of the if statement is executed.

If you want more than one statements to be executed in the if_body part of the if satement, enclose the statements within the braces. You should always use braces on conditional statements even when there is only a single statement. If you use multiple statements in the if_body part without braces, the intented output is not generated. The compiler treats the first statement as the if_body part. The remaining statements are not executed as a part of the if statement.

if (expression); {
statement;
}

Placing a semicolon on the if statement, terminates the statement. The line following the if statement will not be included in the if statement when this is done. Therefore, even if the condition is false, the statement after the if statement will still be executed.

If-else Construct

The simple form of the if statement is inefficient when actions are performed depeneding on whether the result of an expression is true or false. This is why two if statements are needed to handle the two states. In such situations, you use the if-else construct in the code.

SYNTAX:

if (expression) {
if_body;
} else {
else_body;
}

The if-else construct is another form of the if statement. This form can handle both the true and false values of an expression. The syntax of the if-else construct is displayed on the screen. If the expression in the syntax evaluates to true, the if_body part of the statement is executed, otherwise the else_body part is executed.

Fig: Flowdiagram


The flow diagram displayed above illustrates the flow of control in an if-else statement. If the expression evaluates to true, the control executes the if_body. If the expression evaluates to false, the control executes the else_body.

The if-else construct is more efficient than the simple if statement. In the if-else construct, only the if_body part or the else_body part of the code is executed at a time. Both parts are never executed together.

Within the if-else construct, you can use other if statements. The if statements contained within other statements are called nested statements. You can use nested if-else statements to perform actions based on multiple conditions at one time.

Using many nested if-else statement complicates nesting of if statements and can make code difficult to follow. In addition, you should always use braces even when only a single statement is contained in the if clause. This reduces bugs and makes code easier to read.

If-else-if Construct

To perform various actions based on multiple conditions at one time you can use the if-else-if construct. This construct is another form of the if statement.

SYNTAX:

if (expression1) {
body1;
} else if (expression2) {
body2;

….

} else {
bodyN;
}

The body1 and body2 parts of the if-else-if construct indicate the statements that will be executed if the respective conditions evaluate to true. If neither of the conditions evaluates to true, the bodyN part of the if-else-if construct will be executed.

Conditional Operator

The Java language provides an operator to handle situations, where different actions are performed, based on the evaluation of a condition. The conditional operator is used for this task. It is also called the ternary operator, and it is represented by the question mark sign (?) and the colon sign (:). This operator is an efficient alternative to a simple if-else construct.

SYNTAX:

expression1 ? expression2 : expression3;

The expression1 must be a boolean expression. If this condition is true, the expression to the right of the question mark, expression2 is evaluated. If the condition is false, the expression to the right of the colon, expression3 is evaluated.

EXAMPLE:

x=(a>b)?a:b;

Equivalent If-else Construct

if (a>b) {
x = a;
} else {
x = b;
}

switch statement

The switch statement is a conditional statement that branches to various alternative actions. You can use this statement to perform various actions based on the evaluation of a single expression. The switch statement can be used instead of the if-else-if construct if the condition evaluates to an integer value. This integer value must evaluate one of the 32-bit or smaller integer types, such as byte, char, short or int.

SYNTAX:

switch (expression) {
case value 1:
statement1;
break;

case value 2:
statement2;
break;

case value N:
statementN;
break;

default:
statement1;
break;
}

Java Operators

Operator define the actions to be performed on the operands in an expression. Depending on the number of operands on which an operator acts, operators are classified as unary, binary, and ternary operators.

Unary operator act on a single operand. Binary and ternary operators act on two and three operands respectively.

Unary Operator

They are of three types: minus, increment and decrement.

Then minus operator is represented by the minus (-) symbol. It acts on a variable or constant that follows the operator. The minus operator indicated that the value of the operand on which the operator acts is negated. A variable containing a negated value becomes a postive.

Example: -(-6) would be 6.

The increment operator is represented by two plus(++) signs. It causes the value of its operand to be increased by the value 1. The increment operator can be placed before or after the operand. If the increment operator precedes an operand, then the value of the operand will be increased by the value 1 before a statement in a program uses the operand. This type of increment is called prefix increment. [Refer Fig 1.1]

Fig 1.1-Prefix Increment

If the increment operator follows an operand, then the value of the operand is altered after the operand is utilized in a specifix statement in a program. This type of increment operator is called a postfix increment operator. [Refer Fig 1.2]

Fig 1.2-Postfix Increment

The decrement operator is represented by two minus(–) signs. The decrement operator causes an operand to be decreased by the value 1. It can be placed before or after an operand to perform a prefix or postfix decrement operation. The operation of the decrement operator is similar to the increment operator. However, the effect of the decrement operator is to decrease the value of the operand on which it acts.

Arithmetic Operators

To perform arithmetic operations or calculations in a program, you use the arithmetic operators in expressions. The expressions that contain these operators are called arithmetic expressions. There are five arithmetic operators: the slash mark (/), the asterisk (*), the percent sign (%), the plus sign (+), and the minus sign (-). These operators represent division, multiplication, remainder, addition, and subtraction operations respectively.

The operands with which arithmetic operators work must have numeric values. Therefore, operands, or their values can be integers or real numbers.

Arithmetic operators have a specific order of evaluation. This order of evaluation is called precedence. The division, multiplication, and remainder operators belong to one precedence group. The addition and subtraction operators belong to another precedence group. The group of the division, multiplication and remainder operators has precedence over the group of addition and subtraction operators.

When evaluating arithmetic expressions, the order in which consecutive operations occur within the same precedence group is called associativity.

Within each precedence group, the associativity of arithmetic operators is from left to right. The consecutive division, multiplication, and remainder operations are carried out from left to right in the order of their occurrence.

EXAMPLE

12/4*2 = 6
Division is performed first and then multiplication.

15+6-3=18
Both operators + and – belong to the same precedence group, and their associativity is from left to right. In the example, addition is performed first. Next, subtraction is performed.

You can alter the precedence of arithmetic operators by using parentheses. Parentheses have precedence over all arithmetic operators. You can also have nested parentheses in an expression. The innermost parentheses have precedence over the outer parentheses.

EXAMPLE

(8*(x+y))
Here the addition of x and y is carried out first and the sum is then multiplied by the value 8.

HINT:
Operator Precedence = BEDMAS Rule
B – > Brackets [Parentheses]
E – > Exponential
D – > Division
M – > Multiplication
A – > Addition
S – > Subtraction

Assignment Operators

To assign a value to a variable, an assignment operator is used.

SYNTAX:
var = expression

The assignment operator is represented by the equal to symbol (=). A statement that contains the assignment operator is written as var=expression. The variable var stores the value of the expression.

EXAMPLE:
age = 25
total = a + b

In the statement total=a+b, the sum of a and b is assigned to total. Such assignments are called single assignments.

In addition to a single assignment, multiple assignments are also possible in Java. This means that two or more variables can be assigned the same value by using the assignment operator.

EXAMPLE:
var1=var2=10
Assigns the value 10 to the variables var1 and var2.

In addition to the assignment operator, Java has compound assignment operators. These are +=,-=,*=,/= and %=.

Compound assignment operators enable you to write shorthand notation expressions.

EXAMPLE
var1+=var2;
This is equivalent to var1 = var1 + var2;

var1 -= exp ====> Equivalent to var1 = var1 – exp
var1 *= exp ====> Equivalent to var1 = var1 * exp
var1 /= exp ====> Equivalent to var1 = var1 / exp
var1 %= exp ====> Equivalent to var1 = var1 % exp

Assignment operators have right to left associativity. This indicates that in the expressions that contain assignment operators, the expression is evaluated from right to left.

Relational Operators

Relational operators are used for comparing values and taking appropriate actions based on the comparison. For example, a program calculates the levels of the employees in a department by comparing their salaries with different values.

The result of the expression containing a relational operator is either true or false. Relational operators accept two operands.

There are six relational operators in java: greater than (>), less than (<), less than or equal to (<=), greater than or equal to (>=), equal to (==), and not equal to (!=).

EXAMPLE

if (salary < 50000) {
Level = B
}

if (salary >= 50000) {
Level = A
}

If the salary is below $50000 a year, an employee is categorized as a level B employee. If the salary is $50000 or above in a year, the employee is categorized as a level A employee. To determine the level of an employee, the salary of the employee has to be compared with the value 50000.

If the salary of an employee is $50000 and is stored in the variable empSal, the expression empSal<50000 compares the value of empSal with 50000 by using a relational operator.

The equal to and not equal to operators are also called equality operators.

Relational operators have a precedence that determines the order in which they are evaluated in a multiple-operator expression. The operators greater than (>), less than (<), less than or equal to (<=), and greater than or equal to (>=) fall into one precedence group. The equality operators equal to (==) and not equal to (!=) fall into another precedence group. The equality operators have a lower precedence than other relational operators.

The associativity of relational operators is from left to right. Therefore, in an expression that contains more than one relational operator from the same precedence group, the expression is evaluated from left to right.

Logical Operators

Logical operators enable you to combine and compare two conditions

EXAMPLE:

If basePay is below $2000 and above $1000, allowance is 10% of basePay.

This means that an employee receives the allowance only when both these conditions are satisfied. The result of an expression that contains a logical operator is either true or false.

There are six boolean logical operators.

  • Boolean Logical AND – &
  • Boolean Logical OR – |
  • Boolean Logical XOR – ^
  • Conditional AND – &&
  • Conditional OR – ||
  • Boolean Logical NOT – !

In Java, there are two short-circuit logical operators. These are Conditional AND (&&) and Conditional OR (||). Java does not evaluate the operand on the right when the result can be determined by the operand on the left only. This can be important when there are side affects from the operand on the right.

The &&,||,&,| and ^ are binary operators. The ! operator is a unary operator.

Associativity relates to precedence and resolves any ambiguity over the grouping of operators with the same precedence. The associativity of the &&,||,&,|, and ^ operators is from left to right.

The && operator evaluates two subexpressions, Op1 and Op2, and generates the value true only if both the subexpressions individually evaluate to true. The result of the expression that combines the expressions oP1 and oP2 by using the && operator is false if either oP1 or oP2 evaluates to false.

If two expressions, op1 and op2 are combined using the || operator, the result of the combined expression is true if either op1 or op2 evaluates to true.

The ! operator negates the value of an expression. This indicates if the value of an expression op1 is true initially, the ! operator alters its value to false. If the value of an experssion, op1 is originally false, the ! operator alters the value to true.

The & operator works the same as the && operator, except that the operand on the right is always evaluated. The expression evaluates to true only if both of the operands are true.

The | operator works the same as the || operator, except that the operand on the right is always evaluated. The expression evaluates to true if either of the operands are true.

The ^ operator is the exclusive OR (XOR) operator. The expression evaluates to true if only one of the operands is true. If both operands are false or both operands are true, the expression will evaluate to false.

Bitwise Operators

It enables you to calculate the result of an expression by using the individual bits of the operands in the expression. There are four bitwise operators in Java: AND, OR, XOR, and NOT. These operators are represented by the symbols &, |, ^, and ~ respectively. The AND, OR, and XOR operators are binary operators. The NOT operator is a unary operator.

The AND operator evaluates the binary equivalent of the two operands, op1 and op2 and generates 1 if the value of both the operands is 1. If the value of any of the operands is 0, the result is 0.

The OR operator results in the value 0 when the value of both the bits is 0. Otherwise, the result of the OR operation is the value 1.

The XOR operator is an exclusive OR operator. This operator results in the value 1 if the two operand bits are different. Otherwise, the result of the XOR operation is the value 0.

In addition to the bitwise operators, some shortcut assignment operators perform bitwise operations. These assignment operators are &=, |=, ^=.

The &= shortcut assignment operator works the same as & operator and the results are assigned to op1. If the value of the corresponding bits in both operands is 1, then the operator generates a result of 1, otherwise the result is 0.

The |= shortcut assignment operator works the same as | operator and results are assigned to op1. If the value of the either, or both of the corresponding bits in both operands is 1, then the operator generates a result of 1, otherwise the result is 0.

The ^= shortcut assignment operator works the same as ^ operator and the results are assigned to op1. If the value of only one of the corresponding bits in both operands is 1, then the operator generates a result of 1. If both of the corresponding bits are 0 or 1, the result is 0.

Related Posts: Introduction to Java | Classes, Methods & Objects | Objects and Variables | Datatypes | Conditional Flow Control | Iterative Flow Control | Jump Statements

Introduction to Java

Java is the key to developing platform-independant programs. Therefore, it is the ideal option when diverse hardware platforms and OSs need to be supported.

GOSSIP:
Java was designed at Sun Microsystems, Inc in 1991 and was initially called Oak. It was renamed Java in 1995.

Java was designed to be compatible with different platforms used by computers connected to the Internet. The compiled code of a Java Program can be executed on different platforms without any changes. This is possible because of bytecode that is generated during the compilation of source code. Bytecode is a highly optimized set of instructions that is executed by the Java run-time system called Java Virtual Machine (JVM). The JVM acts as an interpreter for bytecode.

Java Source Files


Fig 1.1 – Java Source Files

A Java source file contains three sections. The first setion is the package section that contains a single line of code that specifies the package to while the source file belongs. The package statement may be omitted, in which case the default package will be assumed.

The second section is the import section. This section includes import statements that tell the compiler which packages to include. The import section may be omitted. The compiler will automatically import the java.lang.package that includes the most commonly used Java classes and interfaces.

The third section includes the class or interface definition. This is where all of the remaining Java code for the source file will be placed. There can only be one top-level public class or a single public interface defined in a source file.

A Java source file must be named with the same name as the top-level class or interface, if that top level class or interface is defined as public. The extension .java is appended to the name to form the source file name. In our example, it would be HelloWorld.java

Java Compiler ignores extra white spaces. So you can use..hell lots of space to make your code more readable.

Comments are used to annotate the code. The compiler will strip the comments from the code during compilation. It is a good idea to use comments to explain code that may be confusing. Comments are also used for producing Javadoc documentation such as the Java API reference.

There are two types of comments that can be coded into a Java source file.

Type 1: Multiple line comments

Syntax:
/* blah blah blag */

Example:
/*
Blah
Blah
*/

Type 2: End-of-line comment

Syntax:
// Blah

Hello World Program

Java Keywords

Related Post: Classes, Methods & Objects | Objects and Variables | Datatypes | Operators | Conditional Flow Control | Iterative Flow Control | Jump Statements