Big Ideas
Key notes from AP CSA Unit 1.1–1.20 (curated & includes all provided summaries)
Unit 1 & 2 — Video Explanation
If the video doesn’t load, use the “Open in Google Drive” button.
1.1 – Why Programming?
- Programming is creating instructions for a computer to solve tasks.
- Computers execute repetitive and complex problems quickly and accurately.
- Skills developed: problem decomposition, logical thinking, creativity.
- Examples: automation, AI, simulations, data analysis, apps.
- AP CSA builds a strong foundation in Java and problem-solving.
1.2 – Introduction to Java
- Object-Oriented language: organizes code into classes and objects.
- Portable: compiles into bytecode that runs on the JVM.
- Strongly typed: variables need explicit types (e.g.,
int,String). - Basic program structure with
classandmainmethod. - Case-sensitive; semicolons end statements; braces define blocks.
1.3 – Printing in Java & Literals
System.out.print()vsSystem.out.println()- Concatenation with
+, escape sequences:\n,\t,\"
1.4 – Comments
- Single-line:
//• Multi-line:/* ... */• Javadoc:/** ... */ - Explain purpose; keep up to date.
1.5 – Variables & Data Types
- Primitives:
int,double,boolean; Reference:String. - Declare/init & constants with
final. - Integer bounds via
Integer.MIN_VALUE/MAX_VALUE.
1.6 – Operators, Expressions & Casting
- Arithmetic
+ - * / %, precedence, integer division truncation. - Casting & round-off considerations.
1.7 – User Input with Scanner
nextInt,nextDouble,next,nextLine, newline gotcha.
1.8 – The Math Class (Basics)
abs,pow,sqrt,max,min,random;PI,E.
1.9 – Errors & Debugging
- Syntax vs runtime vs logic errors; use stack traces & incremental testing.
1.1.10 Summary
- Algorithm: Adım adım süreç tanımıdır, diyagram ya da yazıyla ifade edilebilir.
- Sequencing: İşlemler sıralı yapılır.
- IDE: Kod yazma, derleme ve çalıştırma ortamıdır.
- Java Program Yapısı:
public class ClassNamevepublic static void main(String[] args)ile başlar. System.out.println()çıktıyı ekrana yazdırır.;satır sonu,{}kod blokları için,//ve/* */yorumlar için kullanılır.- Compiler: Kodu .class dosyasına çevirir; syntax errors (dilbilgisi hataları) derleme aşamasında tespit edilir.
- Logic errors: Kod çalışır ama yanlış sonuç verir; testle bulunur.
- Run-time errors: Çalışma anında oluşur, exceptions program akışını keser.
public class MyClass {
public static void main(String[] args) {
System.out.println("Hi there!");
}
}
1.2.7 Summary
- (AP 1.2.B.2) A variable is a memory storage location that holds a value, which can change while the program is running.
- (AP 1.2.B.2) Every variable has a name and an associated data type that determines the kind of data it can hold. A variable of a primitive type holds a primitive value from that type.
int score; double gpa = 3.5;
- (AP 1.2.A.1) A data type is a set of values and a corresponding set of operations on those values. Data types can be primitive types (like int) or reference types (like String).
- (AP 1.2.A.2) The primitive data types used in this course define the set of values and corresponding operations on those values for numbers and Boolean values.
- (AP 1.2.A.3) A reference type, like String, is used to define objects that are not primitive types.
- (AP 1.2.B.1) The three primitive data types used in this course are int (integer numbers), double (decimal numbers), and boolean (true or false).
- String is a reference data type representing a sequence of characters.
1.3.6 Summary
- (AP 1.3.A.1) System.out.print and System.out.println are Java output statements that display information on the computer screen. System.out.println moves the cursor to a new line after the information has been displayed, while System.out.print does not.
- (AP 1.3.B.1) A literal is the code representation of a fixed value, which can be a string or a numerical value.
- (AP 1.3.B.2) A string literal is a sequence of zero to many characters enclosed in starting and ending double quotes.
- (AP 1.3.B.3) Escape sequences are special sequences of characters that can be included in a string. They start with a backslash \ and have a special meaning in Java. Escape sequences used in this course include double quote ", backslash \, and newline\n.
- (AP 1.3.C.1) Arithmetic expressions, which consist of numeric values, variables, and operators, include expressions of type int and double.
- (AP 1.3.C.2) The arithmetic operators consist of +, -, * , /, and % also known as addition, subtraction, multiplication, division, and remainder.
- (AP 1.3.C.2) An arithmetic operation that uses two int values will evaluate to an int value. With integer division, any decimal part in the result will be thrown away.
- (AP 1.3.C.2) An arithmetic operation that uses at least one double value will evaluate to a double value.
- (AP 1.3.C.3) When dividing numeric values that are both int values, the result is only the integer portion of the quotient. Anything after the decimal point is thrown away. When dividing numeric values that use at least one double value, the result is the double quotient as expected.
- (AP 1.3.C.4) The remainder (modulo) operator % is used to compute the remainder when one number is divided by another number.
- (AP 1.3.C.5) Multiple operators can be used to combine expressions into compound expressions.
- (AP 1.3.C.5) During evaluation, numeric values are associated with operators according to operator precedence to determine how they are grouped. *, /, % have precedence over + and -, unless parentheses are used to group those to be evaluated first. Operators with the same precedence are evaluated from left to right.
- (AP 1.3.C.6) An attempt to divide an integer by zero will result in an ArithmeticException.
1.5.6 Summary
- Type casting is used to convert a value from one type to another.
- (AP 1.5.A.1) The casting operators (int) and (double) can be used to convert from a double value to an int value (or vice versa).
- (AP 1.5.A.2) Casting a double value to an int causes the digits to the right of the decimal point to be truncated (cut off and thrown away).
- (AP 1.5.A.3) Some code causes int values to be automatically cast (widened) to double values. In expressions involving doubles, the double values are contagious, causing ints in the expression to be automatically converted (“widened”) to the equivalent double value so the result of the expression can be computed as a double.
- (AP 1.5.A.4) Values of type double can be rounded to the nearest integer by (int)(x + 0.5) or (int)(x – 0.5) for negative numbers.
- (AP 1.5.B.1) The constant Integer.MAX_VALUE holds the value of the largest possible int value. The constant Integer.MIN_VALUE holds the value of the smallest possible int value.
- (AP 1.5.B.2) Integer values in Java are represented by values of type int, which are stored using a finite amount (4 bytes) of memory. Therefore, an int value must be in the range from Integer.MIN_VALUE to Integer.MAX_VALUE, inclusive.
- (AP 1.5.B.3) If an expression would evaluate to an int value outside of the allowed range, an integer overflow occurs. The result is an int value in the allowed range but not necessarily the value expected.
- (AP 1.5.C.1) Computers allot a specified amount of memory to store data based on the data type. If an expression would evaluate to a double that is more precise than can be stored in the allotted amount of memory, a round-off error occurs. The result will be rounded to the representable value. To avoid rounding errors that naturally occur, use int values or round doubles to the precision needed.
1.7.4 Summary
- (AP 1.7.A.1) Libraries are collections of classes written by other programmers.
- (AP 1.7.A.1) An Application Programming Interface (API) specification informs the programmer how to use classes in a library.
- (AP 1.7.A.1) Documentation found in API specifications and libraries is essential to understanding the attributes and behaviors of a class defined by the API.
- (AP 1.7.A.1) Classes in the APIs and libraries are grouped into packages that can be imported into a program.
- (AP 1.7.A.1) A class defines a specific reference type and is the building block of object-oriented programming. Existing classes and class libraries can be utilized to create objects.
- (AP 1.7.A.2) Attributes refer to the data related to the class and are stored in variables.
- (AP 1.7.A.2) Behaviors refer to what instances of the class can do (or what can be done with them) and are defined by methods.
1.8.6 Summary
- (AP 1.8.A.1) Comments are written for both the original programmer and other programmers to understand the code and its functionality, but are ignored by the compiler and are not executed when the program is run.
- (AP 1.8.A.1) Three types of comments in Java include /* /, which generates a block of comments, //, which generates a comment on one line, and /* */, which are Javadoc comments and are used to create API documentation.
- (AP 1.8.A.2) A precondition is a condition that must be true just prior to the execution of a section of program code in order for the method to behave as expected. There is no expectation that the method will check to ensure preconditions are satisfied.
- (AP 1.8.A.3) A postcondition is a condition that must always be true after the execution of a section of program code. Postconditions describe the outcome of the execution in terms of what is being returned or the current value of the attributes of an object.
1.9 Summary
- Method: Adlandırılmış kod bloğu, çağrıldığında çalışır.
- Procedural abstraction: Metodu içini bilmeden kullanma.
- Parameter: Metot başlığındaki değişken.
- Argument: Çağırırken verilen değer.
- Call by value: Argüman kopyası ile çalışır.
- Overloading: Aynı isim, farklı parametre listesi.
1.10.5 Summary
- (AP 1.10.A.1) Class methods are associated with the class (not instances of the class which we will see in later lessons).
- (AP 1.10.A.2) Class methods include the keyword static in the header before the method name.
- (AP 1.9.B.1) A void method does not have a return value and is therefore not called as part of an expression.
- (AP 1.9.B.2) A non-void method returns a value that is the same type as the return type in the header.
- (AP 1.9.B.2) To use the return value when calling a non-void method, it must be stored in a variable or used as part of an expression.
- Common errors with methods are mismatches in the order or type of arguments, return values, and forgetting to do something with the value returned from a method. When you call a method that returns a value, you should do something with that value like assigning it to a variable or printing it out.
- (AP 1.10.A.2) Class methods are typically called using the class name along with the dot operator. When the method call occurs in the defining class, the use of the class name is optional in the call.
1.11.4 Summary
- (AP 1.11.A.1) The Math class is part of the java.lang package. Classes in the java.lang package are available by default.
- (AP 1.11.A.2) The Math class contains only class (static) methods. They can be called using Math.method(); for each method.
- (AP 1.11.A.2) The following static Math methods are part of the Java Quick Reference:
- int abs(int)
- double abs(double)
- double pow(double, double)
- double sqrt(double)
- double random()
- (AP 1.11.A.3) The values returned from Math.random() can be manipulated to produce a random int or double in a defined range.
(int)(Math.random() * range) + min(range = max - min + 1).
1.12.8 Summary
- (AP 1.12.A.1) A class defines a new data type (a classification). It is the formal implementation, or blueprint, of the attributes and behaviors of the objects of that class.
- (AP 1.12.A.1) An object is a specific instance of a class with defined attributes. Objects are declared as variables of a class type.
- (AP 1.12.B.1) A variable of a reference type holds an object reference, which can be thought of as the memory address of that object.
- An attribute or instance variable is data the object knows about itself. For example a turtle object knows the direction it is facing or its color.
- A behavior or method is something that an object can do. For example a turtle object can go forward 100 pixels.
- (AP 1.12.A.2) A class hierarchy … inheritance relationship … (outside the AP CSA exam scope).
- (AP 1.12.A.2) All classes in Java are subclasses of the Object class.
1.13.7 Summary
- (AP 1.13.A.1) A class contains constructors that are called with the keyword new to create objects and initialize its attributes.
- (AP 1.13.A.1) Constructors have the same name as the class.
- (AP 1.13.C.1) new ClassName() creates a new object and calls a constructor.
- (AP 1.13.B.1) The new object is saved in a variable of a reference type (or null).
- (AP 1.13.A.2) Constructor signature = name + ordered parameter types; parameter list has types & names.
- (AP 1.13.A.3) Overloaded constructors differ by number/type/order.
- No-argument constructor: takes no arguments.
- (AP 1.13.C.2) Parameters establish initial attribute values.
- (AP 1.13.C.3) Arguments must be compatible with the signature; call by value (copies).
- (AP 1.13.C.4) Constructor call interrupts flow, then returns to next statement.
1.14.7 Summary
- Instance methods define behavior; called on objects.
- (AP 1.14.A.1) Use dot operator:
object.method(). - (AP 1.14.A.2) Calling on null →
NullPointerException. - Methods can take arguments; signature = name + parameter list (types & names).
- Arguments must match number, order, type.
- Method call interrupts sequential flow; resumes after method returns.
- Non-void methods return values; use the returned value.
1.15.9 Summary
- (AP 1.15.A.1) A String object represents a sequence of characters and can be created by a string literal.
- (AP 1.15.A.2) String is in
java.lang(available by default). Create via literal ornew String(...). - (AP 1.15.A.3) String is immutable.
- (AP 1.15.A.4) Concatenate with
+/+=; primitives auto-convert. - (AP 1.15.A.5) Concatenating any object calls its
toString(overriding details outside AP scope). - index, length, substring basics; indices 0..length-1; out-of-range →
IndexOutOfBoundsException. - AP Quick Reference:
String(String str)int length()String substring(int from, int to)String substring(int from)int indexOf(String str)boolean equals(Object other)int compareTo(String other)
Note:str.substring(index, index + 1)returns a single character.
1.16 – Unit Summary 1a (1.1–1.6)
In this unit you learned about the three primitive data types on the exam: int, double, and boolean. You also learned how to declare (name) and change the value of variables. You learned about operators, casting, and integer constants for the min and max integer values.
1.16.1 Concept Summary
- Compiler - Software that translates the Java source code into the Java class file which can be run on the computer.
- Compiler or syntax error - An error that is found during the compilation.
- Main method - Where execution starts in a Java program.
- Variable - A name associated with a memory location in the computer.
- Declare a Variable - Specifying the type and name for a variable. This sets aside memory for a variable of that type and associates the name with that memory location.
- Initializing a Variable - The first time you set the value of a variable.
- data type - determines the size of memory reserved for a variable, for example int, double, boolean, String.
- integer - a whole number like 2 or -3
- boolean - An expression that is either true or false.
- Camel case - One way to create a variable name by appending several words together and uppercasing the first letter of each word after the first word (myScore).
- Casting a Variable - Changing the type of a variable using (type) name.
- Operator - Common mathematical symbols such as + for addition and * for multiplication.
- Compound assignment or shortcut operators - Operators like x++ which means x = x + 1 or x =y which means x = x * y.
- remainder - The % operator which returns the remainder from one number divided by another.
- arithmetic expression - a sequence of operands and operators that describe a calculation to be performed, for example 3(2 + x)
- operator precedence - some operators are done before others, for example *, /, % have precedence over + and -, unless parentheses are used.
1.16.2 Java Keyword Summary
- boolean, double, int, String
- System.out.print(), System.out.println()
- = (assignment), +, -, *, /, %
1.20 – Unit Summary 1b (1.7–1.15)
In this unit, you learned to use objects (variables of a class type) that have been written for you in Java. You learned to use constructors and methods with and without parameters of objects, and built-in Java classes like String, Integer, Double, and Math.
1.20.1 Concept Summary
- class, object
- constructors, new
- instance variables (attributes), methods (behaviors)
- dot (.) operator, parameters (arguments), return values
- immutable strings; wrapper classes (Integer, Double)
1.20.2 Java Keyword Summary
- new, null
- String Quick Ref: String(String), length(), substring(from,to), substring(from), indexOf(String), equals(Object), compareTo(String)
- Integer Quick Ref: Integer(value), Integer.MIN_VALUE, Integer.MAX_VALUE, intValue()
- Double Quick Ref: Double(double), doubleValue()
- Math Quick Ref: abs, pow, sqrt, random
- Random range:
(int)(Math.random()*range) + minwhererange = max - min + 1.
Class Notes — Java & String Hızlı Rehber (alt alta satırlar)
Sık kullanılan satırlar (I/O, Math, değişkenler) ve String metodları — tek tek satırlar halinde.
Java Satırları
System.out.println("Hello");
System.out.print("No newline");
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
double x = scanner.nextDouble();
String w = scanner.next(); // boşluğa kadar
String line = scanner.nextLine(); // tüm satırı alır
final double PI = Math.PI;
double s = Math.sqrt(16);
double p = Math.pow(2, 5);
int mx = Math.max(aa, bb);
int mn = Math.min(aa, bb);
double r = Math.random();
String Metodları
String word = "mind";
int n = word.length();
char c = word.charAt(2); // 'n'
String first = word.substring(0, 1);
String mid = word.substring(1, 3); // "in"
int pos = word.indexOf("in"); // 1 (yoksa -1)
boolean has = word.contains("in"); // true
String rep = "m y".replace(" ", "\n");
boolean eq = "hello".equals("hello"); // true
int cmp = "hello".compareTo("jello"); // negatif
String up = "hi".toUpperCase();
String low = "OK".toLowerCase();
Karakter Karakter Döngü
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
// işlem...
}
Unit 2 — Selection & Repetition
Short, full-English summary of 2.1–2.6
2.1 Algorithms with Selection and Repetition
- Selection: choose actions based on conditions (
if,else if,else). - Repetition: repeat actions using loops (
while,for). - Combines decision-making and iteration for efficient algorithms.
2.2 Boolean Expressions
- Evaluate to
trueorfalse. - Operators:
==,!=,<,>,<=,>=,&&,||,!. - Use
.equals()for Strings instead of==.
2.3 if Statements
- Controls program flow based on conditions.
- Syntax:
if (condition) {
// code
} else if (condition) {
// code
} else {
// code
}
- Executes only the first true condition; chain or nest for complex logic.
2.4 Nested if Statements
- Place an
ifinside anotherifto make multi-level decisions (e.g., first by day, then by age). - Readability tip: prefer else-if ladders when branches are mutually exclusive; use nesting when the inner test only matters after an outer test is true.
- Binding rule: an
elsepairs with the closest unmatchedif. Use braces to avoid ambiguity.
// Example: school lunch price
if (isStudent) {
if (hasID) {
price = 5.0;
} else {
price = 6.5;
}
} else {
price = 8.0;
}
2.5 Compound Boolean Expressions
- Combine conditions with
&&(AND),||(OR),!(NOT). - Short-circuiting:
A && BskipsBifAis false;A || BskipsBifAis true. Useful to avoid errors (e.g., check bounds before indexing). - Precedence:
!>&&>||. Always add parentheses for clarity. - Ranges: use
&&for "between":if (0 <= x && x < 10). - De Morgan's laws:
!(A || B) == !A && !B,!(A && B) == !A || !B.
// Safe check with short-circuit
if (i >= 0 && i < arr.length && arr[i] != null) {
use(arr[i]);
}
2.6 Comparing Boolean Expressions
- Two different expressions can be logically equivalent (always same truth value).
- Common equivalences:
!(A || B)≡!A && !B(De Morgan)!(A && B)≡!A || !BA && (B || C)≡(A && B) || (A && C)(distribution)A ^ B(XOR) is true when exactly one is true
- Style: prefer the clearest form; avoid double negatives like
!(x <= 5)→ writex > 5. - Performance & safety: keep cheaper/safer checks first to benefit from short-circuiting.
// Equivalent but clearer rewrite
// Original:
if (!(age < 13 || age > 18)) teen = true;
// Better:
if (age >= 13 && age <= 18) teen = true;
Unit 2 — Loops & Algorithms (2.7–2.9)
2.7 — while Loops
- Purpose: repeat a block while a condition is true.
- Syntax:
while (condition) { /* code */ } - Key: ensure the condition eventually becomes
falseto avoid infinite loops. - Use when the number of repetitions is unknown (e.g., keep asking until input is valid).
2.8 — for Loops
- Purpose: run code a specific number of times.
- Syntax:
for (int i = 0; i < n; i++) { /* code */ } - Advantage: built-in counter; perfect when the loop count is known.
- Common uses: iterate arrays/strings, accumulate sums, build tables.
2.9 — Implementing Selection & Iteration Algorithms
- Selection: decisions with
if / else if / else. - Iteration: repetition with
whileandfor. - Together: decisions inside loops (e.g., count only even numbers), basic search/count patterns.
Runestone Notes — Unit 2 (2.1–2.13, 2.20)
2.1.5 Summary
- (AP 2.1.A.1) The building blocks of algorithms include sequencing, selection, and repetition.
- (AP 2.1.A.2) Algorithms can contain selection (decision making) and repetition (looping).
- (AP 2.1.A.3) Selection occurs when a choice of how execution proceeds is based on a true/false decision.
- (AP 2.1.A.4) Repetition is when a process repeats until a desired outcome is reached.
- (AP 2.1.A.5) The order of sequencing, selection, and repetition contributes to the algorithm’s outcome.
2.2.5 Summary
- (AP 2.2.A.1) Values or expressions can be compared using
==and!=. With primitive types this compares values; with reference types this compares object references. - (AP 2.2.A.2) Numeric values can be compared using
<,>,<=,>=. - (AP 2.2.A.3) Relational expressions evaluate to
booleanresults:trueorfalse. - The remainder operator
%can test divisibility, e.g.,num % 2 == 0checks for even.
2.3.6 Summary
- (AP 2.3.A.1) Selection statements change sequential execution.
- (AP 2.3.A.2) An
ifexecutes different code segments based on a Boolean expression. - (AP 2.3.A.3) One-way selection runs a body only when the condition is
true. - if statements test a boolean expression and if it is true, execute the following statement or block.
2.4.4 Summary
- (AP 2.4.A.1) Nested
ifstatements placeif/if-else/if-else-ifinside each other. - (AP 2.4.A.2) The inner Boolean expression is evaluated only if the outer condition is
true. - (AP 2.4.A.3) Multi-way selection (
if-else-if) executes at most one matching branch; an optional trailingelseruns if none match.
2.5.5 Summary
- (AP 2.5.A.1) Logical operators
!(not),&&(and),||(or) operate on Booleans. A && Bis true only if both are true.A || Bis true if either (or both) is true.!Aflips A.- (AP 2.5.A.1) Precedence:
!>&&>||(parentheses clarify intent). - (AP 2.5.A.1) Logical expressions evaluate to
boolean. - (AP 2.5.A.2) Short-circuiting: in
||if the first is true, skip the second; in&&if the first is false, skip the second.
2.6.9 Summary
- (AP 2.6.A.1) Two Boolean expressions are equivalent if they match for all cases; truth tables can prove equivalence.
- (AP 2.6.A.2) De Morgan’s Laws:
!(a && b)≡!a || !b!(a || b)≡!a && !b
- Negated relational simplifications:
!(c == d)≡c != d;!(c != d)≡c == d!(c < d)≡c >= d;!(c > d)≡c <= d!(c <= d)≡c > d;!(c >= d)≡c < d
- (AP 2.6.B.1) Two variables can reference the same object;
==/!=compare references (aliases compare equal). - (AP 2.6.B.2) Compare an object reference with
nullusing==or!=. - (AP 2.6.B.3) Classes often define
equalsto specify object equivalence via attributes.
2.7.6 Summary
- (AP 2.7.A.1) Iteration repeats a segment while a Boolean condition is
true. - (AP 2.7.B.1)
whileevaluates the condition before each iteration.
// Runs zero or more times
int count = 0; // initialize
while (count < 10) { // test
// body
count++; // update
}
- Typical loop pattern: Initialize → Test → Update.
- (AP 2.7.A.2) Infinite loop: condition never becomes false.
- (AP 2.7.A.3) If initial test is false, body doesn’t run.
- (AP 2.7.A.4) Off-by-one errors: loop runs one too many/few times.
- Input-controlled (sentinel) loops (e.g.,
-1, "bye") are useful though not on AP exam.
2.8.4 Summary
- (AP 2.8.A.1) A
forloop header has initialization, Boolean test, and update. - (AP 2.8.A.2) Initialization runs once; then test → body → update cycles until test is false.
- (AP 2.8.A.3)
forandwhileare inter-convertible.
2.9.9 Summary
- (AP 2.9.1) Standard loop/selection algorithms:
- Compute sum/average
- Determine min/max
- Check divisibility of integers
- Extract digits of an integer
- Count frequency meeting a criterion
- Accumulator pattern: store/update a running value inside a loop.
- Common pattern:
ifinside loop to test each value (e.g., track min/max).
2.10.4 Summary
- Loops can traverse/process a
String. - (AP 2.10.A.1) Standard string algorithms:
- Find substrings with a property
- Count substrings meeting criteria
- Create a reversed string
2.11.3 Summary
- Nested iteration: a loop inside another loop.
- The inner loop completes all iterations before the outer loop continues.
2.12.4 Summary
- (AP 2.12.A.1) Statement execution counts measure how many times a statement runs; computed by tracing/analyzing loops.
- Trace tables track variables across iterations.
- For simple counters: executions ≈
largestValue - smallestValue + 1. - Nested loops: total ≈ outer count × inner count.
- Non-rectangular loops: use
n(n+1)/2for triangular counts.
2.12.5 Loop Analysis Game
2.13 — Unit 2 Part 1: Selection (2.1–2.6)
Conditionals execute code when a Boolean expression is true or false (e.g., x > 0).
2.13.1 Concept Summary
- Block of statements — one or more statements in
{ }. - Boolean expression — evaluates to true/false.
- Compound Boolean — multiple conditions joined by
&&/||. - Conditional — executes only if a Boolean is true.
- De Morgan’s Laws — distribution of negation on complex conditionals.
- Logical AND / OR — truth rules for combined conditions.
- Negation — flips a truth value.
- Short-circuit evaluation — skip evaluating the second condition when first determines result.
2.13.2 Java Keyword Summary
if (Boolean)— start a conditional; follow with a statement or block.else— runs when the precedingifcondition was false.else if (Boolean)— adds additional mutually exclusive branches.
2.20 — Unit 2 Part 2: Loops (2.7–2.12)
Loops repeat a statement or block inside { }.
2.20.1 Concept Summary
- Body of a Loop — statement or block that can repeat (may run zero times).
- For Loop — header with initialization, condition, change (update).
- While Loop — repeats while a Boolean condition is true.
- Infinite Loop — never-ending loop.
- Nested Loop — one loop inside another.
- Out of Bounds error — accessing past end of string/list in a loop.
- Trace Code — write variable values as loop executes.
2.20.2 Java Keyword Summary
while— starts a while loopfor— starts a for (or for-each) loopSystem.out.println(variable)— useful for tracing and debugging
Unit 3 — Cortado (3.1–3.5)
High-level design & OOP structure: abstraction, impact of design, anatomy of a class, constructors, and how to write methods.
3.1 — Abstraction and Program Design
- Abstraction: hide low-level details and expose only what the user needs (e.g.,
Scannerhides how input is read from the keyboard). - Procedural abstraction: use methods as “black boxes” — you care about what they do, not how they do it internally.
- Object abstraction: design classes that model real-world or problem-world things with attributes and behaviors.
- Top-down design / decomposition: start from a big task → break into smaller sub-problems → write methods for each part.
- Good abstraction = small, focused methods; clear parameters and return types; internal details can change without breaking other code.
3.2 — Impact of Program Design
- Readability: good names for classes, methods, and variables make code easier to understand for humans (including “future you”).
- Maintainability: well-structured code (small methods, clear responsibility) is easier to fix, extend, and debug.
- Reusability: generic, well-designed methods and classes can be reused in other projects instead of rewriting logic.
- Collaboration: consistent style, comments, and APIs let multiple people work on the same code base.
- Testing: small, isolated methods are easier to test with different inputs and edge cases.
3.3 — Anatomy of a Class
- Typical class skeleton:
public class Player {
// 1) Fields (instance variables)
private String name;
private int score;
// 2) Constructors
public Player(String name, int score) {
this.name = name;
this.score = score;
}
// 3) Methods (behaviors)
public void addPoints(int points) {
score += points;
}
public int getScore() {
return score;
}
}
- Fields: store the state of each object (usually
private). - Constructors: special methods that run when you call
newto create and initialize an object. - Methods: actions the object can perform or questions you can ask about it.
- Access modifiers:
publicvsprivatecontrol what can be used from outside the class (encapsulation).
3.4 — Constructors
- Purpose: set up a new object in a valid starting state.
- Rules:
- Constructor name must exactly match the class name.
- No return type (not even
void).
- Overloading: a class can have multiple constructors with different parameter lists (number/types/order).
- Using
this: often used to distinguish fields from parameters (e.g.,this.health = health;). - Default / no-arg constructor: sets default values when no parameters are given.
public class Point {
private int x;
private int y;
// No-arg constructor
public Point() {
this(0, 0); // calls the other constructor
}
// Full constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
3.5 — Methods: How to Write Them
- Method header:
accessModifier returnType methodName(parameterList)
public int add(int a, int b) {
int sum = a + b; // local variable
return sum; // return value
}
- Parameters: input values the method needs; types and order must match the call.
- Return type:
voidif nothing is returned; otherwise type must match thereturnvalue. - Side effects vs pure: some methods only compute and return a value, others also change fields (update object state).
- Preconditions: what must be true before the method is called (e.g., parameter is non-negative).
- Postconditions: what the method guarantees after it finishes (e.g., returned value is in a certain range, object fields updated).
- Good method design:
- One clear job (“do one thing well”).
- Descriptive name that starts with a verb for actions (
calculateTotal,printReport). - Short body; if it becomes long, split into helper methods.