Chapter 2 Par 2
Chapter 2 Par 2
Control
Statements
Cont’d …
• Now we will examine programming statements
that allow us to:
make decisions
repeat processing steps in a loop
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).
Jumps tatements allow your program to execute in a
nonlinear fashion
Flow of Control
• Unless specified otherwise, the order of statement
execution through a method is linear: one
statement after another in sequence
if ( condition )
statement;
condition
evaluated
true
false
statement
Boolean Expressions
• A condition often uses one of Java's equality
operators or relational operators, which all return
boolean results:
higher == equal to
precedence != not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
a b a && b a || b
true true true true
true false false true
false true false true
false false false false
Boolean Expressions
• Specific expressions can be evaluated using truth
tables
total < MAX found !found total < MAX && !found
false false true false
false true false false
true false true true
true true false false
The if-else Statement
• An else clause can be added to an if statement to
make an if-else statement
if ( condition )
statement1;
else
statement2;
condition
evaluated
true false
statement1 statement2
Switch Statements
• The switch statement is Java’s multiway branch
statement. As such, it often provides a better
alternative than a large series of if-else-if
statements. Here is the general form of a switch
statement.
switch (expression) {
casevalue1:
break;
casevalue2:
// statement sequence
break;
casevalueN:
// statement sequence
break;
default:
}
…Switch Statements
• The expression must be of type byte,short,int, or
char; each of the values specified in the case
statements must be of a type compatible with the
expression. Each case value must be a unique literal
(that is, it must be a constant, not a variable).
Duplicate case values are not allowed.
… case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
}
}
class Switch {
public static void main(String args[]) {
int month = 4;
String season;
switch (month) {
case 12:
case 1:
case 2:
season = "Winter";
break;
case 3:
case 4:
case 5:
season = "Spring";
break;
case 6:
case 7:
case 8:
season = "Summer";
break;
case 9:
case 10:
case 11:
season = "Autumn";
break;
default:
season = "Bogus Month";
}
System.out.println("April is in the " + season + ".");
}
}
Repetition Statements
• Repetition statements allow us to execute a
statement multiple times
• Often they are referred to as loops
• Like conditional statements, they are controlled by
boolean expressions
• Java has three kinds of repetition statements:
the while loop
the do loop
the for loop
while ( condition )
statement;
condition
evaluated
true false
statement
The while Statement
• An example of a while statement:
int count = 1;
while (count <= 5)
{
System.out.println (count);
count++;
}
true
product <= 1000 product = 2 * product
false
Parts of a while loop
int x = 1;
while (x < 10) {
System.out.println(x);
x++;
}
• Label the following loop
int product = 2;
while ( product <= 1000 )
product = 2 * product;
Another loop example
• Label the parts of the loop
int x = 1;
int y = 2;
while (x < 10)
{
System.out.println(x + “ “ + y);
y *= 2;
x++;
}
while loop format
• Sum the numbers from 1 to 100
Average.java
System.out.print ("Enter an integer (0 to quit): ");
value = scan.nextInt();
sum += value;
System.out.println ("The sum so far is " + sum);
if (count == 0)
System.out.println ("No values were entered.");
else
{
average = (double)sum / count;
int count = 1;
while (count <= 25)
{
System.out.println (count);
count = count - 1;
}
count1 = 1;
while (count1 <= 10)
{
count2 = 1;
while (count2 <= 20)
{
System.out.println ("Here");
count2++;
}
count1++;
}
The do Statement
• A do statement has the following syntax:
do
{
statement;
}
while ( condition )
statement
true
condition
evaluated
false
The do Statement
• An example of a do loop:
int count = 0;
do
{
count++;
System.out.println (count);
} while (count < 5);
do
{
lastDigit = number % 10;
reverse = (reverse * 10) + lastDigit;
number = number / 10;
}
while (number > 0);
statement
condition
evaluated
true
condition
true false
evaluated
statement
false
The for Statement
• A for statement has the following syntax:
initialization
condition
evaluated
true false
statement
increment
The for Statement
• A for loop is functionally equivalent to the
following while loop structure:
initialization;
while ( condition )
{
statement;
increment;
}
The for Statement
• An example of a for loop:
System.out.println();
}
}
The for Statement
• Each expression in the header of a for loop is
optional
Index
prime
0 1 2 3 4 5 6 7 8 9
2 1 11 -9 2 1 11 90 101 2
value
Default Initialization
• When array is created, array elements are
initialized
Numeric values (int, double, etc.) to 0
Boolean values to false
Char values to ‘\u0000’ (unicode for blank character)
Class types to null
Accessing Array Elements
• Index of an array is defined as
Positive int, byte or short values
Expression that results into these types
• Any other types used for index will give
error
long, double, etc.
Incase Expression results in long, then type
cast to int
• Indexing starts from 0 and ends at N-1
primes[2]=0;
int k = primes[2];
…
Validating Indexes
• JAVA checks whether the index values are valid at
runtime
If index is negative or greater than the size of the array
then an IndexOutOfBoundException will be thrown
Program will normally be terminated unless handled in
the try {} catch {}
Initializing Arrays
• Initialize and specify size of array while
declaring an array variable
int[] primes={2,3,5,7,11,13,17}; //7 elements
• You can initialize array with an existing
array
int[] even={2,4,6,8,10};
int[] value=even;
One array but two array variables!
Both array variables refer to the same array
Array can be accessed through either variable
name
Graphical Representation
even
0 1 2 3 4
2 4 6 8 10
value
Demonstration
long[] primes = new long[20];
primes[0] = 2;
primes[1] = 3;
long[] primes2=primes;
System.out.println(primes2[0]);
primes2[0]=5;
System.out.println(primes[0]);
Output
2
5
Array Length
• Refer to array length using length
A data member of array object
array_variable_name.length
for(int k=0; k<primes.length;k++)
….
• Sample Code:
long[] primes = new long[20];
System.out.println(primes.length);
• Output: 20
Sample Program
class MinAlgorithm
{
public static void main ( String[] args )
{
int[] array = { -20, 19, 1, 5, -1, 27, 19, 5 } ;
int min=array[0]; // initialize the current minimum
for ( int index=0; index < array.length; index++ )
if ( array[ index ] < min )
min = array[ index ] ;
System.out.println("The minimum of this array is: " + min
);
}
}
Sample[0] 0 1 2 3 4 5 6 7 8 9
Sample[1] 0 1 2 3 4 5 6 7 8 9
Sample[2] 0 1 2 3 4 5 6 7 8 9
Initializing Array of Arrays
int[][] array2D = { {99, 42, 74, 83, 100},
{90, 91, 72, 88, 95}, {88, 61, 74, 89,
96}, {61, 89, 82, 98, 93}, {93, 73, 75,
78, 99}, {50, 65, 92, 87, 94}, {43, 98,
78, 56, 99} };
//5 arrays with 5 elements each
Arrays of Arrays of Varying Length
• All arrays do not have to be of the same length
float[][] samples;
samples=new float[6][];//defines # of arrays
samples[2]=new float[6];
samples[5]=new float[101];
• Not required to define all arrays
Initializing Varying Size Arrays
int[][] uneven = { { 1, 9, 4 }, { 0, 2},
{ 0, 1, 2, 3, 4 } };
//Three arrays
//First array has 3 elements
//Second array has 2 elements
//Third array has 5 elements
Array of Arrays Length
long[][] primes = new long[20][];
primes[2] = new long[30];
System.out.println(primes.length); //Number of arrays
System.out.println(primes[2].length);//Number of elements in the
second array
OUTPUT:
20
30
Sample Program
class unevenExample3
{
public static void main( String[] arg )
{ // declare and construct a 2D array
int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2,
3, 4 } };
// print out the array
for ( int row=0; row < uneven.length; row++ )
//changes row
{
System.out.print("Row " + row + ": ");
for ( int col=0; col < uneven[row].length;
col++ ) //changes column
System.out.print( uneven[row][col] + "
"); System.out.println();
}
}
}
Output
Row 0: 1 9 4
Row 1: 0 2
Row 2: 0 1 2 3 4