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, and switch).

    • Iterative loops (while, do-while, and for) 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: true or false.

    • Boolean Condition: The actual true or false resultant state yielded by evaluating a Boolean expression.

    • Evaluation examples:

    • 4>34 > 3 evaluates to true.

    • 4<34 < 3 evaluates to false.

    • 4≥34 ≥ 3 (4 >= 3) evaluates to true.

    • 4≤34 ≤ 3 (4 <= 3) evaluates to false.

    • 4==34 == 3 evaluates to false.

    • 4!=34 != 3 evaluates to true.

    • Arithmetic combined with relational operators:

      • 15/3==515 / 3 == 5 evaluates to true (integer division yields 55).

      • 15 % 3==515 \text{ \% } 3 == 5 evaluates to false (modulus division yields remainder 00).

      • 15 % 3==015 \text{ \% } 3 == 0 evaluates to true.

  • 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:

    • NOT

    • AND

    • XOR (Exclusive OR)

    • OR

    • Advanced 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.

Logic gate learning board displaying discrete circuits, LEDs, pushbuttons, and truth tables for AND, OR, NAND, NOR, XOR, and NOT 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: 1010).

    • Compound addition: age += 2; (state: 1212)

      • Evaluation: System.out.println(age < 16); → true (value: 1212).

    • Compound multiplication: age *= 2; (state: 2424)

      • Evaluation: System.out.println(age >= 16); → true (value: 2424).

    • Compound subtraction: age -= 4; (state: 2020)

      • Evaluation: System.out.println(age > 20); → false (value: 2020).

    • Decrement: age--; (state: 1919)

      • Evaluation: System.out.println(age != 20); → true (value: 1919).

    • Compound division: age /= 2; (state: 99 due to integer truncation of 19/219 / 2)

      • Evaluation: System.out.println(age == 9); → true (value: 99).

One-Way and Two-Way Conditional Statements

  • One-Way Conditionals (if Statements):

    • An if statement is designated as a "one-way" conditional because code execution branches only when the condition evaluates to true; when false, the statement is skipped entirely.

    • Formal syntax structure:

    • if (Boolean_Expression) Statement; or if (Boolean_Expression) { Block_Statements }.

    • The Boolean expression must be enclosed within parentheses immediately following the if keyword.

    • Formatting and stylistic conventions:

    • Statements following an if construct 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 is false; System.out.print("Hello "); is bypassed; subsequent unconditioned line executes → Outputs: Goodbye.

      • if(num != 50) System.out.print("Hello "); System.out.println("Goodbye"); → Condition is true → Outputs: Hello Goodbye.

      • if(num % 5 == 0) System.out.print("Hello "); System.out.println("Goodbye"); → 45 % 5==045 \text{ \% } 5 == 0 is true (45/5=945 / 5 = 9, remainder 00) → Outputs: Hello Goodbye.

      • if(num % 6 != 3) System.out.print("Hello "); System.out.println("Goodbye"); → 45 % 6=345 \text{ \% } 6 = 3 (45/6=745 / 6 = 7, remainder 33), making 3!=33 != 3 evaluate to false → Outputs: Goodbye.

    • Given int num = 55;:

      • if(num <= 50) System.out.print("Hello "); System.out.println("Goodbye"); → Condition is false → Outputs: Goodbye.

  • Two-Way Conditionals (if-else Statements):

    • An if-else statement offers a binary branch: one code block executes if the condition is true, and an alternative block executes under the else umbrella if the condition is false.

    • Parallel testing comparisons with fixed values 55 and 1010:

    • if (5 < 10) → true → Executes statement 1A.

    • if (5 <= 10) → true → Executes statement 2A.

    • if (5 > 10) → false → Executes statement 3B.

    • if (5 >= 10) → false → Executes statement 4B.

    • if (5 == 10) → false → Executes statement 5B.

    • if (5 != 10) → true → Executes statement 6A.

  • 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."); } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

    • 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 == 1 or x % 2 != 0.

    • Implementation: java if (number % 2 == 0) { System.out.println("Even number"); } else { System.out.println("Odd number"); } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

    • Test behaviors:

    • Input 12 → Outputs: Even number.

    • Input 25 → Outputs: Odd number.

  • Divisibility and Multiples Calculation:

    • Verification of factor divisibility by 55: java if (number % 5 == 0) { System.out.println("Multiple of 5"); } else { System.out.println("Not a multiple of 5"); } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Test behaviors:

    • Input 1760 → 1760 % 5==01760 \text{ \% } 5 == 0 → Outputs: Multiple of 5.

    • Input -1324 → −1324 % 5≠0−1324 \text{ \% } 5 \neq 0 → Outputs: Not a multiple of 5.

      • Input 2345 → 2345 % 5==02345 \text{ \% } 5 == 0 → Outputs: Multiple of 5.

  • Real-World Applied Problem Scenarios:

    • E-Commerce Order Thresholds:

    • Scenario: Orders costing $50.00\$50.00 or more qualify for complimentary shipping; all other orders incur a $7.99\$7.99 charge.

    • Implementation: java if (total >= 50.00) { System.out.println("Free shipping"); } else { System.out.println("Shipping: $7.99"); } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Parking Garage Rate Computation:

    • Pricing formula: Base rate of $5.00\$5.00 covers up to the first 22 hours. Every subsequent hour costs an additional $1.50\$1.50.

    • Implementation: java double fee; if (hours <= 2) { fee = 5.00; } else { fee = 5.00 + (hours - 2) * 1.50; } System.out.println("Fee: $" + fee); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Numerical derivations across discrete input intervals:

    • Duration 2 hours: fee = 5.00 → Output: 5.0

    • Duration 3 hours: fee = 5.00 + (3 - 2) * 1.50 = 6.50 → Output: 6.5

    • Duration 5 hours: 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-else Chains:

    • 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 an int count of total characters within a String.

    • Example: "Hello".length() evaluates to 55.

    • String length classification algorithm (threshold: ≤8≤ 8 is short; >8> 8 is long): java if (word.length() <= 8) { System.out.println("This is a short word."); } else { System.out.println("This is a long word."); } &nbsp;&nbsp;&nbsp;&nbsp;

    • Trace results:

    • Input "Hello" (length 55) → Outputs: This is a short word.

    • Input "Goodbye" (length 77) → Outputs: This is a short word.

    • Input "Salutations" (length 1111) → 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 55; condition false → Outputs: Goodbye.

    • Given String word = "Hello, There!"; (length 1313):

    • if(word.length() >= 13) System.out.print("Hello "); System.out.println("Goodbye"); → 13≥1313 ≥ 13 is true → Outputs: Hello Goodbye.

    • if(word.length() % 2 == 0) System.out.print("Hello "); System.out.println("Goodbye"); → 13 % 2==1≠013 \text{ \% } 2 == 1 \neq 0 (false) → Outputs: Goodbye.

    • Given String word = "Billy Goats Gruff"; (length 1717):

      • if(word.length() > 10) System.out.print("Hello "); else System.out.println("Goodbye"); → 17>1017 > 10 is true → Outputs: Hello.

      • if(word.length() <= 15) System.out.print("Hello "); else System.out.println("Goodbye"); → 17≤1517 ≤ 15 is false → Outputs: Goodbye.

      • if(word.charAt(1) == 'B') System.out.print("Trip "); else System.out.println("Trap"); → Index 1 is character 'i'; 'i' == 'B' is false → Outputs: Trap.

      • if(word.charAt(15) == 'f') System.out.print("Trip "); else System.out.println("Trap"); → Index 15 is 'f'; 'f' == 'f' is true → Outputs: Trip.

    • Given String word = "Three Little Pigs"; (length 1717):

      • 17 % 3=217 \text{ \% } 3 = 2 (17/3=517 / 3 = 5, remainder 22).

      • Evaluates word.length() % 3 == 0 → false.

      • Evaluates word.length() % 3 == 1 → false.

      • Falling to else branch → 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"); } &nbsp;&nbsp;&nbsp;&nbsp;

    • Trace results:

    • Grade 100 → 100 >= 90 is true → Outputs: A.

    • Grade 88 → 88 >= 90 is false, 88 >= 80 is true → Outputs: B.

    • Grade 75 → 75 >= 70 is true → Outputs: C.

    • Grade 64 → All conditions evaluate to false → 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"); } &nbsp;&nbsp;&nbsp;&nbsp;

    • 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-else chains (such as temperature bands or letter grade ranges) into switch structures is problematic.

    • A switch construct 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 unique case.

Switch Statements: Syntax, Execution Mechanics, and Evolution

  • Overview of Switch Constructs:

    • A switch statement provides a structured alternative to replace multi-way if-else chains 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 listed case.

  • 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 2626 letters of the alphabet).

    • Appropriate when replacing an if-else chain 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; } &nbsp;&nbsp;&nbsp;&nbsp;

  • Execution trace:

    • When evaluating variable let = 'B', the runtime checks case '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 the break keyword.

  • Fall-Through Behavior:

    • If a break statement is omitted, execution falls through unconditionally into subsequent case blocks, executing statements regardless of whether subsequent case labels match, until a break or the closing brace is reached.

    • Example: Omitting break on case 'A' results in outputs for both 'A' and 'B': .- followed immediately by -....

    • Example: In an older Morse code switch spanning 'A' through 'G', omitting all break statements and executing on input 'C' produces:     -.-.     -..     .     ..-.     --.

  • Intentional Fall-Through (Grouped Cases):

    • Stacking case labels without interleaving break statements 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"); } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • 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; } &nbsp;&nbsp;&nbsp;&nbsp;

  • 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 break keyword 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; } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

    • Outputs: 2 3 because execution enters at 'B' and falls through into 'C' before reaching the break.

  • Modern arrow syntax: java switch (c) { case 'A' -> System.out.print("1 "); case 'B' -> System.out.print("2 "); case 'C' -> System.out.print("3 "); } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

    • Outputs: 2 because 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); &nbsp;&nbsp;&nbsp;&nbsp;

    • Input day = 3 → Outputs: Wednesday.

    • Input day = 7 → Matches no case label; triggers default → Outputs: Weekend.

  • T-Shirt Size Translation:

    • Converting an if-else chain 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"); } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • 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); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

    • 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."; } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • 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); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Input "Spanish" → Outputs: In Mexico they say Hello World! as ¡Hola Mundo!.