Comprehensive Study Guide to Java Conditionals, Boolean Logic, and Switch Constructs
Foundations of Boolean Logic and Relational Operators
Relational Operators:
In computer programming, algorithmic decisions are established by comparing values using relational operators.
There are six primary relational operators utilized to compare two values:
>: "is greater than"<: "is less than">=: "is greater than or equal to"<=: "is less than or equal to"==: "is equal to"!=: "is not equal to"Primary programming paradigms that rely on relational operators include:
Conditional branch statements (
if,if-else, andswitch).Iterative loops (
while,do-while, andfor) to regulate execution termination and continuation.Recursive methods to define base cases and prevent infinite recursion.
Boolean Concepts and Definitions:
Boolean Expression: An expression that evaluates strictly to one of two truth values:
trueorfalse.Boolean Condition: The actual
trueorfalseresultant state yielded by evaluating a Boolean expression.Evaluation examples:
evaluates totrue.evaluates tofalse.(4 >= 3) evaluates totrue.(4 <= 3) evaluates tofalse.evaluates tofalse.evaluates totrue.Arithmetic combined with relational operators:
evaluates totrue(integer division yields).evaluates tofalse(modulus division yields remainder).evaluates totrue.
Historical and Theoretical Foundations:
Named after George Boole, a 19th-century English mathematician who founded the field of Boolean logic (Boolean algebra), which forms the operational backbone of all digital computing logic.
Foundational logic gates used to build complex Boolean expressions:
NOTANDXOR(Exclusive OR)ORAdvanced Boolean algebra principles for analyzing and simplifying logical circuits and expressions include:
DeMorgan’s Law
Law of Absorption
Law of Involution
Idempotent Law
Law of the Disappearing Opposite
Truth table construction and evaluation
Hardware and Engineering Applications:
The study of Boolean expressions directly underlies the engineering and manufacturing of electronic circuit boards.
Electronic circuits direct and manipulate microscopic electrical currents through transistor-based logic gates.

Sequential Variable Tracing with Relational Operators:
Tracing the evolution of an integer variable across compound assignment and relational operations:
Initial state:
int age = 10;Evaluation:
System.out.println(age >= 16);→false(value:).
Compound addition:
age += 2;(state:)Evaluation:
System.out.println(age < 16);→true(value:).
Compound multiplication:
age *= 2;(state:)Evaluation:
System.out.println(age >= 16);→true(value:).
Compound subtraction:
age -= 4;(state:)Evaluation:
System.out.println(age > 20);→false(value:).
Decrement:
age--;(state:)Evaluation:
System.out.println(age != 20);→true(value:).
Compound division:
age /= 2;(state:due to integer truncation of)Evaluation:
System.out.println(age == 9);→true(value:).
One-Way and Two-Way Conditional Statements
One-Way Conditionals (
ifStatements):An
ifstatement is designated as a "one-way" conditional because code execution branches only when the condition evaluates totrue; whenfalse, the statement is skipped entirely.Formal syntax structure:
if (Boolean_Expression) Statement;orif (Boolean_Expression) { Block_Statements }.The Boolean expression must be enclosed within parentheses immediately following the
ifkeyword.Formatting and stylistic conventions:
Statements following an
ifconstruct can exist on the same line, but standard industry conventions dictate placing them on the next line with an indent or within braced blocks{}to make code structure legible.Execution trace of single-line branches:
Given
int num = 45;:if(num < 50) System.out.print("Hello "); System.out.println("Goodbye");→ Outputs:Hello Goodbye.if(num > 50) System.out.print("Hello "); System.out.println("Goodbye");→ Condition isfalse;System.out.print("Hello ");is bypassed; subsequent unconditioned line executes → Outputs:Goodbye.if(num != 50) System.out.print("Hello "); System.out.println("Goodbye");→ Condition istrue→ Outputs:Hello Goodbye.if(num % 5 == 0) System.out.print("Hello "); System.out.println("Goodbye");→istrue(, remainder) → Outputs:Hello Goodbye.if(num % 6 != 3) System.out.print("Hello "); System.out.println("Goodbye");→(, remainder), makingevaluate tofalse→ Outputs:Goodbye.
Given
int num = 55;:if(num <= 50) System.out.print("Hello "); System.out.println("Goodbye");→ Condition isfalse→ Outputs:Goodbye.
Two-Way Conditionals (
if-elseStatements):An
if-elsestatement offers a binary branch: one code block executes if the condition istrue, and an alternative block executes under theelseumbrella if the condition isfalse.Parallel testing comparisons with fixed values
and:if (5 < 10)→true→ Executes statement1A.if (5 <= 10)→true→ Executes statement2A.if (5 > 10)→false→ Executes statement3B.if (5 >= 10)→false→ Executes statement4B.if (5 == 10)→false→ Executes statement5B.if (5 != 10)→true→ Executes statement6A.
Classic Algorithmic Implementations:
Age Verification Construct:
Logic to verify driving eligibility using standard console input (
Scanner):java if (age >= 16) { System.out.println("Ok to drive."); } else { System.out.println("Too young to drive."); } Test behaviors:
Input
12→ Outputs:Too young to drive.Input
16→ Outputs:Ok to drive.Input
20→ Outputs:Ok to drive.
Parity (Even/Odd) Determination:
Boolean expression determining even state:
x % 2 == 0.Boolean expression determining odd state:
x % 2 == 1orx % 2 != 0.Implementation:
java if (number % 2 == 0) { System.out.println("Even number"); } else { System.out.println("Odd number"); } Test behaviors:
Input
12→ Outputs:Even number.Input
25→ Outputs:Odd number.
Divisibility and Multiples Calculation:
Verification of factor divisibility by
:java if (number % 5 == 0) { System.out.println("Multiple of 5"); } else { System.out.println("Not a multiple of 5"); }
Test behaviors:
Input
1760→→ Outputs:Multiple of 5.Input
-1324→→ Outputs:Not a multiple of 5.Input
2345→→ Outputs:Multiple of 5.
Real-World Applied Problem Scenarios:
E-Commerce Order Thresholds:
Scenario: Orders costing
or more qualify for complimentary shipping; all other orders incur acharge.Implementation:
java if (total >= 50.00) { System.out.println("Free shipping"); } else { System.out.println("Shipping: $7.99"); }
Parking Garage Rate Computation:
Pricing formula: Base rate of
covers up to the firsthours. Every subsequent hour costs an additional.Implementation:
java double fee; if (hours <= 2) { fee = 5.00; } else { fee = 5.00 + (hours - 2) * 1.50; } System.out.println("Fee: $" + fee);
Numerical derivations across discrete input intervals:
Duration
2hours:fee = 5.00→ Output:5.0Duration
3hours:fee = 5.00 + (3 - 2) * 1.50 = 6.50→ Output:6.5Duration
5hours:fee = 5.00 + (5 - 2) * 1.50 = 5.00 + 4.50 = 9.50→ Output:9.5
Multi-Way Decision Structures and Range Evaluations
if-else-if-elseChains:Multi-way selection chains represent the optimal control mechanism when program logic must evaluate among more than two distinct outcomes.
Conditions are evaluated top-down; as soon as a condition evaluates to
true, its corresponding block executes and the remaining chain is bypassed.
String Operations in Conditional Logic:
String.length(): Class method returning anintcount of total characters within a String.Example:
"Hello".length()evaluates to.String length classification algorithm (threshold:
is short;is long):java if (word.length() <= 8) { System.out.println("This is a short word."); } else { System.out.println("This is a long word."); } Trace results:
Input
"Hello"(length) → Outputs:This is a short word.Input
"Goodbye"(length) → Outputs:This is a short word.Input
"Salutations"(length) → Outputs:This is a long word.
Tracing String evaluation test cases:
Given
String word = "Hello";:if(word.length() > 10) System.out.print("Hello "); System.out.println("Goodbye");→word.length()is; conditionfalse→ Outputs:Goodbye.Given
String word = "Hello, There!";(length):if(word.length() >= 13) System.out.print("Hello "); System.out.println("Goodbye");→istrue→ Outputs:Hello Goodbye.if(word.length() % 2 == 0) System.out.print("Hello "); System.out.println("Goodbye");→(false) → Outputs:Goodbye.Given
String word = "Billy Goats Gruff";(length):if(word.length() > 10) System.out.print("Hello "); else System.out.println("Goodbye");→istrue→ Outputs:Hello.if(word.length() <= 15) System.out.print("Hello "); else System.out.println("Goodbye");→isfalse→ Outputs:Goodbye.if(word.charAt(1) == 'B') System.out.print("Trip "); else System.out.println("Trap");→ Index1is character'i';'i' == 'B'isfalse→ Outputs:Trap.if(word.charAt(15) == 'f') System.out.print("Trip "); else System.out.println("Trap");→ Index15is'f';'f' == 'f'istrue→ Outputs:Trip.
Given
String word = "Three Little Pigs";(length):(, remainder).Evaluates
word.length() % 3 == 0→false.Evaluates
word.length() % 3 == 1→false.Falling to
elsebranch → Outputs:Blow.
Continuous Range Evaluation Systems:
Academic Grade Categorization:
java if (grade >= 90) { System.out.println("A"); } else if (grade >= 80) { System.out.println("B"); } else if (grade >= 70) { System.out.println("C"); } else { System.out.println("F"); } Trace results:
Grade
100→100 >= 90istrue→ Outputs:A.Grade
88→88 >= 90isfalse,88 >= 80istrue→ Outputs:B.Grade
75→75 >= 70istrue→ Outputs:C.Grade
64→ All conditions evaluate tofalse→ Outputs:F.
Temperature Range Evaluation:
java if (temp >= 90) { System.out.println("Hot"); } else if (temp >= 70) { System.out.println("Nice"); } else if (temp >= 50) { System.out.println("Cool"); } else { System.out.println("Cold"); } Trace results:
Input
temp = 58→58 >= 90(false),58 >= 70(false),58 >= 50(true) → Outputs:Cool.Input
temp = 90→90 >= 90(true) → Outputs:Hot.
Limitation of Switch Statements on Continuous Ranges:
Converting continuous range
if-elsechains (such as temperature bands or letter grade ranges) into switch structures is problematic.A
switchconstruct matches discrete, exact values. Because each grade or temperature category spans an infinite or large set of integer/decimal values, each specific number would need to be enumerated as its own uniquecase.
Switch Statements: Syntax, Execution Mechanics, and Evolution
Overview of Switch Constructs:
A
switchstatement provides a structured alternative to replace multi-wayif-elsechains when checking a single control variable against distinct target values.Primary reserved keywords:
switch: Initiates the block and identifies the evaluation expression/variable.case: Flags specific selector matching values.break: Exits the switch construct execution block.default: Catches any input values that fail to match any listedcase.
Permitted and Prohibited Data Types:
Permitted selector variable types:
Primitive integer types (
int,short,byte)Character type (
char)String objects (
String)Prohibited selector variable types:
Decimal values (
double,float)Boolean values (
boolean)
Core Advantages of Switch Statements:
Easier to read.
Easier to understand.
Easier to debug.
Easier to maintain.
Usage Guidelines:
Appropriate when the variable to evaluate is strictly an integer, character, or String.
Appropriate when the list of selector cases is relatively concise (an upper limit around the
letters of the alphabet).Appropriate when replacing an
if-elsechain significantly reduces clutter and improves structural clarity.
Older Colon Syntax and the Mechanics of Fall-Through:
Traditional syntax requires explicit colons after selector values and manual termination:
java switch (inputLetter) { case 'A': System.out.println(".-"); break; case 'B': System.out.println("-..."); break; case 'C': System.out.println("-.-."); break; }
Execution trace:
When evaluating variable
let = 'B', the runtime checkscase 'A'. Because it does not match, it checks the next case.Upon finding a match at
case 'B', execution "jumps the fence," prints-..., and halts execution upon encountering thebreakkeyword.
Fall-Through Behavior:
If a
breakstatement is omitted, execution falls through unconditionally into subsequentcaseblocks, executing statements regardless of whether subsequent case labels match, until abreakor the closing brace is reached.Example: Omitting
breakoncase 'A'results in outputs for both'A'and'B':.-followed immediately by-....Example: In an older Morse code switch spanning
'A'through'G', omitting allbreakstatements and executing on input'C'produces:-.-.-.....-.--.
Intentional Fall-Through (Grouped Cases):
Stacking case labels without interleaving
breakstatements allows multiple inputs to share the same resulting block.Categorization example mapping 10 cases to 3 distinct output paths:
java switch (name) { case "JOE": case "BILL": case "JEANNIE": case "HOLLY": case "SAM": System.out.println("BFF"); break; case "MARY": case "BOB": case "LEE": case "CINDY": case "JOHN": System.out.println("GOOD FRIEND"); break; default: System.out.println("STRANGER"); }
Schedule mapping example using older syntax:
java switch (period) { case 1: System.out.println("First Period, Algebra II"); break; case 2: System.out.println("Second Period, English"); break; case 3: System.out.println("Third Period, Chemistry"); break; case 4: System.out.println("Fourth Period, Band"); break; case 5: System.out.println("Fifth Period, American History"); break; case 6: System.out.println("Sixth Period, Computer Science"); break; } Newer Arrow (
->) Syntax:Modern Java introduces arrow syntax, which eliminates unintended fall-through entirely.
Only the code block corresponding to the exact matching case runs; no
breakkeyword is required or permitted.Trace comparison between syntaxes using
char c = 'B';:Older syntax with fall-through:
java switch (c) { case 'A': System.out.print("1 "); case 'B': System.out.print("2 "); case 'C': System.out.print("3 "); break; } Outputs:
2 3because execution enters at'B'and falls through into'C'before reaching thebreak.
Modern arrow syntax:
java switch (c) { case 'A' -> System.out.print("1 "); case 'B' -> System.out.print("2 "); case 'C' -> System.out.print("3 "); } Outputs:
2because only the directly matching branch executes.
Arrow Syntax Code Applications:
Day of the Week Mapping:
java int day = 3; String name; switch (day) { case 1 -> name = "Monday"; case 2 -> name = "Tuesday"; case 3 -> name = "Wednesday"; default -> name = "Weekend"; } System.out.println(name); Input
day = 3→ Outputs:Wednesday.Input
day = 7→ Matches no case label; triggersdefault→ Outputs:Weekend.
T-Shirt Size Translation:
Converting an
if-elsechain into arrow switch syntax:java switch (size) { case 'S' -> System.out.println("Small"); case 'M' -> System.out.println("Medium"); case 'L' -> System.out.println("Large"); default -> System.out.println("Unknown size"); }
Multi-Statement Blocks with Curly Braces:
When a matched case requires multiple commands (such as updating multiple variables), statements are wrapped inside curly braces
{}.Sport venue mapping:
java String sport = "Soccer"; String season, field; switch (sport) { case "Football" -> { season = "Fall"; field = "Stadium"; } case "Soccer" -> { season = "Spring"; field = "Pitch"; } default -> { season = "Unknown"; field = "none"; } } System.out.println(sport + " is played in " + season + " on the " + field); Execution for
"Soccer"produces:Soccer is played in Spring on the Pitch.
String-Based Multilingual Translation System:
Single-statement mapping:
java switch (inputLanguage) { case "Spanish" -> translate = "¡Hola Mundo!"; case "German" -> translate = "Hallo Welt!"; case "French" -> translate = "Bonjour le monde!"; case "Italian" -> translate = "Ciao mondo!"; case "Swahili" -> translate = "Habari Dunia!"; case "Esperanto" -> translate = "Saluton Mondo!"; default -> translate = "Language not supported."; }
Compound multi-statement mapping with formatted output:
java switch (language) { case "Spanish" -> { translate = "¡Hola Mundo!"; country = "Mexico"; } case "German" -> { translate = "Hallo Welt!"; country = "Germany"; } case "French" -> { translate = "Bonjour le monde!"; country = "France"; } default -> { translate = "Language not supported."; country = "none"; } } System.out.printf("In %s they say Hello World! as %s%n", country, translate); Input
"Spanish"→ Outputs:In Mexico they say Hello World! as ¡Hola Mundo!.