Module 4 Study Guide
Module 4 Study Guide
Control Structures
if, else statement
switch, case statement
while loop
do, while loop
for loop
The if statement enables your program to selectively execute other statements, based on some
criteria.
The else statement performs a different set of statements if the expression is false.
Syntax:
if(condition/boolean expression) {
//codes to execute if the condition is true
}
else {
//codes to execute if the condition is false
}
The switch statement is used to conditionally perform statements based on an integer
expression.
Syntax:
switch(varName)
{
case const1: codes here; break;
case const2: codes here; break;
default: codes here; break;
}
The break statement causes the program flow to exit from the body of the switch construct.
Each case label takes only a single argument, but when execution jumps to one of these labels,
it continues downward until it reaches a break statement.
The while loop executes a given statement or block of statements repeatedly as long as the
value of the expression is true.
Syntax:
while(condition/expression) {
//codes to execute if condition is true
}
The do-while loop facilitates evaluation of condition or expression at the end of the loop to
ensure that the statements are executed at least once .
Syntax:
do{
//codes to execute if condition is true
} while(condition/expression);
The for loop executes a given statement or a block of statements for a definite number of
times.
Syntax:
for (initialization; condition; altering list) {
//codes to execute if condition is true
}
The foreach loop is for traversing items in a collection. foreach is usually used in place of a
standard for statement. It usually maintain no explicit counter: they essentially say "do this to
everything in this set", rather than "do this x times".
Syntax:
for(initialization : [collection/array]) {
//codes to execute if condition is true
}
Arrays
First index
0 1 2 3 4 5 6 7 8 9
Array length is 10
Element at index 8
Array Declaration
Syntax:
type arrayName[ ] = new type[length];
Example:
String names[ ] = new String[5];
int [ ]grades = new int[15];
double[ ] grades;
grades = new double[2];
Array Initialization
Syntax:
type arrayName[ ] = {value,value,…};
Example:
String names[ ] ={“maria”,”blanco”,”forever”};