Control Flow and Decision Making Statement (Module 3) - 110945
Control Flow and Decision Making Statement (Module 3) - 110945
Objectives
i. Understand and explain the use of if, if-else, if-else-if, and switch statements in Java.
ii. Write Java programs that make decisions using if, if-else, if-else-if, and switch
statements.
iii. Identify and correct errors in Java programs using selection statements.
iv. Apply selection statements to solve real-world problems.
Control Statement
Control statements are important building blocks in every programming language. They let a
programmer to control the flow of a program's execution, allowing activities to be performed
conditionally and repeatedly. In Java, control statements are divided into three types:
1. Selection Statements: These are used to switch between distinct execution routes based
on criteria. The most common selection statements in Java are if, if-else, if-else-if, and
switch.
2. Iteration Statements: These enable the repeating running of a block of code. For, while,
and do-while loops are among the most used iteration statements in Java.
3. Jump Statements: These allow the software to navigate to another section of the
program. Java has break, continue, and return statements for this purpose.
Selection statements, often known as conditional statements, are critical decision-making tools
within programs. They let a program to behave differently under different conditions, resulting in
more dynamic and adaptable code. Let's go into the details of why selection statements are
important:
3. Error Handling: Selection statements are frequently used in mistake detection and
treatment. For example, before completing an action, a program can check whether
certain criteria are satisfied, and if not, it can take a different path to handle the issue or
offer feedback to the user.
4. User Interaction: In applications that need user input, selection statements aid in
verifying and processing the data. Depending on the input, several actions can be
conducted, making the application more interactive and user-friendly.
5. Efficiency: By directing the flow of execution to the relevant parts of the program,
selection statements can help in optimizing the performance. They ensure that only
necessary code blocks are executed, thus saving computational resources.
The if Statement: The if statement is the most basic form of a selection statement. It
evaluates a boolean expression and, if it is true, executes the corresponding block of
code.
Syntax:
if (condition) {
// code to be executed if condition is true
}
Example: Write a java program to show if a person is eligible to vote.
The if-else Statement: The if-else statement extends the if statement by including an alternate
block of code that will be run if the condition is false.
Syntax:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
In this example, the program prints a different message depending on whether the age is 18 or
older.
The if-else-if Ladder: The if-else-if ladder is used to examine various conditions. It allows the
software to select one of several alternative execution pathways.
Syntax:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if all conditions are false
}
Example:
Write a java program that reads a score and prints the corresponding grade based on the following
examination scores
Scores Grade
70-100 A
60-69 B
50-59 C
45-49 D
<45 F
This example assigns a grade based on the value of score.
The switch Statement: The switch statement is used to run one block of code from among many
based on the value of an expression. It is an alternative to utilizing numerous if-else-if statements
and can improve code readability when dealing with various situations.
Syntax:
switch (expression) {
case value1:
// code to be executed if expression equals value1
break;
case value2:
// code to be executed if expression equals value2
break;
// more cases
default:
// code to be executed if none of the cases match
}
Example:
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
In this example, the program prints the day of the week based on the value of day.
Loop
While loop: The while loop in Java is a fundamental control flow statement that facilitates the
repeated execution of a block of code as long as a specified boolean condition remains true. This
type of loop is particularly useful when the number of iterations is not predetermined and
depends on dynamic conditions during runtime.
Syntax
while (condition) {
// code block to be executed
}
Explanation of Components
1. Initialization: Any required initialization for variables that control the loop can be done
before entering the while loop. This setup is crucial to ensure that the condition can be
correctly evaluated right from the start.
2. Condition: The condition is a boolean expression evaluated before each iteration of the
loop. If the condition evaluates to true, the loop body is executed. If it evaluates to false,
the loop terminates, and control passes to the next statement following the loop. This pre-
condition check makes while loops ideal for scenarios where the number of iterations is
unknown beforehand.
3. Code Block: The code block inside the {} braces is the body of the loop. This block
contains the statements that need to be executed repeatedly. It is crucial to include logic
within this block that influences the condition to eventually become false; otherwise, the
loop may run indefinitely.
4. Update: Typically, within the loop body, there will be statements that modify the
variables involved in the condition, ensuring progress toward terminating the loop. This
is often done through increment or decrement operations.
Basic Example
Here’s a simple example demonstrating a while loop that prints numbers from 1 to 5:
Example 2
The do-while Loop
The do-while loop in Java is a control flow statement that repeatedly executes a block of code at
least once, and then continues to execute the block as long as a specified boolean condition
remains true. Unlike the while loop, the do-while loop ensures that the code block is executed at
least once before the condition is tested.
Syntax
do {
} while (condition);
Explanation of Components
1. Initialization: Any required initialization for variables used in the loop can be done
before entering the do-while loop. This setup is crucial to ensure that the condition can be
correctly evaluated in subsequent iterations.
2. Code Block: The code block inside the {} braces is the body of the loop. This block
contains the statements that need to be executed repeatedly.
3. Condition: The condition is a boolean expression evaluated after each iteration of the
loop. If the condition evaluates to true, the loop body is executed again. If it evaluates to
false, the loop terminates, and control passes to the next statement following the loop.
For example:1
int i = 1; // Initialization
do {
i++; // Update
} while (i <= 5); // Condition
import java.util.Scanner;
example 2:
int number;
int sum = 0;
do {
number = scanner.nextInt();
sum += number;
scanner.close();
The for loop in Java is a control flow statement that allows code to be executed repeatedly based
on a given boolean condition. It is particularly useful when the number of iterations is known
beforehand. The for loop provides a concise way to initialize a variable, test a condition, and
increment or update the variable, all in one line.
Syntax
Explanation of Components
1. Initialization: This part is executed once at the beginning of the loop. It typically
initializes the loop control variable(s).
2. Condition: The condition is evaluated before each iteration of the loop. If the condition
evaluates to true, the loop body is executed. If it evaluates to false, the loop terminates.
3. Update: This part is executed after each iteration of the loop. It typically updates the loop
control variable(s).
This example demonstrates a basic for loop that prints numbers from 1 to 5.
}
DECLARATION OF STRING &FORMATTING CONSOLE OUTPUT
DECLARATION OF STRING
Syntax
For example
Note: if you declare a string with the syntax the value are not the same
For example:
The second output which is false in the above output is so because they are not of the same pool.
In java, a string is a sequence of characters that is treated as an object. Strings are immutable, meaning
that once a string is created its value cannot be changed.
Most common ways to create a string is by using string literals. String literals are enclosed within double
quotes””. For example
You can also create a string using the new keyword and the string constructor. This is useful when you
want to create a string from other datatypes , such as an array of characters. For example
You can combine strings using the + operator. This is known as string concatenation. For example
String firstName=”John”;
String lastName=”Doe”;
These classes provides methods for dynamically building and modifying strings. They are useful when
you need to perform a series of string operations, as they can be more efficient than repeated
concatenating string. String Builder is non- synchronized, while string Buffer is synchronized.
For example:
Sb.append(“Hello”);
Sb.append(“,”);
Sb.append(“world!”);
USING THE INTERN()METHOD: The intern()method returns a canonical representation for the string
object . it checks if the String pool and if so , if so it returns the pooled instance . if the string does not
exist in the pool, it is added to the pool; and the reference to the pooled instance is returned
For example
System.out.println(s1==s2);//false
System.out.println(s1==s2.intern());//true
Strings in java are not primitive types they are object types and are one of the most powerful types in
java.
Formatted specifiers
% s= String.
%c =character
%b = Boolean.
In the example above , to print the length of the name which is Ekundayo Oluwasayo. To do this we
have Ekundayo is of length 8 the space is 1 and the last which is oluwasayo is of length 9, there for we
have 8+1+9=18 as seen above.
For example:
The example below test if the string is empty
CONVERSION OF A STRING FROM UPPERCASE TO LOWERCASE OR FROM LOWERCASE TO UPPERCASE
The example changes the name given, which is Ekundayo Oluwasayo to Upper case
Then let’s try for lowercase as well
TO REPLACE A STRING