Java Control Structures, Math, Errors, and Debugging Techniques

Boolean Expressions and Relational Operators
  • Study Objective: Master conditional logic, truth evaluations, and comparisons essential for Grade 11 decision structures.

  • Boolean Expression Definition:

    • A Boolean expression is any code construct that evaluates to exactly one of two values: true or false.

  • Relational Operators (Value Comparisons):

    • Symbols used to compare two values, producing a Boolean result:

    • == : Equal to.

    • != : Not equal to.

    • > : Greater than.

    • < : Less than.

    • >= : Greater than or equal to.

    • <= : Less than or equal to (also referenced syntactically as <+).

  • Compound Boolean Expressions:

    • Combines two or more simple Boolean expressions using logical operators:

    • && (Logical AND): Evaluates to true only if both conditions are true.

    • || (Logical OR): Evaluates to true if at least one condition is true.

    • ! (Logical NOT): Reverses or flips a Boolean value (transforms true to false, and false to true).

    • Syntax Example:java if (model == 119 || model == 179 || model == 189) { System.out.println("Your car is defective. It must be repaired"); } else { System.out.print("Your car is not defective"); } &nbsp;&nbsp;&nbsp;&nbsp;

  • Short-Circuit Evaluation:

    • Occurs when the Java compiler stops evaluating a compound expression because the outcome is already guaranteed:

    • In an && expression, if the first condition is false, the entire expression must be false; remaining conditions are skipped.

    • In an || expression, if the first condition is true, the overall expression is already true; remaining conditions are skipped.

  • Grade 11 Exam Tip: Pay close attention to operator precedence and short-circuit behavior when tracing logic questions on tests.

Conditional and Decision Control Structures
  • Study Objective: Direct program execution flow using branching statements.

  • Definition of Conditional Control Structure (Decision Structure):

    • A programming mechanism that evaluates a condition and selects which path of code to execute based on whether the condition is true or false.

  • Nesting:

    • Placing one control structure directly inside another (e.g., embedding an if statement inside a loop).

  • Core Java Conditional Statements:

    • The if Statement:

    • Executes its block strictly when the Boolean condition is true; skips the block entirely if false.

    • Allows the programmer to handle distinct program scenarios.

    • Example: java if (score >= 60) { System.out.println("You passed!"); } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • The if-else Statement:

    • Implements a two-way branch. Runs one block if true and an alternative block if false.

    • Example: java if (score >= 60) { System.out.println("Pass"); } else { System.out.println("Fail"); } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • The else-if Statement (if-else if-else):

    • Evaluates multiple conditions sequentially from top to bottom.

    • Stops at the very first condition that evaluates to true, runs its block, and bypasses the rest.

    • Example: java if (score >= 90) { System.out.println("A"); } else if (score >= 80) { System.out.println("B"); } else { System.out.println("C or lower"); } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • The switch Statement:

    • Tests a variable or expression against multiple constant values (case clauses).

    • The evaluated expression must resolve to an integer.

    • A break statement is required after each case to exit the switch; omitting break causes execution to fall through to subsequent cases.

    • An optional default clause catches unmatched values.

    • Example: java int day = 2; switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; default: System.out.println("Other day"); break; } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

Loop Control Structures and Program Flow
  • Study Objective: Automate repetitions and control loop iterations efficiently.

  • Essential Loop and Debugging Vocabulary:

    • Iteration: A single complete pass through a loop's code block.

    • Loop Control Variable: A variable that tracks progress and determines when the loop terminates.

    • Infinite Loop: A loop that runs endlessly because its termination condition is never reached.

    • Counter: A variable used to count how many times an event or iteration takes place.

    • Accumulator: A variable used to keep a running total by adding values to it across iterations.

    • Breakpoint: A marker placed on a specific line of code telling a debugger to pause execution for inspection.

  • Increment and Decrement Operators:

    • ++ (Increment Operator): Increases the numeric value of a variable by exactly 11.

    • -- (Decrement Operator): Decreases the numeric value of a variable by exactly 11.

  • Java Loop Types:

    • The while Loop:

    • A pre-test loop that checks its condition before running the body.

    • If the condition is initially false, the body may execute 00 times.

    • Example: java int i = 0; while (i < 5) { System.out.println(i); i++; } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • The do-while Loop:

    • A post-test loop that guarantees the code block runs at least once before testing the condition.

  • The for Loop:

    • Used when the exact number of iterations is known before entering the loop.

    • General syntax: java for (<initialization>; <condition>; <increment>); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

The Java Math Class (java.lang.Math)
  • Study Objective: Utilize built-in mathematical functions correctly in calculations.

  • Class Properties:

    • Fully qualified class path: java.lang.Math.

    • Built-in package: does not require an import statement.

    • All methods are static and called directly via the class name prefix: Math.methodName().

  • Core Methods for Grade 11 Computer Science:

    • Math.abs(x):

    • Returns the absolute positive value of x (takes an int or double).

    • Example: int num = Math.abs(-5); returns 55.

    • Math.pow(base, exponent):

    • Raises base to the power of exponent.

    • Return type: Always returns a double.

    • Example: double result = Math.pow(2, 3); returns 8.08.0.

    • Math.sqrt(x):

    • Returns the square root of a positive number x.

    • Return type: Always returns a double.

    • Example: double root = Math.sqrt(25); returns 5.05.0.

    • Math.random():

    • Generates a pseudorandom double in the range [0.0,1.0)[0.0, 1.0) (0.00.0 inclusive to 1.01.0 exclusive).

    • Standard Grade 11 formula for generating a random integer from 00 to 99 inclusive: java (int)(Math.random() * 10) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

The Java Random Class (java.util.Random)
  • Study Objective: Instantiate objects and generate random values using Java's utility class.

  • Class Overview and Object Instantiation:

    • Located in java.util.Random; requires an explicit import statement.

    • An instance object must be created before calling non-static methods: java import java.util.Random; Random rand = new Random(); &nbsp;&nbsp;&nbsp;&nbsp;

  • Theoretical Concepts:

    • Linear Congruential Method: The mathematical algorithm utilized by java.util.Random to generate numeric sequences.

    • Pseudorandom Numbers: Values that appear random and unpredictable but are generated mathematically by an algorithm.

  • Methods to Memorize:

    • rand.nextInt(): Returns a random integer across the full generator sequence range.

    • rand.nextInt(int n): Returns a random integer from 00 (inclusive) up to nn (exclusive), yielding values from 00 through n−1n - 1.

    • Example: int randomNum = rand.nextInt(10); generates an integer from 00 through 99.

    • rand.nextDouble(): Returns a pseudorandom double between 0.00.0 (inclusive) and 1.01.0 (exclusive).

    • Example: java double randDouble = rand.nextDouble(); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;


Boolean Expressions and Relational Operators

  • Study Objective: Master conditional logic, truth evaluations, and comparisons essential for Grade 11 decision structures.

  • Boolean Expression Definition:

    • A Boolean expression is any code construct that evaluates to exactly one of two values: true or false.

  • Relational Operators (Value Comparisons):

    • Symbols used to compare two values, producing a Boolean result:

    • == : Equal to.

    • != : Not equal to.

    • > : Greater than.

    • < : Less than.

    • >= : Greater than or equal to.

    • <= : Less than or equal to (also referenced syntactically as <+).

  • Compound Boolean Expressions:

    • Combines two or more simple Boolean expressions using logical operators:

    • && (Logical AND): Evaluates to true only if both conditions are true.

    • || (Logical OR): Evaluates to true if at least one condition is true.

    • ! (Logical NOT): Reverses or flips a Boolean value (transforms true to false, and false to true).

    • Syntax Example:java if (model == 119 || model == 179 || model == 189) { System.out.println("Your car is defective. It must be repaired"); } else { System.out.print("Your car is not defective"); } &nbsp;&nbsp;&nbsp;&nbsp;

  • Short-Circuit Evaluation:

    • Occurs when the Java compiler stops evaluating a compound expression because the outcome is already guaranteed:

    • In an && expression, if the first condition is false, the entire expression must be false; remaining conditions are skipped.

    • In an || expression, if the first condition is true, the overall expression is already true; remaining conditions are skipped.

  • Grade 11 Exam Tip: Pay close attention to operator precedence and short-circuit behavior when tracing logic questions on tests.

Conditional and Decision Control Structures

  • Study Objective: Direct program execution flow using branching statements.

  • Definition of Conditional Control Structure (Decision Structure):

    • A programming mechanism that evaluates a condition and selects which path of code to execute based on whether the condition is true or false.

  • Nesting:

    • Placing one control structure directly inside another (e.g., embedding an if statement inside a loop).

  • Core Java Conditional Statements:

    • The if Statement:

    • Executes its block strictly when the Boolean condition is true; skips the block entirely if false.

    • Allows the programmer to handle distinct program scenarios.

    • Example: java if (score >= 60) { System.out.println("You passed!"); } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • The if-else Statement:

    • Implements a two-way branch. Runs one block if true and an alternative block if false.

    • Example: java if (score >= 60) { System.out.println("Pass"); } else { System.out.println("Fail"); } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • The else-if Statement (if-else if-else):

    • Evaluates multiple conditions sequentially from top to bottom.

    • Stops at the very first condition that evaluates to true, runs its block, and bypasses the rest.

    • Example: java if (score >= 90) { System.out.println("A"); } else if (score >= 80) { System.out.println("B"); } else { System.out.println("C or lower"); } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • The switch Statement:

    • Tests a variable or expression against multiple constant values (case clauses).

    • The evaluated expression must resolve to an integer.

    • A break statement is required after each case to exit the switch; omitting break causes execution to fall through to subsequent cases.

    • An optional default clause catches unmatched values.

    • Example: java int day = 2; switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; default: System.out.println("Other day"); break; } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

Loop Control Structures and Program Flow

  • Study Objective: Automate repetitions and control loop iterations efficiently.

  • Essential Loop and Debugging Vocabulary:

    • Iteration: A single complete pass through a loop's code block.

    • Loop Control Variable: A variable that tracks progress and determines when the loop terminates.

    • Infinite Loop: A loop that runs endlessly because its termination condition is never reached.

    • Counter: A variable used to count how many times an event or iteration takes place.

    • Accumulator: A variable used to keep a running total by adding values to it across iterations.

    • Breakpoint: A marker placed on a specific line of code telling a debugger to pause execution for inspection.

  • Increment and Decrement Operators:

    • ++ (Increment Operator): Increases the numeric value of a variable by exactly 11.

    • -- (Decrement Operator): Decreases the numeric value of a variable by exactly 11.

  • Java Loop Types:

    • The while Loop:

    • A pre-test loop that checks its condition before running the body.

    • If the condition is initially false, the body may execute 00 times.

    • Example: java int i = 0; while (i < 5) { System.out.println(i); i++; } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • The do-while Loop:

    • A post-test loop that guarantees the code block runs at least once before testing the condition.

  • The for Loop:

    • Used when the exact number of iterations is known before entering the loop.

    • General syntax: java for (<initialization>; <condition>; <increment>); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

The Java Math Class (java.lang.Math)

  • Study Objective: Utilize built-in mathematical functions correctly in calculations.

  • Class Properties:

    • Fully qualified class path: java.lang.Math.

    • Built-in package: does not require an import statement.

    • All methods are static and called directly via the class name prefix: Math.methodName().

  • Core Methods for Grade 11 Computer Science:

    • Math.abs(x):

    • Returns the absolute positive value of x (takes an int or double).

    • Example: int num = Math.abs(-5); returns 55.

    • Math.pow(base, exponent):

    • Raises base to the power of exponent.

    • Return type: Always returns a double.

    • Example: double result = Math.pow(2, 3); returns 8.08.0.

    • Math.sqrt(x):

    • Returns the square root of a positive number x.

    • Return type: Always returns a double.

    • Example: double root = Math.sqrt(25); returns 5.05.0.

    • Math.random():

    • Generates a pseudorandom double in the range [0.0,1.0)[0.0, 1.0) (0.00.0 inclusive to 1.01.0 exclusive).

    • Standard Grade 11 formula for generating a random integer from 00 to 99 inclusive: java (int)(Math.random() * 10) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

The Java Random Class (java.util.Random)

  • Study Objective: Instantiate objects and generate random values using Java's utility class.

  • Class Overview and Object Instantiation:

    • Located in java.util.Random; requires an explicit import statement.

    • An instance object must be created before calling non-static methods: java import java.util.Random; Random rand = new Random(); &nbsp;&nbsp;&nbsp;&nbsp;

  • Theoretical Concepts:

    • Linear Congruential Method: The mathematical algorithm utilized by java.util.Random to generate numeric sequences.

    • Pseudorandom Numbers: Values that appear random and unpredictable but are generated mathematically by an algorithm.

  • Methods to Memorize:

    • rand.nextInt(): Returns a random integer across the full generator sequence range.

    • rand.nextInt(int n): Returns a random integer from 00 (inclusive) up to nn (exclusive), yielding values from 00 through n−1n - 1.

    • Example: int randomNum = rand.nextInt(10); generates an integer from 00 through 99.

    • rand.nextDouble(): Returns a pseudorandom double between 0.00.0 (inclusive) and 1.01.0 (exclusive).

    • Example: java double randDouble = rand.nextDouble(); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

Programming Errors

  • Study Objective: Identify, distinguish, and correct different categories of programming bugs.

  • Types of Program Errors:

    • Syntax Errors:

    • Errors that violate the strict syntax and grammar rules of Java (e.g., forgetting a semicolon at the end of a statement).

    • Detected during compilation by the compiler.

    • An application with syntax errors cannot compile and will not run.

    • Logic Errors (Semantic Errors):

    • Statements that are syntactically valid and compile successfully, but yield unexpected, erroneous, or unintended program output.

    • Example: Assigning length = 3.2; to an int variable truncates it to 33, producing an unexpected calculation result for area.

    • Must be tracked down and diagnosed by the programmer through code inspection and testing.

    • Prevention: Clear commenting, structured indentation, and meaningful identifier names help prevent logic bugs.

    • Run-Time Errors (Exceptions):

    • Errors not detected during compilation that trigger a program halt during execution at the problematic line.

    • ArithmeticException: Generated by undefined mathematical operations such as division by zero (e.g., 40 / 0).

    • InputMismatchException: Generated when user input does not match the expected data type (e.g., entering a String when Scanner.nextInt() expects an integer).

Debugging Techniques and Tools

  • Study Objective: Apply systematic methods and IDE tools to isolate, trace, and resolve program defects.

  • Testing vs. Debugging:

    • Testing: A planned, structured activity designed to verify that a program performs according to requirements.

    • Debugging: The diagnostic process of running an application, identifying bugs or compilation failures, and fixing them to ensure proper function.

  • Key Debugging Techniques:

    • Variable Tracing:

    • Constructing a manual tracing table that tracks the values assigned to each variable chronologically during loop passes or statement executions.

    • Helps detect exactly where a variable's value deviates from the expected output.

    • Additional println() Statements:

    • Inserting print statements immediately after variable assignments or before/after conditional evaluations to monitor runtime states.

    • Commenting Out Code:

    • Placing // markers in front of code lines or segments to disable them selectively, isolating bugs via process of elimination.

    • Catching Off-By-One Errors:

    • A frequent loop error where an iteration executes one time too many or one time too few due to an incorrect relational operator (e.g., < versus <=).

  • Using an Interactive Debugger:

    • Breakpoints (Stop Points): Markers placed in the code margin instructing the debugger to suspend program execution on that line.

    • Stepping: Using step commands (such as Step Over or Step Into) to advance execution one statement at a time.

    • Watch Window: An inspection panel displaying monitored variables and updating their values live as stepping occurs.

  • jGRASP Debugging Environment Features:

    • Compile Messages Box: Displays compiler diagnostic messages and provides clickable links jumping directly to the problem line.

    • Run I/O Box: Terminal interface where application console inputs and outputs are processed.

    • Debug Tool / Stop Points: Interactive margin controls to set stop points and single-step through routines.

  • Six Core Guidelines to Debugging:

    1. Make sure all variables are initialized before use.

    2. Don't stop at one bug (there are often more).

    3. Initialize constants in declarations; initialize variables with executable code.

    4. Watch for off-by-one errors.

    5. Test programs at their boundary values.

    6. Program defensively.