• References/Citations
  • Reference Guide

    Term Definition / Example College Board Requirement
    Algorithm A step-by-step process that completes a task: The login steps below Unit 1, Topic 1.1, pp. 30–31
    Sequencing Doing the steps one at a time, in order: Log in before you click Send Unit 1, Topic 1.1, 1.1.A.2, pp. 30–31
    Source code The Java program you write, saved in a .java file: StoreUserInfo.java Unit 1, Topic 1.1, pp. 30–31
    Compiler Checks code for syntax errors and turns it into bytecode: javac StoreUserInfo.java Unit 1, Topic 1.1, 1.1.B.2, pp. 30–31
    Bytecode The compiled .class file that the Java Virtual Machine runs: StoreUserInfo.class —
    Exception A run-time error that stops the program while it runs: ArithmeticException Unit 1, Topic 1.1, pp. 30–31
    • The compiler finds syntax errors before the program can run
    • Testing with answers you already know finds logic errors the compiler cannot see

    Types of Errors

    Error When you find it Example
    Syntax The compiler stops you, so the program cannot run yet. System.out.println("Hi") with no semicolon
    Logic It runs, but testing shows a wrong answer. test1 + test2 / 2 divides before adding
    Run-time (exception) It compiles, then stops while running. 12 / 0 throws an ArithmeticException

    College Board Requirements

    AP CSA Unit 1, Topic 1.1 Introduction to Algorithms, Programming, and Compilers. Quoted from the course and exam description (College Board, 2025, pp. 30-31):

    • 1.1.A.2 “Sequencing defines an order for when steps in a process are completed. Steps in a process are completed one at a time.”
    • 1.1.B.2 “A compiler checks code for some errors. Errors detectable by the compiler need to be fixed before the program can be run.”
    • 1.1.C.2 “A logic error is a mistake in the algorithm or program that causes it to behave incorrectly or unexpectedly. These errors are detected by testing the program with specific data to see if it produces the expected outcome.”

    HashMap is outside the AP CSA Java subset. This lesson uses it in the login example because it looks up a password by username in one step, but it will not be on the exam.

    Reference: College Board, AP Computer Science A Course and Exam Description (2025), Unit 1, Topic 1.1, pp. 30–31.


    Real-Life Application

    Two Spacecraft That Compiled Just Fine

    In 1996, Europe’s brand-new Ariane 5 rocket blew itself up about 40 seconds after launch. In 1999, NASA’s Mars Climate Orbiter reached Mars and was never heard from again. Neither failure was a syntax error: the code in both compiled and ran. Everyone take 30 seconds and guess which kind of error each one was before you read the table!

    Mission What Went Wrong Error Type Would the Compiler Catch It?
    Ariane 5, Flight 501 (1996) Code reused from the older Ariane 4 tried to fit a 64-bit decimal value into a 16-bit integer. The number was too big, an exception was thrown, and the guidance system shut down. Run-time error (exception) No: it only failed while running
    Mars Climate Orbiter (1999) One team’s software reported thruster force in pound-force seconds, and the navigation team’s software read it as newton-seconds. Every number looked fine; the answer was wrong. Logic error No: only testing with known answers could catch it
    Your next missing semicolon System.out.println("Hi") Syntax error Yes: the program cannot run until you fix it

    The takeaway: “it compiles” is the first check, not the last one. That is why every homework hack in this lesson ends with checks that must print true.


    Tech Talk

    Learning Objective: Write an everyday algorithm as ordered steps, explain how code is compiled and run, and identify syntax, logic, and run-time errors.

    Success Criteria: You can order steps, fix an algorithm with steps out of order, turn an algorithm into code, and name the error type in a broken program.

    An algorithm is a list of steps in order. Each step runs one at a time, so order and detail decide whether it works.

    Making a sandwich

    1. Get two slices of bread
    2. Spread peanut butter on one slice
    3. Spread jelly on the other slice
    4. Put the slices together
    5. Cut in half

    Notice how each step is clear and in a specific order. That’s an algorithm!

    Java code is compiled before it runs. The compiler catches broken rules, but it cannot catch a wrong answer, so test with data where you know the result.

    From Code to Running Program

    Step What happens Errors found here
    1. Write You type source code in a .java file. None yet
    2. Compile javac checks the rules and makes a .class bytecode file. Syntax errors
    3. Run The Java Virtual Machine (JVM) runs the bytecode. Run-time errors (exceptions)
    4. Test You compare the output with an answer you already know. Logic errors
    
    int test1 = 80;
    int test2 = 90;
    int average = test1 + test2 / 2;   // compiles, but prints 125 instead of 85
    

    This lesson does not run a real login server. The login example keeps three made-up users in a small in-memory map, so you can test the algorithm without real accounts.


    Code Examples

    A. Storing information. The StoreUserInfo class stores a name, an age, and a student flag, then prints them

    Order matters even in two lines:

    
    System.out.println("Name: " + name);   // uses name before it exists: the compiler stops you
    String name = "Alice";                // declare and store first, then print
    

    Terminology:

    Sequencing: Java runs these lines top to bottom, one at a time. Swapping two lines can turn a working program into a syntax error or a wrong answer.


    Code Runner Challenge

    Change the values, predict the output, then run it

    View IPYNB Source
    // CODE_RUNNER: Change the values, predict the output, then run it
    public class StoreUserInfo {
        public static void main(String[] args) {
            // Algorithm: Store user information
            int age = 16;
            String name = "Alice";
            boolean isStudent = true;
    
            System.out.println("Name: " + name);
            System.out.println("Age: " + age);
            System.out.println("Is a student: " + isStudent);
    
            // Try changing the values and run again!
            // age = 17;
            // name = "Bob";
        }
    }
    
    StoreUserInfo.main(null);
    
    Lines: 1 Characters: 0
    Output
    Click "Run" in code control panel to see output ...

    B. Login algorithm. The LoginSystem class turns the seven login steps into Java code

    
    1. Get username from user
    2. Get password from user
    3. Check if username exists in database
    4. If username doesn't exist → show error message
    5. If username exists → compare password
    6. If password matches → grant access
    7. If password doesn't match → show error message
    

    The steps above, written as code.

    Common ordering mistake:

    
    userDatabase.get(username).equals(password);   // step 5 first: a missing user gives null, so this throws a NullPointerException
    userDatabase.containsKey(username);            // step 3 first: check the user exists, then compare
    

    Terminology:

    Run-time error: skipping step 3 still compiles, so the compiler cannot warn you. The program only fails while running, when a test uses a username that is not in the map.


    Code Runner Challenge

    Run the three tests, then add a test for bob with the wrong password

    View IPYNB Source
    // CODE_RUNNER: Run the three tests, then add a test for bob with the wrong password
    import java.util.HashMap;
    import java.util.Map;
    
    public class LoginSystem {
        // Simple user database
        private static Map<String, String> userDatabase = new HashMap<>();
    
        static {
            userDatabase.put("alice", "password123");
            userDatabase.put("bob", "securepass");
            userDatabase.put("charlie", "mypass456");
        }
    
        // Login algorithm
        public static boolean login(String username, String password) {
            // Step 3: Check if username exists
            if (!userDatabase.containsKey(username)) {
                // Step 4: Handle user not found
                System.out.println("❌ Error: Username not found");
                return false;
            }
    
            // Step 5-7: Compare password
            if (userDatabase.get(username).equals(password)) {
                System.out.println("✅ Login successful!");
                return true;
            } else {
                System.out.println("❌ Error: Incorrect password");
                return false;
            }
        }
    
        public static void main(String[] args) {
            System.out.println("Test 1: Correct login");
            login("alice", "password123");
    
            System.out.println("\nTest 2: Wrong password");
            login("alice", "wrongpass");
    
            System.out.println("\nTest 3: User doesn't exist");
            login("david", "anypass");
        }
    }
    LoginSystem.main(null);
    
    Lines: 1 Characters: 0
    Output
    Click "Run" in code control panel to see output ...

    Hacks & Practice Tasks

    
    Lesson: CSA 1.1 Algorithms, Programming, and Compilers
    MCQ 1.1: <paste the copied result line, such as 3/4 | answers: D,A,C,B>
    Popcorn: 10 store closing steps printed in order (yes/no); first = <first step>; last = <last step>; why the employee door is last = <your reason>
    Homework Hack 1: <activity chosen>, <number> steps, check prints true (yes/no)
    Homework Hack 2: corrected email order = <your order>, both checks print true (yes/no)
    Homework Hack 3: all six grade checks print true (yes/no); the two logic errors were = <one line>
    

    Popcorn Hack

    2-minute challenge: the 10 steps for closing a store are out of order. Put them in order, then run the cell.

    1. Read all 10 steps first
    2. Think about what has to happen before each step
    3. Move each System.out.println line to its correct spot
    4. Run it and check that the output reads like a real closing routine
    5. Answer the question in the Popcorn checker under the runner before you run. When every check passes, copy its line into your notes

    Keep all 10 steps. Only change their order.

    Code Runner Challenge

    Move the lines into the right order, then run it

    View IPYNB Source
    // CODE_RUNNER: Move the lines into the right order, then run it
    // Practice #1 - Store Closing Algorithm. Try it yourself first!
    public class StoreClosing {
        public static void main(String[] args) {
            // These 10 steps are out of order. Move each line so the store closes safely.
            System.out.println("Mop the floor");
            System.out.println("Turn on the security system and cameras");
            System.out.println("Count inventory");
            System.out.println("Lock the front door after the last customer leaves");
            System.out.println("Take out the trash");
            System.out.println("Exit through the employee door and lock it");
            System.out.println("Close out cash registers and put the money somewhere safe");
            System.out.println("Turn off all of the lights");
            System.out.println("Straighten up the items on the shelves");
            System.out.println("Make a list of items that need to be restocked");
        }
    }
    
    StoreClosing.main(null);
    
    Lines: 1 Characters: 0
    Output
    Click "Run" in code control panel to see output ...

    Before you press Run, answer this in your own words.

      Pass every check to finish the Popcorn Hack.

      MCQ Check

      4 questions, one at a time. Answer, check, then go to the next one. At the end, copy the score line into your notes.

      Homework Hack

      Task: Practice the three algorithm skills one at a time: write steps, put steps in order, and test code with answers you already know. Each starter compiles before you edit it, so you can run the initial version and compare its incorrect output with the expected output. Change only what the TODO asks for, and keep going until every check prints true.

      Solution Skeleton:

      Hack 1: Write an Algorithm

      Algorithms. Write an algorithm of at least 6 specific steps, in order, for one of these: getting ready for a basketball game, making a pizza from scratch, or setting up a new phone. Put each step in its own step("...") line.

      Code Runner Challenge

      Add your steps until the check prints true.

      View IPYNB Source
      // CODE_RUNNER: Add your steps until the check prints true.
      public class MyAlgorithm {
          static int stepCount = 0;
      
          // Prints one numbered step and counts it.
          static void step(String text) {
              stepCount++;
              System.out.println(stepCount + ". " + text);
          }
      
          public static void main(String[] args) {
              String activity = "TODO: basketball game, pizza from scratch, or new phone";
              System.out.println("Algorithm: " + activity);
      
              // TODO: write at least 6 specific steps, in order, one step("...") line each.
              step("First step goes here");
      
              System.out.println(stepCount >= 6);
          }
      }
      MyAlgorithm.main(null);
      
      Lines: 1 Characters: 0
      Output
      Click "Run" in code control panel to see output ...

      Hack 2: Fix the Step Order

      Sequencing. These steps are out of order. Rewrite them correctly.

      
      Algorithm: Send an Email
      1. Click "Send"
      2. Open email application
      3. Type the message
      4. Log into your account
      5. Enter recipient's email address
      6. Write subject line
      

      Move whole lines in the runner below. Keep all six steps and do not change their text.

      Code Runner Challenge

      Move the step lines into the right order so both checks print true.

      View IPYNB Source
      // CODE_RUNNER: Move the step lines into the right order so both checks print true.
      public class EmailOrder {
          static int stepNumber = 0;
      
          // Prints one numbered step and returns its position in the order.
          static int step(String text) {
              stepNumber++;
              System.out.println(stepNumber + ". " + text);
              return stepNumber;
          }
      
          public static void main(String[] args) {
              // Algorithm: Send an Email
              // TODO: these six lines are out of order. Move whole lines; do not change the text.
              int send = step("Click \"Send\"");
              int open = step("Open email application");
              int message = step("Type the message");
              int login = step("Log into your account");
              int recipient = step("Enter recipient's email address");
              int subject = step("Write subject line");
      
              System.out.println(open == 1 && login == 2);
              System.out.println(send == 6);
          }
      }
      EmailOrder.main(null);
      
      Lines: 1 Characters: 0
      Output
      Click "Run" in code control panel to see output ...

      Hack 3: Find the Logic Errors

      Testing for logic errors. This calculator compiles and runs, but it gives the wrong letters. Find and fix the two logic errors until all six checks print true. Hint: one error is in how the average is worked out, and the other only shows up at exactly 90. The rule: 90 and up is an A, 80 a B, 70 a C, 60 a D, anything lower an F.

      Code Runner Challenge

      Find and fix the two logic errors so all six checks print true.

      View IPYNB Source
      // CODE_RUNNER: Find and fix the two logic errors so all six checks print true.
      public class LetterGradeCalculator {
          /**
           * Calculate letter grade from three test scores
           *
           * @param score1 first test score
           * @param score2 second test score
           * @param score3 third test score
           * @return the letter grade
           */
          public static String calculateGrade(int score1, int score2, int score3) {
              // Step 1 and 2: Add the three scores together, then calculate the average
              double average = score1 + score2 + score3 / 3.0;
      
              // Step 3: Determine the letter grade using if-else if-else
              if (average > 90) {
                  return "A";
              } else if (average >= 80) {
                  return "B";
              } else if (average >= 70) {
                  return "C";
              } else if (average >= 60) {
                  return "D";
              } else {
                  return "F";
              }
          }
      
          public static void main(String[] args) {
              // Test your function!
              System.out.println("A".equals(calculateGrade(95, 92, 88)));  // Test 1: should be A
              System.out.println("B".equals(calculateGrade(85, 80, 82)));  // Test 2: should be B
              System.out.println("C".equals(calculateGrade(75, 70, 72)));  // Test 3: should be C
              System.out.println("D".equals(calculateGrade(65, 60, 62)));  // Test 4: should be D
              System.out.println("F".equals(calculateGrade(55, 50, 52)));  // Test 5: should be F
              System.out.println("A".equals(calculateGrade(90, 90, 90)));  // Test 6: exactly 90 should be A
          }
      }
      LetterGradeCalculator.main(null);
      
      Lines: 1 Characters: 0
      Output
      Click "Run" in code control panel to see output ...

      References/Citations

      Altadmri, A., & Brown, N. C. C. (2015). 37 million compilations: Investigating novice programming mistakes in large-scale student data. In Proceedings of the 46th ACM Technical Symposium on Computer Science Education (pp. 522–527). Association for Computing Machinery. https://doi.org/10.1145/2676723.2677258

      College Board. (2025). AP Computer Science A course and exam description [Effective fall 2025]. https://apcentral.collegeboard.org/media/pdf/ap-computer-science-a-course-and-exam-description-effective-fall-2025.pdf

      All Java lessons