Control Statements, Boolean Logic, and Loops in Java
Fundamentals of Program Control Flow
Sequential Execution Baseline: Standard computer programs execute sequentially from top to bottom, beginning at line and proceeding sequentially to the final statement.
Control Statements: Mechanisms that alter the sequential flow of program execution through a method fall into two distinct structural categories:
Conditionals (Selection Statements): Enable decision-making by selecting alternative execution paths based on evaluated conditions.
Loops (Repetition Statements): Enable repetitive execution of code blocks based on evaluated conditions.
Boolean Foundation: Both conditional statements and loops rely entirely on boolean expressions that evaluate strictly to either
trueorfalse.
Selection Statements: If, Else, and Multi-Branch Logic
Conditional Statement Definition: A selection statement permits a program to determine which action or block of statements to execute next at runtime.
Java Selection Statements:
In Java (specifically on the AP Computer Science A Examination), selection is implemented using
ifandif-elsestatements.switchstatements exist within Java syntax but are explicitly excluded from the AP Computer Science A syllabus.
The Basic
ifStatement:Evaluates a boolean expression. If the condition evaluates to
true, the subsequent statement or enclosed block executes; iffalse, execution bypasses the body entirely.

Implementation example:
java import java.util.Scanner; class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("What is your grade on the test? "); int grade = scan.nextInt(); if (grade >= 80) System.out.println("Good job"); } } The Two-Way
if-elseStatement:Directs program flow between two mutually exclusive alternatives. When the boolean expression is
true, theifblock executes; whenfalse, theelseblock executes.

Implementation example:
java if (grade >= 80) System.out.println("Good job"); else System.out.println("Someone's in trouble!!"); Nested
ifStatements vs. Chainedelse ifLadders:Deep nesting places subsequent conditional branches inside nested
elseblocks, which quickly degrades code readability with multiple indentation levels and braces.

Chaining using
else ifcreates a flat, sequential decision ladder that evaluates each condition in order until a true condition is met, bypassing all remaining branches.

Chained grading scale implementation:
java if (grade == 100) System.out.println("You were perfect!! A+"); else if (grade >= 90) System.out.println("You got an A!"); else if (grade >= 80) System.out.println("You got a B."); else if (grade >= 70) System.out.println("You got a C."); else if (grade >= 60) System.out.println("You got a D...you might want a tutor"); else System.out.println("You failed...please get tutoring"); Conditional Flow Tracing and Dangling Else Resolution:
In Java, an
elseclause binds to the closest preceding unmatchedifwithin the same block scope.Tracing problem:
java int a = /* unknown value */; int b = /* unknown value */; if (a > 0) if (b < 0) System.out.print("A"); else if (a > 5) System.out.print("B"); else System.out.print("C"); else System.out.print("D"); Execution paths to reach each output:
Path to "A": Requires and .
Path to "B": Requires , , and .
Path to "C": Requires , , and (that is, with ).
Path to "D": Requires (bypassing the outer
ifentirely, regardless of ).
Minimum Value Determination Task:
Algorithm requirement: Accept three integers from user input via a
Scannerinstance, evaluate their relative values using selection statements, and output the minimum integer.
Relational and Equality Operators
Operator Inventory:
==: Equal to!=: Not equal to<: Less than<=: Less than or equal to>: Greater than>=: Greater than or equal to
Strict Primitive Usage Rule:
Relational operators (
<,<=,>,>=) and equality operators (==,!=) are strictly intended for primitive data types (int,double,boolean,char).Applying
==or!=to object reference variables compares memory references (memory addresses) rather than the underlying contents of the objects.
Logical Operators and Boolean Algebra
Java Logical Operators:
!(Logical NOT): Unary operator that negates the boolean value. Ifaistrue,!aisfalse; ifaisfalse,!aistrue.&&(Logical AND): Binary operator that yieldstrueif and only if both left and right operands evaluate totrue. Yieldsfalseotherwise.||(Logical OR): Binary operator that yieldstrueif either the left operand, right operand, or both operands evaluate totrue. Yieldsfalseonly when both operands evaluate tofalse.
Evaluating Compound Boolean Expressions:

Code snippet:
java import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Type two integers: "); int num1 = scan.nextInt(); int num2 = scan.nextInt(); if (num1 > 5 && num2 < 8) System.out.println("AAA"); else if (num1 > 5 || num2 < 8) System.out.println("BBB"); else System.out.println("CCC"); } } Input conditions and output mappings:
"AAA" Output: Both conditions must hold: and (e.g., , ).
"BBB" Output: The first condition fails, but at least one sub-condition holds: (e.g., , or , ).
"CCC" Output: Neither condition holds: and (e.g., , ).
Short-Circuit Evaluation:
Java optimizes compound boolean expressions by evaluating operands strictly from left to right, terminating evaluation the instant the result is guaranteed:
In
a && b, ifaisfalse, the entire expression must evaluate tofalse; operandbis never evaluated.In
c || d, ifcistrue, the entire expression must evaluate totrue; operanddis never evaluated.Practical Utility (Guard Expressions): Prevents fatal runtime errors such as division by zero or null reference exceptions:
java if (count != 0 && sum / count > 90) System.out.println("Great job, an A average!"); If , the expression
count != 0evaluates tofalse. Short-circuiting guaranteessum / count > 90is bypassed, preventing anArithmeticException(/ by zero).
De Morgan's Laws:
Logical equivalences governing the distribution of negation across conjunctions and disjunctions:
(in Java:
!(A && B)is equivalent to!A || !B)
(in Java:
!(A || B)is equivalent to!A && !B)Negating relational operators:
!(a >= b)simplifies toa < b!(a < b)simplifies toa >= b!(a == b)simplifies toa != b
Analytical Boolean Problems and Proofs
Problem 1 (Contradiction Analysis):
Expression:
(x && y) && !(x || y)Analytical simplification:
By De Morgan's Law:
!(x || y)is equivalent to!x && !y.The expression becomes
(x && y) && (!x && !y).Rearranging terms yields
(x && !x) && (y && !y).Because
x && !xevaluates tofalseunder all circumstances, the overall expression evaluates to false always.Truth table verification:
|
|
|
| ||
|---|---|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Problem 2 (Relational Precedence and Arithmetic):
Expression:
(3 + 4 == 5) != (3 + 4 >= 5)Step-by-step reduction:
Evaluate arithmetic operations: .
Evaluate left relational expression:
7 == 5evaluates tofalse.Evaluate right relational expression:
7 >= 5evaluates totrue.Evaluate boolean inequality:
false != trueevaluates to true.
Problem 3 (Conjunctive Absorption with Negated Disjunction):
Expression:
a && !(b || a)Step-by-step reduction:
Apply De Morgan's Law:
!(b || a)simplifies to!b && !a.Substitute back:
a && !b && !a.Commute operands:
(a && !a) && !b.Because
a && !aevaluates unconditionally tofalse, the entire expression is always false.
Problem 4 (Tautology / Law of Excluded Middle):
Expression:
(x && y) || !(x && y)Analytical structure:
Let .
The expression conforms to the fundamental tautology .
Any boolean expression ORed with its exact negation evaluates to always true.
Problem 5 (Three-Variable De Morgan Application):
Target expression:
!x || !y || zAnalytical reduction:
Group first two disjuncts:
(!x || !y) || z.By De Morgan's Law,
!x || !yis logically equivalent to!(x && y).Recombining gives
!(x && y) || z.
Problem 6 (Negating Compound Relational Logic):
Target expression:
!((a >= b) && !(c < d))Analytical reduction:
Apply De Morgan's Law across outer negation:
!(a >= b) || !(!(c < d)).Invert
!(a >= b)intoa < b.Eliminate double negation
!(!(c < d))intoc < d.Final equivalent expression:
(a < b) || (c < d).
String and Object Comparison
Object Reference Equality vs. Content Equality:
The equality operator
==checks whether two reference variables point to the exact same memory address on the heap.The
.equals()method inspects the state/content of the objects to determine lexical equivalence.Relational comparison operators (
<,<=,>,>=) cannot be applied toStringobjects or any non-primitive objects in Java; attempting to do so generates a compiler error.
The
.compareTo()Method Mechanics:Syntax:
string1.compareTo(string2)Lexicographical comparison based on underlying Unicode/ASCII numerical values:
Returns a negative integer if
string1precedesstring2alphabetically.Returns if
string1is identical in content tostring2.Returns a positive integer if
string1followsstring2alphabetically.ASCII Precedence Detail: Uppercase letters ('A' through 'Z', ASCII values through ) precede lowercase letters ('a' through 'z', ASCII values through ). Thus, uppercase characters are numerically "less than" lowercase characters.
Reference Trace of String Comparisons:
Variable declarations:
java String word1 = "ants"; String word2 = "bears"; String word3 = "cats"; String word4 = "ants"; String word5 = "Tigers"; String word6 = new String("ants"); Evaluation outcomes:
word1.equals(word4):true(contents match: "ants" vs "ants")word1 == word4:true(string literal pooling maps both references to the identical interned memory address)word1.compareTo(word2):negative #('a' precedes 'b')word2.compareTo(word3):negative #('b' precedes 'c')word3.compareTo(word4):positive #('c' follows 'a')word4.compareTo(word5):positive #(lowercase 'a' has ASCII , uppercase 'T' has ASCII ; )word1.equals(word6):true(both store identical character sequences "ants")word1 == word6:false(word6was created usingnew, allocating a distinct object on the heap with a distinct address)
String Method Applications in Conditionals:

input.toLowerCase().equals("yes"): Tests for exact whole-word match, normalizing case.input.indexOf("yes") != -1: Tests whether the substring "yes" appears anywhere within the input string.Independent
ifstatements vsif-else: When two standaloneifstatements are used sequentially, both code blocks can execute if both conditions evaluate totrue.Alphabetical Word Ordering Implementation:

Code snippet:
java System.out.print("Type in two words: "); String w1 = scan.next(); String w2 = scan.next(); if (w1.compareTo(w2) < 0) System.out.println(w1 + " comes before " + w2); else if (w1.compareTo(w2) > 0) System.out.println(w1 + " comes after " + w2); else System.out.println("You typed the same word twice!!");
Compound Assignment and Increment/Decrement Operators
Operator Behavior and Expanded Equivalents:
=: Assignment (x = yassigns the value ofyintox).++: Increment (x++adds tox; equivalent tox = x + 1).--: Decrement (x--subtracts fromx; equivalent tox = x - 1).+=: Addition then assignment (x += yis equivalent tox = x + y).+=(String context) : String concatenation then assignment (x += yappends stringyto stringx).-=: Subtraction then assignment (x -= yis equivalent tox = x - y).*=: Multiplication then assignment (x *= yis equivalent tox = x * y)./=: Division then assignment (x /= yis equivalent tox = x / y).%=: Remainder/Modulus then assignment (x %= yis equivalent tox = x % y).
Repetition Statements: While Loops
While Loop Structure:
Evaluates a boolean condition prior to each iteration.
The loop body continues executing repeatedly until the tested condition evaluates to
false.If the condition is
falseupon initial check, the loop body executes zero times.
Infinite Loops:
Occur when the tested condition never transitions to
false.

Cause: In the code above,
int i = 0; while (i <= 1000) System.out.println(i);, the loop control variableiis never incremented, creating an infinite loop that repeatedly outputs .Sentinel-Controlled Loops:
Continue iterating until a specific value (the sentinel value) is supplied by user input or an external source.

Example:
java import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String input = ""; while (input.equals("STOP") == false) { System.out.print("Do you want to play a game? "); input = scan.nextLine(); } System.out.println("Fine! You don't have to yell!!"); } } Integer Digit Reversal Algorithm:

Algorithmic mechanics:
Extract the lowest-order digit via modulo :
num % 10.Shift existing reversed digits left by one base- power:
temp *= 10.Append the extracted digit:
temp += num % 10.Truncate the lowest-order digit from the original number via integer division by :
num /= 10.Terminate when
num == 0.
Complete code:
java public static int reverse(int num) { int temp = 0; while (num != 0) { temp *= 10; temp += num % 10; num /= 10; } return temp; } String Filtering and Accumulation via While Loop:
Code snippet:
java String text = "AP COMPUTER SCIENCE A"; String x = ""; int loc = 0; while (loc < text.length()) { if (text.substring(loc, loc + 1).compareTo("M") <= 0 && !text.substring(loc, loc + 1).equals(" ")) x += text.substring(loc, loc + 1); loc++; } System.out.println(x); Trace analysis: Accumulates characters from
"AP COMPUTER SCIENCE A"that are lexicographically and not equal to a space character:'A' () -> accumulated
'P' () -> skipped
' ' (space) -> skipped
'C' () -> accumulated
'O' () -> skipped
'M' () -> accumulated
'P', 'U', 'T' () -> skipped
'E' () -> accumulated
'R', ' ', 'S' -> skipped
'C', 'I', 'E' () -> accumulated
'N' () -> skipped
'C', 'E' () -> accumulated
' ' -> skipped
'A' () -> accumulated
Final value printed:
"ACMECEICEA".
Nested While Loops (Multiplication Table):
Nested repetition structures execute the entire inner loop cycle for each individual iteration of the outer loop.
Implementation ( grid):
java int x = 1; while (x <= 10) { int y = 1; while (y <= 10) { System.out.print(x * y + "\t"); y++; } System.out.println(); x++; }
Repetition Statements: For Loops
Loop Selection Criteria:
whileloops: Preferred when the number of iterations is unknown prior to entering the loop (indefinite iteration, such as awaiting specific user input or state changes).forloops: Preferred when the exact number of iterations is known or fixed in advance (definite iteration, such as counting over ranges or traversing fixed structures).
Header Components and Scope:

A standard
forloop header consists of three segments separated by semicolons:for (initialization; conditional statement; increment/decrement)Initialization: Declares and assigns the loop control variable (e.g.,
int i = 1). Crucial scope rule: Variables declared within theforloop header exist strictly within the loop's block scope and cannot be referenced outside the loop.Conditional Statement: Evaluated before every iteration (e.g.,
i < 100). The body executes only if this evaluates totrue.Update (Increment/Decrement): Executes immediately following each execution of the loop body (e.g.,
i++).
Table of squares example:
java System.out.println("SQUARES"); for (int i = 1; i < 100; i++) System.out.println(i + "\t" + i * i); Structural Equivalence between
forandwhileLoops:A definite counting loop written as a
forloop:java for (int i = 0; i < 1000; i++) { System.out.println(i); }
The functionally equivalent
whileloop:java int i = 0; while (i < 1000) { System.out.println(i); i++; } Note on scope difference: In the
whileimplementation,iremains in scope after loop termination, whereas in theforimplementation,igoes out of scope.
String Traversal using
forLoops:Filtering characters lexicographically () from
"HELLO WORLD":java String text = "HELLO WORLD"; for (int i = 0; i < text.length(); i++) { if (text.substring(i, i + 1).compareTo("M") < 0) System.out.println(text.substring(i, i + 1)); } Execution trace on
"HELLO WORLD":Index : 'H' () -> prints "H"
Index : 'E' () -> prints "E"
Index : 'L' () -> prints "L"
Index : 'L' () -> prints "L"
Index : 'O' () -> skipped
Index : ' ' (Space ASCII ) -> prints " "
Index : 'W' () -> skipped
Index : 'O' () -> skipped
Index : 'R' () -> skipped
Index : 'L' () -> prints "L"
Index : 'D' () -> prints "D"
Modulo and Compound Filter Tracing:
Code snippet:
java String text = "Rusty Curry"; for (int i = 0; i < text.length(); i++) { if (text.substring(i, i + 1).equals("s") || i % 3 == 0) System.out.print(text.substring(i, i + 1)); }
Tracing indices of
"Rusty Curry":Index : 'R' () -> prints "R"
Index : 'u' (, not "s") -> skipped
Index : 's' (equals "s") -> prints "s"
Index : 't' () -> prints "t"
Index : 'y' -> skipped
Index : ' ' -> skipped
Index : 'C' () -> prints "C"
Index : 'u' -> skipped
Index : 'r' -> skipped
Index : 'r' () -> prints "r"
Index : 'y' -> skipped
Complete output:
"RstCr".
Nested
forLoops (Star Pattern Generation):Implementation:
java for (int i = 0; i < 10; i++) { for (int j = 0; j < i; j++) System.out.print("*"); System.out.println(); }
Behavior: Generates a triangular star display. When , the inner loop executes times (prints a newline). For each subsequent line from to , exactly asterisks are printed, producing lines of lengths through .
String Traversal Patterns and Idioms
Standard Forward Traversal:
Using a
forloop:java for (int i = 0; i < text.length(); i++) { String ch = text.substring(i, i + 1); }
Using a
whileloop:java int i = 0; while (i < text.length()) { String ch = text.substring(i, i + 1); i++; } Reverse Traversal:
To process characters from right to left, initialize at
text.length() - 1and decrement down to index :java for (int i = text.length() - 1; i >= 0; i--) { String ch = text.substring(i, i + 1); }
Pattern-Matching / Substring Elimination Traversal:
Loops conditioned on
indexOfsearch for targets and iteratively modify the source string:java while (text.indexOf(something) != -1) { // code modifying text to eventually render condition false }
Algorithmic Implementations and Projects
Algorithm 1: Sum of Divisible Integers (
sumDivisible):Problem Specification: Compute the sum of all integers between
startandend(inclusive) that are evenly divisible bydivisor. Return ifstart > end.Implementation:
java public static int sumDivisible(int start, int end, int divisor) { if (start > end) return -1; int sum = 0; for (int i = start; i <= end; i++) { if (i % divisor == 0) sum += i; } return sum; }
Algorithm 2: Counting Adjacent Double Letters (
countDoubleLetters):Problem Specification: Count occurrences where two identical characters appear directly adjacent in a string (e.g.,
"bookkeeper"returns for 'oo', 'kk', and 'ee').Implementation:
java public static int countDoubleLetters(String str) { int count = 0; for (int i = 0; i < str.length() - 1; i++) { if (str.substring(i, i + 1).equals(str.substring(i + 1, i + 2))) count++; } return count; } Boundary safety: Loop terminates at
str.length() - 1to ensuresubstring(i + 1, i + 2)does not throw aStringIndexOutOfBoundsExceptionat the string's final character.
Game Implementation 1: Guess My Number (User Guesses):

Logic requirements:
Generate random integer in via
1 + (int)(max * Math.random()).Prompt user for guesses iteratively.
If guess target, print "Too Low…" (higher).
If guess target, print "Too High…" (lower).
Terminate loop when guess equals target, output total guess count, and print a concluding message.
Game Implementation 2: High Low Game Version 2.0 (Computer Guesses):

Logic requirements:
The user holds an integer in mind within a specified range.
Computer maintains lower and upper bounds, generating guesses within the current interval.
User enters feedback: "higher" (computer adjusts lower bound), "lower" (computer adjusts upper bound), or "correct".
Repeat iteratively until user enters "correct", then output total guesses taken.
Major Project: Decision Tree Simulation Games:
Game variants: "Rock, Paper, Scissors", "Rock, Paper, Scissors, Lizard, Spock", and "Giants, Wizards, Elves".
Decision Rules for "Giants, Wizards, Elves":
Giants beat Elves: Giants squash Elves.
Elves beat Wizards: Elves outsmart Wizards and chew at their legs.
Wizards beat Giants: Wizards zap Giants with a magic spell.