Control Structures
| Site: | Newgate University Minna - Elearning Platform |
| Course: | Computer Programming I |
| Book: | Control Structures |
| Printed by: | Guest user |
| Date: | Monday, 9 November 2026, 1:10 PM |
1. Control Structures
control structures (also called control flow statements) determine the order in which statements are executed in a program. They allow developers to control the flow of execution based on conditions, loops, or branching. Examples of control structures, including their syntax, behavior, and examples with Java code.
1. Types of Control Structures in Java
Java control structures can be categorized into three main types:
1. Sequential: Statements are executed line by line in the order they appear (default behavior).
2. Decision-Making (Conditional): Execute specific blocks of code based on conditions.
3. Looping (Iterative): Repeat a block of code multiple times based on a condition or iteration.
4. Branching: Alter the flow of execution by jumping to another part of the program.
Additionally, Java includes mechanisms for exception handling, which can also affect control flow.
2.Detailed Explanation of Control Structures
2.1 Sequential Control
Sequential execution is the default behavior in Java, where statements are executed one after another in the order they are written.
1.1. Example 1:
java
public class SequentialExample {
public static void main(String[] args) {
int a = 5;
int b = 10;
int sum = a + b;
System.out.println("Sum: " + sum); // Output: Sum: 15
}
}
Notes:
· No special syntax is required for sequential execution.
· All statements are executed unless altered by other control structures.
2.2 Decision-Making (Conditional) Structures
Conditional statements execute a block of code based on whether a condition evaluates to true or false.
2.2.1 if Statement
Executes a block of code if a condition is true.
Syntax:
if (condition) {
// Code to execute if condition is true
}
Example:
public class IfExample {
public static void main(String[] args) {
int num = 10;
if (num > 0) {
System.out.println(num + " is positive"); // Output: 10 is positive
}
}
}
2.2.2 if-else Statement
Executes one block if the condition is true and another if it’s false.
Syntax:
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
1.2. Example 2&3:
public class IfElseExample {
public static void main(String[] args) {
int num = -5;
if (num >= 0) {
System.out.println(num + " is non-negative");
} else {
System.out.println(num + " is negative"); // Output: -5 is negative
}
}
}
if-else-if Ladder
Checks multiple conditions sequentially and executes the first true condition’s block.
Syntax:
if (condition1) {
// Code for condition1
} else if (condition2) {
// Code for condition2
} else {
// Code if no conditions are true
}
Example
public class IfElseIfExample {
public static void main(String[] args) {
int score = 85;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B"); // Output: Grade: B
} else if (score >= 70) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: F");
}
}
}
2. Switch Statement
Selects one of many code blocks to execute based on the value of an expression (typically an int, char, String, or enum).
Syntax (Java 7+ for String):
switch (expression) {
case value1:
// Code
break;
case value2:
// Code
break;
default:
// Code if no case matches
}
Example:
public class SwitchExample {
public static void main(String[] args) {
String day = "Monday";
switch (day) {
case "Monday":
System.out.println("Start of the week"); // Output: Start of the week
break;
case "Friday":
System.out.println("End of the work week");
break;
default:
System.out.println("Midweek or weekend");
}
}
}
2.1. Notes:
The break statement prevents fall-through to subsequent cases. Without break, all cases after a match are executed.
The default case is optional and executes if no case matches.
Java 12+ Switch Expressions (enhanced switch):
public class SwitchExpression {
public static void main(String[] args) {
String day = "Monday";
String result = switch (day) {
case "Monday" -> "Start of the week";
case "Friday" -> "End of the work week";
default -> "Midweek or weekend";
};
System.out.println(result); // Output: Start of the week
}
}
Uses -> for concise syntax and no break needed.
Can assign the result directly to a variable.
3. Looping (Iterative) Structures
Looping structures repeat a block of code while a condition is true or for a specified number of iterations.
2.3.1 for Loop
Executes a block of code a fixed number of times, typically with a counter.
Syntax:
for (initialization; condition; update) {
// Code to repeat
}
Example:
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
// Output:
// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5
}
}
Notes:
Initialization (e.g., int i = 1) runs once before the loop.
Condition (e.g., i <= 5) is checked before each iteration.
Update (e.g., i++) runs after each iteration.
3.1. Enhanced for Loop (for-each)
Iterates over arrays or collections (e.g., ArrayList).
Syntax:
for (Type variable : collection) {
// Code
}
3.2. Example:
public class EnhancedForLoopExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println("Number: " + num);
}
// Output:
// Number: 1
// Number: 2
// Number: 3
// Number: 4
// Number: 5
}
}
Notes:
· Simplifies iteration over arrays or Iterable objects.
· Cannot modify the collection’s structure during iteration.
while Loop
Repeats a block of code as long as a condition is true.
3.3. Syntax:
while (condition) {
// Code
}
Example:
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println("Count: " + i);
i++;
}
// Output:
// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5
}
}
Notes:
Condition is checked before each iteration.
Risk of infinite loops if the condition never becomes false.
4. do-while Loop
Similar to while, but guarantees at least one execution by checking the condition after the loop body.
Syntax:
do {
// Code
} while (condition);
Example:
public class DoWhileLoopExample {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("Count: " + i);
i++;
} while (i <= 5);
// Output:
// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5
}
}
Notes:
Useful when the loop body must execute at least once.
Condition is evaluated after the loop body.
5. Branching Structures
Branching statements alter the flow of execution by jumping to another part of the program.
break Statement
Exits a loop or switch statement immediately.
Example:
public class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exits loop when i is 5
}
System.out.println("i: " + i);
}
// Output:
// i: 1
// i: 2
// i: 3
// i: 4
}
}
Notes:
Can be used in for, while, do-while, or switch.
Labeled break: Breaks out of a specific outer loop (rarely used).
outer: for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break outer; // Exits both loops
}
}
}
5.1. Continue Statement
Skips the current iteration of a loop and proceeds to the next iteration.
Example:
public class ContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skips i == 3
}
System.out.println("i: " + i);
}
// Output:
// i: 1
// i: 2
// i: 4
// i: 5
}
}
Notes:
Only skips the current iteration; the loop continues.
Labeled continue: Skips to the next iteration of a specific outer loop (rarely used).
5.2. Return Statement
Exits a method and optionally returns a value to the caller.
Example:
public class ReturnExample {
public static int add(int a, int b) {
return a + b; // Exits method and returns sum
}
public static void main(String[] args) {
int result = add(5, 3);
System.out.println("Sum: " + result); // Output: Sum: 8
}
}
Notes:
Used to terminate a method’s execution.
If the method’s return type is not void, a value must be returned.
6. Exception Handling (try-catch)
Exception handling controls the flow when errors (exceptions) occur, preventing program crashes.
Syntax:
java
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Handle the exception
} finally {
// Optional: Code that always executes
}
Example:
public class TryCatchExample {
public static void main(String[] args) {
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // Throws ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Invalid index"); // Output: Error: Invalid index
} finally {
System.out.println("This always executes");
}
}
}
Notes:
try: Contains code that might throw an exception.
catch: Handles specific exceptions.
finally: Executes regardless of whether an exception occurs (optional).
Multiple catch blocks can handle different exception types.
throw: Manually throws an exception (e.g., throw new Exception("Error");).
throws: Declares exceptions a method might throw (e.g., public void method() throws IOException).
6.1. Practical Example Combining Control Structures
Here’s a Java program combining multiple control structures to process a list of numbers:
public class ControlStructureDemo {
public static void main(String[] args) {
int[] numbers = {10, -5, 0, 8, 15};
for (int num : numbers) {
// if-else-if for classification
if (num > 0) {
System.out.println(num + " is positive");
} else if (num < 0) {
System.out.println(num + " is negative");
continue; // Skip negative numbers
} else {
System.out.println(num + " is zero");
break; // Exit loop on zero
}
// switch to categorize magnitude
switch (num / 5) {
case 2:
System.out.println(num + " is large");
break;
case 1:
System.out.println(num + " is medium");
break;
default:
System.out.println(num + " is small");
}
}
// Exception handling
try {
int result = numbers[0] / numbers[2]; // Divide by zero
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero");
}
}
}
Output:
10 is positive
10 is medium
-5 is negative
0 is zero
Error: Division by zero
6.2. Explanation:
1. Uses a for-each loop to iterate over an array.
2. if-else-if classifies numbers as positive, negative, or zero.
3. continue skips negative numbers; break exits on zero.
4. switch categorizes positive numbers by magnitude.
5. try-catch handles a potential division-by-zero error.
4. Key Points
1. Nesting: Control structures can be nested (e.g., loops inside if statements).
2. Scope: Variables declared inside a block (e.g., {} in a loop or if) are local to that block.
3. Infinite Loops: Ensure loop conditions eventually become false to avoid infinite loops (e.g., while (true) without a break).
4. Java 12+ Enhancements: Switch expressions and pattern matching for instance of (Java 14+) simplify control flow.
5. Performance: Use break and continue judiciously to avoid confusing code. Prefer for-each for collections when index access isn’t needed.
6.3. BASIC OOP CONCEPT
1. Class
A class is a blueprint or template that defines what data (attributes) and actions (methods) an object can have. It’s like a plan for creating objects.
Key Points
· A class sets the structure but doesn’t hold actual data until an object is created.
· Example: A Person class might define that every person has a name and can say hello.
· In Java, classes are explicitly declared with types; in Python, they’re simpler and use dynamic typing.
Examples
Java:
class Person {
// Attributes and methods go here
}
Python:
class Person:
# Attributes and methods go here
pass
6.4. Object
What is an Object?
An object is a specific instance of a class, created from the class blueprint. It holds actual data and can perform the actions defined in the class.
Key Points
Objects are like individual items made from the class template.
Each object can have different data but follows the same structure.
Example: A person named Alice is an object of the Person class.
Examples
Java:
Person person = new Person(); // Creates an object
Python:
person = Person() # Creates an object
3. Attribute
An attribute is a piece of data (like a variable) that belongs to a class or object. It describes the object’s properties, such as its name or age.
Key Points
Attributes store information specific to an object.
In Java, attributes have explicit data types; in Python, types are inferred.
Example: A Person class might have attributes like name and age.
Examples
Java:
class Person {
String name; // Attribute
int age; // Attribute
}
Python:
class Person:
def __init__(self, name, age):
self.name = name # Attribute
self.age = age # Attribute
7. Method
A method is a function defined in a class that describes what an object can do. It can use or modify attributes or perform tasks.
Key Points
Methods are like actions or behaviors (e.g., a person saying hello).
They can return values or perform operations like calculations.
Example: A Person class might have a method to print a greeting.
Examples
Java:
class Person {
String name;
void sayHello() { // Method
System.out.println("Hello, my name is " + name);
}
}
Python:
class Person:
def __init__(self, name):
self.name = name
def say_hello(self): # Method
print(f"Hello, my name is {self.name}")
7.1. Why These Concepts Matter
Class: Defines the structure for objects.
Object: Holds specific data and performs actions.
Attribute: Stores data unique to each object.
Method: Defines what objects can do. Together, they make code organized, reusable, and easy to understand by modeling real-world entities.
7.2. Practical Examples
Below are two programs—one in Java and one in Python—demonstrating class, object, attribute, and method. They use basic data types (int, double/float, boolean, String/str, char), variables, expressions, assignment statements, and operators (arithmetic, relational, string concatenation), keeping the structure similar to your previous examples.
Java Example
class Person {
// Attributes String name;
int age; double height;
// In feet char initial;
boolean isAdult;
// Constructor to initialize attributes
Person(String name, int age, double height, char initial) {
this.name = name; // Assignment statement
this.age = age;
this.height = height;
this.initial = initial;
this.isAdult = age >= 18; // Expression with relational operator
}
// Method to display greeting
void sayHello() {
String greeting = "Hello, " + name; // Expression with string concatenation
System.out.println(greeting);
}
// Method to calculate height in meters
7.3. Practical Examples
double getHeightInMeters() {
return height * 0.3048; // Expression with arithmetic operator
}
// Method to describe the person
String getDescription() {
return name + " is " + age + " years old.";
}
}
public class BasicOOPConcepts { public static void main(String[] args) { // Create object Person person = new Person("Alice", 25, 5.9, 'A');
// Use attributes and methods
int yearsUntilRetirement = 65 - person.age; // Expression with arithmetic operator
double heightInMeters = person.getHeightInMeters(); // Call method
// Output results
System.out.println("Person Details:");
System.out.printf("Name: %s%n", person.name);
System.out.printf("Age: %d%n", person.age);
System.out.printf("Height: %.1f feet (%.2f meters)%n", person.height, heightInMeters);
System.out.printf("Initial: %c%n", person.initial);
System.out.printf("Is adult? %b%n", person.isAdult);
System.out.printf("Description: %s%n", person.getDescription());
System.out.printf("Years until retirement: %d%n", yearsUntilRetirement);
person.sayHello();
}
}