RUCU
OBJECT ORIENTED
PROGRAMMING I RCS 122
Vincent Pius Bob
Ruaha Catholic University
Department of Computer Science
Faculty of Information and Communication
Technology
CONTROL
STRUCTUR
ES
Direct program flow
through conditional
logic.
Control Structures
Control structures in Java are used to control the
flow of your program by making decisions or
repeating actions.
A block of code that dictates the flow of statements
in a program.
The order in which statements in a program are
executed is called flow of control.
Normally statements in a Java program, are
executed one after the other in the order in which
they are written, a process called sequential
execution.
Control Structures cont..
A procedure for solving a problem in terms of
actions to execute and the order in which these
actions are executed is called an algorithm.
There are three types of control structures namely:
Sequential control structure
Selection control structure
Repetition/Iteration control structure
Control Structures cont..
i. Sequence
A default control structure in Java if no any other
control structure is specified.
With sequential control structure, program
statements are executed one after another in the
order they occur from top to bottom.
A program can contain any number of statements.
Consider statements in the main () method, they
are usually executed in the order in which they
are placed from top to bottom.
The following diagram depicts the execution flow
of four statements in sequential control structure.
i. Sequence cont..
i. Sequence cont..
In this case, statement 1 will execute first, followed
by statement 2, then statement 3 up to statement n.
The statements must be logically placed so as to
avoid compile time errors or logic errors that may
arise if they are wrongly ordered.
You do not have to add any other code to make
sequential execution occur.
ii. Selection
Selection control structures are used by
programs to choose among alternative courses
of action.
They contain a condition which is evaluated to
either true or false.
If the condition is true, a statement linked to
the condition is executed.
If the condition is false, a statement linked to
the condition is ignored (i.e. not executed).
ii. Selection
ii. Selection
Selection control structures, also known as
decision-making structures, allow the
program to make choices based on specific
conditions.
Java provides following types of decision-
making statements:
a) if statement
b) if … else statement
c) if…else if…else
d) nested if statement
e) switch statement
Java Conditions
Java supports the usual logical conditions
from mathematics:
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b
These conditions can be used to perform
different actions for different decisions.
a) if statement
An if statement consists of a Boolean expression
followed by one or more statements.
Syntax:
if(Boolean_expression) {
// Statements will execute if the Boolean
expression is true
}
If the Boolean expression evaluates to true then the
block of code inside the if statement will be
executed. If not, the first set of code after the end
of the if statement (after the closing curly brace)
a) if statement cont..
public class MyClass {
public static void main(String args[]) {
int x = 10;
if( x < 20 ) {
System.out.print("This is if statement");
u t
}
Outp
} ??
}
b) if…else statement
An if statement can be followed by an optional else
statement, which executes when the boolean
expression is false.
Syntax:
if(condition) {
// Executes when the Boolean expression is
true
}else {
// Executes when the Boolean expression is
false
b) if…else statement (cont..)
public class MyClass {
public static void main(String args[]) {
int x = 30;
if( x < 20 ) {
System.out.print("This is if statement");
}else {
u t
System.out.print("This is else statement"); tp
} Ou
??
}
}
c) if…else if…else statement
An if statement can be followed by an optional else
if...else statement, which is very useful to test
various conditions using single if...else if statement.
When using if, else if, else statements there are a
few points to keep in mind.
An if can have zero or one else's and it must come
after any else if's.
An if can have zero to many else if's and they must
come before the else.
Once an else if succeeds, none of the remaining
else if's or else's will be tested.
c) if…else if…else statement cont..
Syntax:
if(condition 1) {
// Executes when the Boolean expression 1 is true
}else if(condition 2) {
// Executes when the Boolean expression 2 is true
}else if(condition 3) {
// Executes when the Boolean expression 3 is true
}else {
// Executes when the none of the above condition is
true.
}
c) if…else if…else statement eg..
public class MyClass {
public static void main(String args[]) {
int x = 30;
if( x == 10 ) {
System.out.print("Value of X is 10");
}else if( x == 20 ) {
System.out.print("Value of X is 20");
}else if( x == 30 ) {
u t
System.out.print("Value of X is 10"); tp
}else {
Ou
System.out.print("This is else statement"); ??
}
}
c) if…else if…else statement eg..
Quiz
Write any full java program that makes use of
the if...else if...else statement.
c) Nested if statement
It is always legal to nest if-else statements which
means you can use one if or else if statement inside
another if or else if statement.
Syntax:
if(Boolean_expression 1) {
// Executes when the Boolean expression 1 is true
if(Boolean_expression 2) {
// Executes when the Boolean expression 2 is true
}
}
You can nest else if...else in the similar way as we
c) Nested if statement cont..
public class MyClass {
public static void main(String args[]) {
int x = 30;
int y = 10;
if( x == 30 ) {
if( y == 10 ) {
u t
System.out.print("X = 30 and Y = 10"); tp
} Ou
} ??
}
}
d) Switch statement
A switch statement allows a variable to be tested for equality against
a list of values. Each value is called a case, and the variable being
switched on is checked for each case.
Syntax:
switch(expression) {
case value :
// Statements
break; // optional
case value :
// Statements
break; // optional
// You can have any number of case statements.
default : // Optional
// Statements
d) Switch statement cont..
Instead of writing many if...else statements, you can use
the switch statement. The switch statement selects one
of many code blocks to be executed.
When Java reaches a break keyword, it breaks out of the
switch block. This will stop the execution of more code
and case testing inside the block. When a match is
found, and the job is done, it's time for a break. There is
no need for more testing.
The default keyword specifies some code to run if there
is no case match
You can have any number of case statements within a
switch. Each case is followed by the value to be
d) Switch statement cont..
What if we remove the break statements ?
See Examples in the next slides
d) Switch statement cont..
public class MyClass {
public static void main(String args[]) {
int x = 2;
switch(x) {
case 1 :
System.out.println("One!");
case 2 :
System.out.println("Two!");
case 3 :
u t
System.out.println("Three!"); tp
default : Ou
System.out.println("Value not found"); ??
}
System.out.println("Your value is " + x);
}}
d) Switch statement cont..
You can see that the execution of statements
continues to the next case statements until a
break statement is reached; if there is no
break statement, all the remaining case
statements will be executed (plus the default
statement).
d) Switch statement cont..
public class MyClass { public class MyClass {
public static void main(String args[]) { public static void main(String args[]) {
int x = 2; int x = 2;
switch(x) { switch(x) {
case 1 : case 1 :
System.out.println("One!"); System.out.println("One!");
break; case 2 :
case 2 : System.out.println("Two!");
u t
System.out.println("Two!");
t case 3 :
tp
case 3 :
tp u Ou
System.out.println("Three!");
default : Ou
System.out.println("Three!"); break;
default : ??
??
System.out.println("Value not found"); System.out.println("Value not found");
} }
System.out.println("Your value is " + x); System.out.println("Your value is " + x);
} }
} }
d) Switch statement cont..
public class MyClass {
public static void main(String args[]) {
char grade = 'C';
switch(grade) {
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
u t
System.out.println("You passed");
tp
case 'F' :
System.out.println("Better try again");
Ou
break; ??
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);}}
d) Switch statement cont..
public class MyClass {
public static void main(String args[]) {
char grade = 'F';
switch(grade) {
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
u t
System.out.println("You passed");
tp
case 'F' :
System.out.println("Better try again");
Ou
default : ??
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
Conditional Operator
The conditional operator (? :) is also known as
the ternary operator.
It can be used to replace if...else statements.
It has the following general form −
Exp1 ? Exp2 : Exp3;
Where Exp1, Exp2, and Exp3 are expressions.
Notice the use and placement of the colon.
Conditional Operator cont..
To determine the value of the whole
expression, initially exp1 is evaluated.
If the value of exp1 is true, then the value of
Exp2 will be the value of the whole
expression.
If the value of exp1 is false, then Exp3 is
evaluated and its value becomes the value of
the entire expression.
In short, the operator is written as :
variable x = (expression) ? value if true :
Conditional Operator cont..
public class MyClass {
public static void main(String args[]) {
int a, b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
u t
b = (a == 10) ? 20: 30; tp
Ou
System.out.println( "Value of b is : " + b ); ??
}
}
iii. Repetition/iteration
A repetition control structure, also known as a
loop, is a programming construct that allows a block
of code to be executed multiple times, based on a
specific condition or a predefined number of
iterations.
These are the control structures that enable
programs to execute statements repeatedly as long as
a condition called the loop-continuation condition
remains true.
Java provides the following types of loop to handle
looping requirements:
a) while loop
a) While Loop
The while loop repeats a statement or
group of statements while a given
condition is true.
The while loop loops through a block of
code as long as a specified condition is
true
It tests the condition before executing
the loop body.
Syntax
a) While Loop cont..
The key point of the while loop is that the
loop might not ever run. When the expression
is tested and the result is false, the loop body
will be skipped and the first statement after
the while loop will be executed.
a) While Loop cont..
public class MyClass {
public static void main(String args[]) {
int x = 10;
while( x < 20 ) {
System.out.print("value of x : " + x ); t
tp u
x++; O u
System.out.print("\n"); ??
}
}
b) For loop
When you know exactly how many times you
want to loop through a block of code, use
the for loop instead of a while loop
The for loop executes a sequence of
statements multiple times and abbreviates the
code that manages the loop variable.
It allows you to efficiently write a loop that
needs to be executed a specific number of
times.
A for loop is useful when you know how many
b) For loop cont..
Syntax
for(initialization; condition; update) {
// Statements
}
b) For loop cont..
Here is the flow of control in a for loop
– The initialization step is executed first, and only once. This
step allows you to declare and initialize any loop control
variables and this step ends with a semi colon (;).
– Next, the Boolean expression is evaluated. If it is true, the
body of the loop is executed. If it is false, the body of the loop
will not be executed and control jumps to the next statement
past the for loop.
– After the body of the for loop gets executed, the control jumps
back up to the update statement. This statement allows you
to update any loop control variables. This statement can be
left blank with a semicolon at the end.
– The Boolean expression is now evaluated again. If it is true,
the loop executes and the process repeats (body of loop, then
b) For loop cont..
public class MyClass {
public static void main(String args[]) {
for(int x = 10; x < 20; x = x + 1) { //OR for(int x = 10; x < 20; x++)
System.out.print("value of x : " + x );
System.out.print("\n"); t
u
} utp
O
} ??
}
c) do…while loop
The do...while loop is similar to the while loop, except
that it tests the condition at the end of the loop body and
therefore it is guaranteed to execute at least once.
Syntax
do {
// Statements
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of
the loop, so the statements in the loop execute once
before the Boolean is tested.
If the Boolean expression is true, the control jumps back
up to do statement, and the statements in the loop
c) do…while loop cont..
public class MyClass {
public static void main(String args[]) {
int x = 10;
do {
System.out.print("value of x : " + x ); t
tp u
x++;
Ou
System.out.print("\n"); ??
}while( x < 20 );
}
c) do…while loop cont..
public class MyClass {
public static void main(String args[]) {
int x = 10;
do {
System.out.print("value of x : " + x ); t
tp u
x++;
Ou
System.out.print("\n"); ??
}while( x < 5 );
}
c) do…while loop cont..
public class MyClass {
public static void main(String args[]) {
int x = 10;
do {
x++; t
tp u
}while( x < 5 );
Ou
System.out.println(x); ??
}
}
c) do…while loop cont..
public class MyClass {
public static void main(String args[]) {
int x = 10;
do {
x++; t
tp u
}while( x < 13 );
Ou
System.out.println(x); ??
}
}
Loop Control Statements
Loop control statements change execution
from its normal sequence. When execution
leaves a scope, all automatic objects that were
created in that scope are destroyed.
Java supports the following control statements.
– break statement
– continue statement
break Statement
We have seen how a break statement I used
in a switch statement in the selection
control structure.
In loops, the break statement terminates
the loop statement and transfers execution
to the statement immediately following the
loop.
break Statement
public class MyClass {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
break;
u t
} tp
System.out.print( x ); Ou
System.out.print("\n"); ??
}
}
continue Statement
The continue keyword causes the loop to skip
the remainder of its body and immediately retest
its condition prior to reiterating (i.e. It causes
the loop to immediately jump to the next
iteration of the loop).
In a for loop, the continue keyword causes
control to immediately jump to the update
statement.
In a while loop or do/while loop, control
immediately jumps to the Boolean expression.
continue Statement
public class MyClass {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
continue;
u t
} tp
System.out.print( x ); Ou
System.out.print("\n"); ??
}
}
Enhance Loop/ For each Loop
The enhanced for loop was introduced in Java 5. It is
mainly used to traverse collection of elements including
arrays.
Syntax
for(declaration : expression) {
// Statements
}
Declaration − The newly declared block variable, is of a
type compatible with the elements of the array you are
accessing. The variable will be available within the for
block and its value would be the same as the current array
element.
Expression − This evaluates to the array you need to loop
Enhance Loop/ For each Loop cont..
public class MyClass {
public static void main(String args[]) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
}
}
Enhance Loop/ For each Loop cont..
public class MyClass {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
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(",");
}}}
END OF LECTURE
SEVEN
NEXT ON LECTURE
EIGHT
JAVA PACKAGES
THANK YOU!