Control structures dictate the sequence of statement execution within a program, enabling the construction of small logical units that perform specific functions.
- Sequential Structure: Statements execute line by line from top to bottom, without any conditional checks or jumps.
- Selection Structure: Executes a specific code block based on a given condition.
- Includes
if…elseandswitchstatements.
- Includes
- Iteration Structure: Repeats a code block as long as a loop condition holds true.
- Includes
for,while, anddo-whileloops. - Note: JDK 5.0 introduced the
foreachloop, which simplifies iterating over collections and arrays (covered in the Collections topic).
- Includes
Selection Structure
The switch statement evaluates an expression against multiple constant cases.
switch(expression) {
case constant1:
codeBlock1;
// break;
case constant2:
codeBlock2;
// break;
// ...
[default:
defaultBlock;
break;
]
}
Key Points for switch:
- The
switchexpression's value must be one of:byte,short,char,int,enum(JDK 5.0), orString(JDK 7.0). caselabels must be constants, not variables, expressions with uncertain results, or ranges.- All
caseconstant values within a singleswitchstatement must be unique. - Fall-through Behavior: If a
caseblock lacks abreakstatement, execution will "fall through" to the nextcaseblock(s) without re-evaluating the condition, until abreakis encountreed or theswitchblock ends. - The
breakstatement exits theswitchblock. Without it, execution proceeds sequentially to the end. - The
defaultblock is optional and can be placed anywhere within theswitchstatement. It executes when nocasematches.
Comparing if-else and switch:
- Any logic implemented with
switchcan be rewritten usingif-else. The reverse is not always true. - Guideline: When both
switchandif-elseare applicable, preferswitchfor slightly better performance. - Detailed Comparison:
if-elseAdvantages:- The
ifcondition is a boolean expression, allowing checks for both equality and ranges, making it more versatile. switchonly tests for equality against constant values, making its use cases narrower.
- The
switchAdvantages:- When checking equality against fixed constants,
switchis often preferred due to slightly higher efficiency and cleaner syntax. Range checks are only possible withif. - Fall-through can be used to execute multiple blocks for a single match, a feature not present in
if-else.
- When checking equality against fixed constants,
Iteration Structure
Comparison of for, while, and do-while:
do-whileexecutes its loop body at least once.forandwhileevaluate the loop condition first before deciding to execute the body.- Fundamentally, all three loop types are interchangeable for implementing iteration logic.
- Use
forwhen the number of iterations (or a clear range) is known beforehand. - Use
whilewhen the iteration count is not predetermined. - Consider
do-whilewhen the loop body must execute at least once.
- Use
- Common infinite loop constructs:
while(true)andfor(;;).- These are useful when the termination condition is determined inside the loop body, using a
breakstatement.
- These are useful when the termination condition is determined inside the loop body, using a
break vs. continue:
break: Terminates the innermost enclosing loop orswitchstatement.continue: Skips the remaining code in the current iteration of the innermost loop and proceeds to the next iteration.- Both can be used with labels to specify which outer loop to break out of or continue. The label must be placed immediately before the loop statement.
// break ends the current statement block
{
...
break;
... // This code is unreachable
}
// Using a labeled break to exit an outer block
outerBlock: {
...
innerBlock: {
...
if (condition) {
break innerBlock; // Exits innerBlock
}
...
}
// Execution continues here after breaking innerBlock
}
Example using a labeled continue to optimize prime number checking:
class PrimeNumberFinder {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
int primeCount = 0;
candidateLoop: for (int candidate = 2; candidate <= 100000; candidate++) {
for (int divisor = 2; divisor <= Math.sqrt(candidate); divisor++) {
if (candidate % divisor == 0) {
continue candidateLoop; // Not a prime, skip to next candidate
}
}
System.out.println(candidate); // It's a prime number
primeCount++;
}
long endTime = System.currentTimeMillis();
System.out.println("Total prime numbers: " + primeCount);
System.out.println("Execution time (ms): " + (endTime - startTime));
}
}
Unlike the unstructured goto found in some languages, Java's break and continue provide controlled flow changes within loops and switches.
Reading Input with Scanner
The java.util.Scanner class is used to read different types of data (int, double, String, etc.) from the standard input (keyboard).
- Import the class:
import java.util.Scanner; - Create a
Scannerobject:Scanner inputReader = new Scanner(System.in); - Call the appropriate
nextXxx()method to read data of the expected type. - Close the resource:
inputReader.close();
Ensure the input value matches the expected type; otherwise, an InputMismatchException will occur.
import java.util.Scanner;
public class UserInputDemo {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Welcome to the Social Network!");
System.out.print("Enter your username: ");
String username = reader.next();
System.out.print("Enter your age: ");
int userAge = reader.nextInt();
System.out.print("Enter your weight (kg): ");
double userWeight = reader.nextDouble();
System.out.print("Are you single (true/false)? ");
boolean isSingle = reader.nextBoolean();
System.out.print("Enter your gender (M/F): ");
char userGender = reader.next().charAt(0); // Get first character
System.out.println("\nProfile Summary:");
System.out.println("Username: " + username);
System.out.println("Age: " + userAge);
System.out.println("Weight: " + userWeight);
System.out.println("Single: " + isSingle);
System.out.println("Gender: " + userGender);
reader.close();
}
}
Generating Random Integers in a Range:
Math.random()returns adoublevalue in the range[0.0, 1.0).- To obtain a random integer in the inclusive range
[a, b], use:(int)(Math.random() * (b - a + 1)) + a.