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:
trueorfalse.
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 totrueonly if both conditions aretrue.||(Logical OR): Evaluates totrueif at least one condition istrue.!(Logical NOT): Reverses or flips a Boolean value (transformstruetofalse, andfalsetotrue).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"); }
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 isfalse, the entire expression must befalse; remaining conditions are skipped.In an
||expression, if the first condition istrue, the overall expression is alreadytrue; 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
trueorfalse.
Nesting:
Placing one control structure directly inside another (e.g., embedding an
ifstatement inside a loop).
Core Java Conditional Statements:
The
ifStatement:Executes its block strictly when the Boolean condition is
true; skips the block entirely iffalse.Allows the programmer to handle distinct program scenarios.
Example:
java if (score >= 60) { System.out.println("You passed!"); }
The
if-elseStatement:Implements a two-way branch. Runs one block if
trueand an alternative block iffalse.Example:
java if (score >= 60) { System.out.println("Pass"); } else { System.out.println("Fail"); }
The
else-ifStatement (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"); }
The
switchStatement:Tests a variable or expression against multiple constant values (
caseclauses).The evaluated expression must resolve to an integer.
A
breakstatement is required after each case to exit the switch; omittingbreakcauses execution to fall through to subsequent cases.An optional
defaultclause 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; }
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 .--(Decrement Operator): Decreases the numeric value of a variable by exactly .
Java Loop Types:
The
whileLoop:A pre-test loop that checks its condition before running the body.
If the condition is initially
false, the body may execute times.Example:
java int i = 0; while (i < 5) { System.out.println(i); i++; }
The
do-whileLoop:A post-test loop that guarantees the code block runs at least once before testing the condition.
The
forLoop:Used when the exact number of iterations is known before entering the loop.
General syntax:
java for (<initialization>; <condition>; <increment>);
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
importstatement.All methods are
staticand 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 anintordouble).Example:
int num = Math.abs(-5);returns .Math.pow(base, exponent):Raises
baseto the power ofexponent.Return type: Always returns a
double.Example:
double result = Math.pow(2, 3);returns .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 .Math.random():Generates a pseudorandom
doublein the range ( inclusive to exclusive).Standard Grade 11 formula for generating a random integer from to inclusive:
java (int)(Math.random() * 10)
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 explicitimportstatement.An instance object must be created before calling non-static methods:
java import java.util.Random; Random rand = new Random();
Theoretical Concepts:
Linear Congruential Method: The mathematical algorithm utilized by
java.util.Randomto 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 (inclusive) up to (exclusive), yielding values from through .Example:
int randomNum = rand.nextInt(10);generates an integer from through .rand.nextDouble(): Returns a pseudorandomdoublebetween (inclusive) and (exclusive).Example:
java double randDouble = rand.nextDouble();
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:
trueorfalse.
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 totrueonly if both conditions aretrue.||(Logical OR): Evaluates totrueif at least one condition istrue.!(Logical NOT): Reverses or flips a Boolean value (transformstruetofalse, andfalsetotrue).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"); }
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 isfalse, the entire expression must befalse; remaining conditions are skipped.In an
||expression, if the first condition istrue, the overall expression is alreadytrue; 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
trueorfalse.
Nesting:
Placing one control structure directly inside another (e.g., embedding an
ifstatement inside a loop).
Core Java Conditional Statements:
The
ifStatement:Executes its block strictly when the Boolean condition is
true; skips the block entirely iffalse.Allows the programmer to handle distinct program scenarios.
Example:
java if (score >= 60) { System.out.println("You passed!"); }
The
if-elseStatement:Implements a two-way branch. Runs one block if
trueand an alternative block iffalse.Example:
java if (score >= 60) { System.out.println("Pass"); } else { System.out.println("Fail"); }
The
else-ifStatement (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"); }
The
switchStatement:Tests a variable or expression against multiple constant values (
caseclauses).The evaluated expression must resolve to an integer.
A
breakstatement is required after each case to exit the switch; omittingbreakcauses execution to fall through to subsequent cases.An optional
defaultclause 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; }
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 .--(Decrement Operator): Decreases the numeric value of a variable by exactly .
Java Loop Types:
The
whileLoop:A pre-test loop that checks its condition before running the body.
If the condition is initially
false, the body may execute times.Example:
java int i = 0; while (i < 5) { System.out.println(i); i++; }
The
do-whileLoop:A post-test loop that guarantees the code block runs at least once before testing the condition.
The
forLoop:Used when the exact number of iterations is known before entering the loop.
General syntax:
java for (<initialization>; <condition>; <increment>);
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
importstatement.All methods are
staticand 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 anintordouble).Example:
int num = Math.abs(-5);returns .Math.pow(base, exponent):Raises
baseto the power ofexponent.Return type: Always returns a
double.Example:
double result = Math.pow(2, 3);returns .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 .Math.random():Generates a pseudorandom
doublein the range ( inclusive to exclusive).Standard Grade 11 formula for generating a random integer from to inclusive:
java (int)(Math.random() * 10)
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 explicitimportstatement.An instance object must be created before calling non-static methods:
java import java.util.Random; Random rand = new Random();
Theoretical Concepts:
Linear Congruential Method: The mathematical algorithm utilized by
java.util.Randomto 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 (inclusive) up to (exclusive), yielding values from through .Example:
int randomNum = rand.nextInt(10);generates an integer from through .rand.nextDouble(): Returns a pseudorandomdoublebetween (inclusive) and (exclusive).Example:
java double randDouble = rand.nextDouble();
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 anintvariable truncates it to , producing an unexpected calculation result forarea.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 aStringwhenScanner.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:
Make sure all variables are initialized before use.
Don't stop at one bug (there are often more).
Initialize constants in declarations; initialize variables with executable code.
Watch for off-by-one errors.
Test programs at their boundary values.
Program defensively.