JAVA Mod2
JAVA Mod2
Module 2
Control Statements
Java’s program control statements can be put into the following categories: selection,
iteration, and jump.
Selection statements allow your program to choose different paths of execution based
upon the outcome of an expression or the state of a variable.
Iteration statements enable program execution to repeat one or more statements (that
is, iteration statements form loops).
Jump statements allow your program to execute in a nonlinear fashion.
The if statement
The if statement executes a block of code only if the specified expression is true.
If the value is false, then the if block is skipped and execution continues with the rest
of the program.
You can either have a single statement or a block of code within an if statement.
Note that the conditional expression must be a Boolean expression.
Syntax:
if (<conditional expression>) {
<statements>
}
Example:
public class Example {
public static void main(String[] args) {
int a = 10, b = 20;
if (a > b)
System.out.println("a > b");
if (a < b)
Syntax:
if (condition)
statement1;
else statement2;
Nested ifs
A nested if is an if statement that is the target of another if or else.
When you nest ifs, the main thing to remember is that an else statement always refers
to the nearest if statement that is within the same block as the else and that is not
already associated with an else.
Here is an example:
if(i == 10) {
if(j < 20) a = b;
if(k > 100) c = d; // this if is
else a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10)
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;
Example:
class IfElse {
public static void main(String args[]) {
int month = 4; // April
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}
The program will select the value of the case label that equals the value of the
controlling expression and branch down that path to the end of the code block.
If none of the case label values match, then none of the codes within the switch
statement code block will be executed. Java includes a default label to use in cases
where there are no matches.
We can have a nested switch within a case block of an outer switch.
Syntax:
switch (<non-long integral expression>) {
case label1: <statement1> ; break;
case label2: <statement2> ; break;
…
case labeln: <statementn> ; break;
default: <statement>
}
Example:
public class Example {
public static void main(String[] args) {
int a = 10, b = 20, c = 30;
int status = -1;
if (a > b && a > c) {
status = 1;
} else if (b > c) {
status = 2;
} else {
status = 3;
}
switch (status) {
case 1:
System.out.println("a is the greatest");
break;
case 2:
The break statement is optional. If you omit the break, execution will continue on
into the next case.
It is sometimes desirable to have multiple cases without break statements between
them.
For example, consider the following program:
// In a switch, break statements are optional.
class MissingBreak {
public static void main(String args[]) {
for(int i=0; i<12; i++)
switch(i) {
case 0:
case 1:
case 2:
case 3:
case 4:
System.out.println("i is less than 5");
break;
case 5:
case 6:
case 7:
case 8:
case 9:
In summary, there are three important features of the switch statement to note:
The switch differs from the if in that switch can only test for equality, whereas if can
evaluate any type of Boolean expression. That is, the switch looks only for a match
between the value of the expression and one of its case constants.
No two case constants in the same switch can have identical values. Of course, a
switch statement and an enclosing outer switch can have case constants in common.
Iteration Statements
Syntax:
while (<loop condition>) {
<statements>
}
Example:
public class Example {
public static void main(String[] args) {
int count = 1;
System.out.println("Printing Numbers from 1 to 10");
while (count <= 10) {
System.out.println(count++);
}
}
}
Syntax:
do {
<loop body>
} while (<loop condition>);
Example:
public class Example {
public static void main(String[] args) {
int count = 1;
System.out.println("Printing Numbers from 1 to 10");
do {
System.out.println(count++);
} while (count <= 10);
}
}
Syntax:
for (<initialization>; <loop condition>; <increment expression>) {
<loop body>
}
Example:
public class Example {
public static void main(String[] args) {
System.out.println("Printing Numbers from 1 to 10");
for (int count = 1; count <= 10; count++) {
System.out.println(count);
}
}
}
Here is another interesting for loop variation. Either the initialization or the iteration
expression or both may be absent, as in this next program:
// Parts of the for loop can be empty.
class ForVar {
public static void main(String args[]) {
int i;
boolean done = false;
i = 0;
for( ; !done; ) {
System.out.println("i is " + i);
if(i == 10) done = true;
i++;
}
}
}
Here, the initialization and iteration expressions have been moved out of the for. Thus, parts
of the for are empty
Here is one more for loop variation. You can intentionally create an infinite loop (a
loop that never terminates) if you leave all three parts of the for empty.
For example:
for( ; ; ) {
// ...
}
This loop will run forever because there is no condition under which it will terminate.
Here, type specifies the type and itr-var specifies the name of an iteration variable
that will receive the elements from a collection, one at a time, from beginning to end.
The collection being cycled through is specified by collection.
There are various types of collections that can be used with the for, but the only type
used in this chapter is the array.
Working:
With each iteration of the loop, the next element in the collection is retrieved and
stored in itr-var.
The loop repeats until all elements in the collection have been obtained.
Because the iteration variable receives values from the collection, type must be the
same as (or compatible with) the elements stored in the collection.
Thus, when iterating over arrays, type must be compatible with the base type of the
array.
class ForEach {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x : nums) {
sum += x;
}
For example, this program sums only the first five elements of nums:
class ForEach2 {
public static void main(String args[]) {
int sum = 0;
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// use for to display and sum the values
for(int x : nums) {
sum += x;
if(x == 5) break; // stop the loop when 5 is obtained
}
System.out.println("Summation of first 5 elements: " + sum);
}
}
nums[i][j] = (i+1)*(j+1);
// use for-each for to display and sum the values
for(int x[] : nums) {
for(int y : x) {
sum += y;
}
}
System.out.println("Summation: " + sum);
}
}
In the program, pay special attention to this line:
for(int x[] : nums) {
Notice how x is declared. It is a reference to a one-dimensional array of integers.
This is necessary because each iteration of the for obtains the next array in nums,
beginning with the array specified by nums[0].
The inner for loop then cycles through each of these arrays, displaying the values of
each element.
}
}
Nested Loops
Like all other programming languages, Java allows loops to be nested.
That is, one loop may be inside another. For example, here is a program that nests for
loops:
class Nested {
public static void main(String args[]) {
int i, j;
for(i=0; i<10; i++) {
for(j=i; j<10; j++)
System.out.print(".");
System.out.println();
}
}
}
Jump Statements
Java supports three jump statements: break, continue, and return. These statements
transfer control to another part of your program.
Syntax:
break; // the unlabeled form
break <label>; // the labeled form
Syntax:
continue; // the unlabeled form
continue <label>; // the labeled form
Syntax:
The return statement has two forms:
One that returns a value
return val;
One that doesn't returns a value
return;
Example:
public class Example {
public static void main(String[] args) {
int res = sum(10, 20);
System.out.println(res);
}
private static int sum(int a, int b) {
return (a + b);
}
}