Loop control
There may be a situation when we need to execute a block of code several times, often referred to as a loop.
Java has a very flexible three-loop mechanism. You can use one of the following three loops:
- While loop
- Do...while Cycle
- For loop
As of JAVA5, an enhanced for loop was introduced. This is primarily used for arrays.
While loop
a while loop is a control structure that can repeat the number of specific tasks.
Grammar
The syntax for the while loop is:
while (Boolean_expression)
{
//statements
}
At execution time, if the result of a Boolean expression is true, the action in the loop is executed. As long as the result of the expression is true, execution will continue.
Here, the key point of the while loop is that the loop may not run forever. When the expression is tested, the result is false, the loop body is skipped, and the first statement after the while loop is executed.
Example
public class Test {public
static void Main (String args[]) {
int x = ten;
while (x <) {
System.out.print ("Value of x:" + x);
x + +;
System.out.print ("\ n");}}
This will produce the following results:
Value of X:10
value of x:11
value of x:12
value of x:13
value of x:14
value of x:15
VA Lue of x:16 value of
x:17
value of x:18 value of
x:19
Do...while Cycle
do ... while loops are similar to a while loop, unlike a do ... while loop is guaranteed to execute at least once.
Grammar
The syntax for Do...while loops is:
Do
{
//statements
} while (Boolean_expression);
Note that the Boolean expression appears at the end of the loop, so the statement in the loop executes the previous Boolean test.
If the Boolean expression is true, the control flow jumps back and the statement in the loop executes again. This process is repeated until the Boolean expression is false.
Example
public class Test {public
static void Main (String args[]) {
int x = ten;
do{
System.out.print ("Value of x:" + x);
x + +;
System.out.print ("\ n");
} while (x <);
}
}
This will produce the following results:
Value of X:10
value of x:11
value of x:12
value of x:13
value of x:14
value of x:15
VA Lue of x:16 value of
x:17
value of x:18 value of
x:19
For loop
A For loop is a circular control structure that effectively writes a specific number of loops that need to be performed.
The For loop is good when you know how many times a task is to be repeated.
Grammar
The syntax for the For loop is:
for (initialization; Boolean_expression; Update)
{
//statements
}
The following is a for loop control process:
The initialization step is executed first and only once. This step can declare and initialize any loop control variable. You don't need to put a declaration here, just a semicolon appears.
Next, the Boolean expression is evaluated. If true, the loop body is executed. If False, the loop body does not execute, and the process controls the jump to the next statement that passes through the for loop.
After the loop body executes in the For loop, the control process jumps back to the UPDATE statement. This statement allows you to update any loop control variable. This statement can be left blank, as long as a semicolon appears after the Boolean expression.
The Boolean expression now evaluates the calculation again. If true, loop through and repeat the process (the loop body, and then the updated step, then the Boolean expression). After the Boolean expression is False, the loop terminates.
Example
public class Test {public
static void Main (String args[]) {for
(int x = x < x = x+1) {
System.out. Print ("Value of x:" + x);
System.out.print ("\ n");}}
This will produce the following results:
Value of X:10
value of x:11
value of x:12 value of x:13 value of
x:14
15/>value of x:16 value of
x:17
value of x:18 value of
x:19
For-loop new features in Java
as of JAVA5, an enhanced for loop was introduced. This is primarily used for arrays.
Grammar
The syntax for the enhanced for loop is:
for (declaration:expression)
{
//statements
}
Declaration: New Declaration block variable, which is a variable that is compatible with the elements in the array you are accessing. The variable can be exploited within a for block and its value as the current array element will be the same.
Expression: The result of this calculation requires a cyclic array. An expression can be an array variable or a method call that returns an array.
Example
public class Test {public
static void Main (String args[]) {
int [] numbers = {A, m, n};
for (int x:numbers) {
System.out.print (x);
System.out.print (",");
}
System.out.print ("\ n");
String [] Names ={"James", "Larry", "Tom", "Lacy"};
for (String name:names) {
System.out.print (name);
System.out.print (",");}}
This will produce the following results:
10,20,30,40,50,
james,larry,tom,lacy,
Break keyword
The keyword break is used to stop the entire loop. The break keyword must be used in any loop or in a switch statement.
The keyword break stops execution of the most inner loop and begins executing the next line of code after the block.
Grammar
The break syntax is a separate statement in any loop:
Copy Code code as follows:
Example
public class Test {public
static void Main (String args[]) {
int [] numbers = {A, m, n};
for (int x:numbers) {
if (x = =) {break
;
}
System.out.print (x);
System.out.print ("\ n");}}
This will produce the following results:
Continue keyword
The Continue keyword can be used in the control structure of any loop. It causes the loop to immediately jump to the next iteration of the loop.
In the For loop, the Continue keyword causes the control flow to immediately jump to the UPDATE statement.
In a while loop or Do/while loop, the control flow immediately jumps to the Boolean expression.
Grammar
The continue syntax is a separate statement in any loop:
Copy Code code as follows:
Example
public static void Main (String args[]) {
int [] numbers = {A, m, n};
for (int x:numbers) {
if (x = =) {
Continue
}
System.out.print (x);
System.out.print ("\ n");}}
This will produce the following results:
Conditional judgment
There are two types of conditional judgment statements in Java, respectively:
- If statement
- Switch statement
If statement:
An If statement consists of a Boolean expression followed by one or more statements.
Grammar
The syntax for the IF statement is:
if (boolean_expression)
{
//statements'll execute if the Boolean expression is true
}
If the Boolean expression evaluates to True, the block if statement inside the code is executed. If not true, the first set of code after the IF statement (after curly braces) is executed.
Example
public class Test {public
static void Main (String args[]) {
int x = ten;
if (x <) {
System.out.print ("This is if Statement");}
}
This will produce the following results:
If...else statement
Any if statement can be followed by an optional else statement, and when the Boolean expression is false, the statement is executed.
Grammar
The syntax for If...else is:
if (boolean_expression) {
//executes when the Boolean expression was true
}else{
//executes when the Boolean expression is false
}
Example
public class Test {public
static void Main (String args[]) {
int x =;
if (x <) {
System.out.print ("This is if statement");
} else{
System.out.print ("This is Else Statement");}}
This will produce the following results:
If...else If...else Statement
if the following can be followed by an optional else if...else statement, it is useful to test a single if statement and an else if statement under different conditions.
There are a few things to keep in mind when using the IF, else if, or else statement.
- An if statement can have 0 or one else statements and it must be after the else if statement.
- An if statement can have 0 or more else if statements and they must precede the else statement.
- If the else if statement succeeds, the remaining else if statement or else statement will not be executed by the test.
Grammar
The syntax for If...else is:
if (Boolean_expression 1) {
//executes when the Boolean expression 1 is true
}else if (boolean_expression 2) {
/ /executes when the Boolean expression 2 are true
}else if (boolean_expression 3) {
//executes when the Boolean expres Sion 3 is True
}else {
//executes ' the none of the above condition is true.
}
Example
public class Test {public
static void Main (String args[]) {
int x =;
if (x = =) {
System.out.print ("Value of X");
} else if (x = =) {
System.out.print ("Value of X is");
} else if (x = =) {
System.out.print ("Value of X is");
} else{
System.out.print ("This is Else Statement");}}
This will produce the following results:
Nested IF...ELSE statement
It is always a valid nested If-else statement, which means that you can use an if or else if statement in another if or else if statement.
Grammar
The syntax for nesting if...else is as follows:
if (Boolean_expression 1) {
//executes when the Boolean expression 1 is true
if (Boolean_expression 2) {
// Executes when the Boolean expression 2 is True
}
}
Because we have nested IF statements, we can nest else if...else in a similar way.
Example
public class Test {public
static void Main (String args[]) {
int x =;
int y = ten;
if (x = =) {
if (y = = ten) {
System.out.print ("x = y = ten");}
}}
This will produce the following results:
Switch statement
A switch statement allows a variable to be tested for a series of worth of equality. Each value is referred to as a case, and the variable that is started is checked for each.
Grammar
The syntax for the enhanced for loop is:
switch (expression) {case
value:
//statements,
//optional case
value:
//statements
//optional//you can have any of the case
statements.
Default://optional
//statements
}
The following rules apply to a switch statement:
- A variable used in a switch statement can only be one byte, Short,int, or char.
- You can have any number of case statements in a switch statement. Each case is followed by a value that is about to be compared and a colon.
- For case the value must be the same data type as the switch variable, it must be a constant or literal.
- When the variable being started is equal to the case, the statement after the case is executed until the break.
- When a break statement is reached, the switch terminates, and the control flow jumps to the next line following the switch statement.
- Not every case needs to contain a break. If a break is not present, the control flow runs through the subsequent case until the break.
- The switch statement can have an optional default case, which must appear at the end of the switch. No case is true when performing a task, and the default can be used. No break is required in the default case.
Example
public class Test {public
static void Main (String args[]) {
//char grade = Args[0].charat (0);
Char grade = ' C ';
Switch (grade)
{case
' A ':
System.out.println ("excellent!");
break;
Case ' B ': Case
' C ':
System.out.println ("OK Done");
break;
Case ' D ':
System.out.println ("You passed");
Case ' F ':
System.out.println ("Better try Again");
break;
Default:
System.out.println ("Invalid grade");
}
System.out.println ("Your grade is" + grade);
}
Compile and run the program that uses the various command-line arguments above. This will produce the following results:
$ java Test
Your grade is a C