Overview
Day 1 is assignment (1.4.A). Students use = to initialize a variable and to change it, learn that Java evaluates the whole right side to one value before storing it (1.4.A.2), find the type of that value and check that the variable can hold it (1.4.A.1, 1.4.A.3), and see that a variable must be assigned before it is used. Day 2 starts with reference variables and null (the rest of 1.4.A.1), then moves to input (1.4.B.1): the forms input can take, and reading text with a Scanner using nextInt, nextDouble, and nextLine.
Students have declared int, double, and boolean variables (Topic 1.2), displayed values with print and println, and evaluated arithmetic expressions, including integer division and % (Topic 1.3). Stay inside the topic boundary:
- A label and a value still take a
printfollowed by aprintln; joining text and numbers in one statement is Topic 1.15. - Every stored value has the same type as its variable. Do not store an
intvalue in adoublevariable or convert between types; that is Topic 1.5. Do not use+=or++(Topic 1.6). Stringappears only as a type for text, assigned a string literal ornull. Do not callStringmethods.new Scanner(...)andinput.nextInt()are used as patterns. Say once that creating objects is Topic 1.13 and calls likeinput.nextInt()are Topic 1.14. Use onlynextInt,nextDouble, andnextLine.- Two CED exclusions: assignment inside an expression (such as
a = b = 4;) is not tested, so do not show it, and no specific form of user input is tested, soScanneris a classroom tool, not exam content.
Teacher note
The slides are the Store It and Scan It deck (20 slides, with speaker notes); slide numbers below refer to it. Day 1 uses slides 1–11 and closes with slide 20; Day 2 uses slides 12–19. The deck names its Scanner variable console and the topic’s examples name it input; tell students the name is the programmer’s choice. The Store It and Scan It puzzle worksheet (10 questions, about 30 minutes) is split across the two nights: questions 1, 2, 4, 5, 7, and 10 are about assignment and go home after Day 1; questions 3, 6, 8, and 9 use null or a Scanner and go home after Day 2.
Files whose names end in .snippet.java hold only the statements that go inside main; paste them into the main of a scratch class to run them. All files are in the topic’s examples/ folder.
- Day 1 demonstrations:
PointsUpdate,TicketCount,PlayerLives,ReversedAssignment,CopyValue,TotalNotUpdated,TotalUpdated,QuizAverage,TypeFromOperations,LossyAverage,BooleanIntoInt,StepGoal,Uninitialized,ScoreTrace, andSwapFixed(the swap challenge’s solution; do not show it until pairs have tried). - Day 2 demonstrations:
NicknameLater,NullInt,QuotedNull,UnassignedString,MottoNull,AgeFromText.java,NoImport.java,SnackOrder.java,OrderReaderLines.java,WrongInput.java,WrongInputFixed.java, andCarWash.java(the model solution for the guided practice; do not show it until students have tried). - Printed only (exit ticket):
ExitCopyandArcadeTokens.java.
Every program in this topic that reads input gets it from a string, as in new Scanner("16"), so it has one exact output to trace. To read the keyboard instead, replace the string with System.in. Before Day 2, check that a keyboard program runs in your IDE and that students can type into its console.
Day 1 · Warm-up: Is points = points + 5 true?
Write points = points + 5 on the board. Ask: “In math, is this ever true?” (No number equals itself plus 5.) Then show PointsUpdate and ask students to write what Java displays. Take a few answers, run it (15), and leave the question open: “Why is that legal in Java? By the end of today you will be able to explain it.”
Teacher note
Slide 2 (a scoreboard where Home gets its score plus 2) is an unplugged version of the same warm-up. Use it instead
of, or just before, PointsUpdate if you want students to talk before they see code.
Day 1 · Direct instruction: The assignment operator
- Goals (slide 3). Goals 1–3 are today’s; goals 4 and 5 (
nulland theScanner) are Day 2’s. - Assignment (1.4.A.2, slide 5). An assignment statement stores a value in a variable. It uses the assignment operator
=: the variable on the left, the value on the right, a semicolon at the end. Readtickets = 3;as “ticketsgets 3,” not “ticketsequals 3.” In math=states a fact; in Java it is an action that happens once, when the line runs. - Initialize, then change (1.4.A.1, 1.4.A.2, slide 5). The first assignment initializes the variable. Every later assignment changes its value: the new value replaces the old one, which is gone. Slide 5 shows
ticketsgoing from 8 to 5. Students then predictTicketCount, and trace it with you (3, then8). The sameprintlndisplays different values because each one displays what the variable holds at that moment. - The type goes only in the declaration. Show
PlayerLives:int lives = 3;declares and initializes in one statement;lives = 2;has no type, becauselivesalready exists.
Misconception: Writing the assignment backward
Because = looks like the math equals sign, students write 10 = score;. Run ReversedAssignment: unexpected type (required: variable, found: value). The left side must name a storage place; 10 is a value with nowhere to store anything. Have students read every assignment aloud as “the left gets the right.”
Day 1 · Direct instruction: The right side first
- Two steps, always (1.4.A.2, 1.4.A.3, slide 6). An expression is code that produces one value. Java (1) evaluates the whole right side using the values variables hold right now, then (2) stores that one value on the left. Walk through slide 6 (
steps = steps + 450;: look up 300, evaluate 750, store 750), then go back to the warm-up and do the same on the board: evaluatepoints + 5withpointsstill 10, get 15, then store 15. That is why a variable can appear on both sides. - A copy, not a link (slide 7). Students predict slide 7 (
doubledstays 8 afterbasechanges), then predictCopyValueandTotalNotUpdated. Run both.tuesday = monday;copies the value 12; changingmondaylater leavestuesdayalone.total = price * quantity;stores 12 once; changingquantityon the next line does not recompute it. - The fix is to run the assignment again. Show
TotalUpdated: assigningtotalagain after the change displays20. - Trace it (slide 8). Students fill in the trace table alone on scrap paper, then compare with a partner: after the four lines
xis 10 andyis 2, so the output is10, then2.
Misconception: An assignment updates itself like a spreadsheet formula
Students who use spreadsheets expect total to change when quantity changes. Java stores a number, not a formula. Nothing is illegal, so there is no error message: this is a logic error (Topic 1.1). Ask, for every variable in a trace: “Which line last stored a value in it? Has that line run again since?”
Misconception: Copying links two variables
After int tuesday = monday; students expect the two to change together. Draw two separate boxes: line 2 put a copy of 12 in the second box, and the boxes are not connected. CopyValue displays 20 and 12.
Day 1 · Direct instruction: The type of an expression, assign before use
- Every expression has a type (1.4.A.3, slide 10). Slide 10 lists five expressions with their values and types; cover the last two columns and have students fill them in. Then students predict the type and value of each right side in
QuizAverage:85 + 90 + 78is theint253,total / 3.0is thedouble84.33333333333333, andtotal / 3is theint84. Java applies the Topic 1.3 rules one operation at a time; the last operation’s result decides the type.TypeFromOperations(10 / 4 * 2.0) gives thedouble4.0, even though 4 is whole. - Compatible types (1.4.A.1, slide 10). The value must come from a type the variable accepts:
intvalues forintvariables,doublevalues fordoublevariables,trueorfalseforbooleanvariables. ShowLossyAverage:int average = total / 3.0;does not compile (possible lossy conversion from double to int), because aninthas no place to keep the decimal part.BooleanIntoIntshows the same error family forint count = true;. Topic 1.5 shows a few cases where Java converts a value for you; today, match the types. - Assign before you use (1.4.A.1, slide 11). Slide 11 shows the error and its fix with
lives. Then showStepGoalandUninitializedside by side. Both declare a variable with no value.StepGoalassignsstepsbefore line 3 uses it and displays5000.Uninitializedusesbonusin50 + bonusbefore any value is stored, and the compiler reportsvariable bonus might not have been initialized. The error points at the line that uses the variable; look upward from there for the missing assignment.
Misconception: A whole-number value is an int
Students think 3.0 * 4 can go in an int because 12.0 has nothing after the decimal point. The compiler checks the type, not the particular value: any expression with a double operand in its last operation is a double. Have students label the type of every intermediate result.
Misconception: A declaration gives the variable a default value
Students expect int bonus; to hold 0. It holds nothing usable, and Java refuses to compile code that uses it. Ask why that is better than a silent 0: a made-up 0 would give a believable wrong answer, a logic error, while a compile error forces the programmer to choose the starting value.
Day 1 · Guided practice: The swap challenge
- Predict. Pairs trace
ScoreTraceon scrap paper with columns forfirstandsecond. The student who wrote it wanted to swap the values. Output:10, then9. The swap failed:first = second;replaced 5 with 9, and the 5 was gone beforesecond = first;ran. - Fix it. Pairs write a swap that works, using one extra variable. Call on one pair to write theirs on the board, then trace it with the class. Show
SwapFixed:int saved = first;keeps the 5 before it is replaced, and the output is9, then5.
Teacher note
If pairs are stuck after two minutes, give the hint: “Before you replace a value, where could you keep a copy of it?”
Pairs that finish early can trace TotalNotUpdated again and change one line so it displays 20.
Day 1 · Independent practice: Independent practice
Hand out the puzzle worksheet. Questions 1, 2, 4, 5, 7, and 10 (be the JVM, a trace table, math’s = versus Java’s =, the average-jump snippet pool, a one-name swap fix, and a one-sentence wrap-up) are homework, about 18 minutes. Question 1 ends with a Think First prediction that question 2 settles. Students keep the worksheet for Day 2.
Day 1 · Closure: Closure
Show slide 20. Partners explain, step by step, what Java does when it runs total = total + price;, using the sentence starter: “First Java evaluates the right side using the values the variables hold now, then it stores the result in total.” If time allows, students also finish this sentence on a sticky note: “total = price * quantity; stores … , and it is worked out when …” Look for “one value (a number, not a formula)” and “the moment that line runs, using the values the variables hold then.”
Day 2 · Warm-up: A nickname that arrives later
Show NicknameLater in the IDE (not slide 12, which shows the answer) and ask students to write the output. Most expect an error on line 2 or an empty line. Run it: null, then Ace. Ask: “Line 1 stored something. What was it?”
Day 2 · Direct instruction: Reference variables and null
- Reference variables (1.4.A.1). From Topic 1.2, any type that is not primitive is a reference type.
String, the type for text, is one. A reference variable does not hold a number ortrue/false; it is connected to an object, such as a piece of text. Objects get their full treatment in Topics 1.12 and 1.13; today, two facts: a reference variable can be assigned an object (a string literal is one), or it can be assignednull. null(1.4.A.1, slide 12). The literalnullmeans the variable is not connected to any object. It is a fixed value written in the code, like3ortrue, so it has no quotes. Assigning it counts as initializing, soNicknameLaterline 2 compiles, and displaying the variable shows the wordnull. Line 3 replacesnullwith"Ace", an ordinary assignment.- Only reference types. Point to the right side of slide 12 (
double price = null;does not compile) and runNullInt:incompatible types: <null> cannot be converted to int. A primitive variable always holds an actual value, so “no object” makes no sense for it. - Check: compiles or not? (slide 13). Students decide alone for each of the four snippets, then compare with a partner: (1) compiles and displays
3.0; (2) compiles and displays2, becausepagesis assigned before it is used; (3) does not compile, because10 / 4.0is adouble; (4) does not compile, becausebooleanis primitive and cannot holdnull.
Misconception: null and "null" are the same
QuotedNull and NicknameLater both display null at first. With quotes it is a string literal, four letters of real text; without quotes it means no object. Ask: “Is there a piece of text here, or is there no object?” Write null without quotes when you mean “no object.”
Misconception: null means the variable was never assigned
Students treat “holds null” and “never assigned” as the same thing. Run UnassignedString (variable motto might not have been initialized) next to MottoNull (displays null). null is a real value that the program chose to store; a variable that was never assigned has no value and cannot be used.
Day 2 · Direct instruction: Forms of input and setting up a Scanner
- Input (1.4.B.1, slide 15). Input is data a program receives from outside itself. Ask students for examples, then sort them into the four forms on the left of slide 15: tactile (touches, presses, movements), audio (sound), visual (images or video), and text (characters). The CED does not test any specific form of input; the course uses text.
- The Scanner class (1.4.B.1, slide 15). A
Scanneris one way to get text input from the keyboard. Walk through the first two rows of the table on slide 15:import java.util.Scanner;at the top of the file, before the class;Scanner inputdeclares a reference variable;new Scanner(System.in)creates aScannerthat reads the keyboard (System.in) and is assigned toinput. Say once: creating objects withnewis explained in Topic 1.13; use the line as a pattern for now. - Reading from a string. Show
AgeFromText.java.new Scanner("16")reads the text16exactly as if a user had typed it, so the output is always the same:Age: 16.int age = input.nextInt();is an ordinary assignment: the right side produces oneint, stored inage. Calls likeinput.nextInt()are explained in Topic 1.14; read it as “askinputfor the next whole number.” Then replace"16"withSystem.in, run it, and type an age. Slide 16 (DogYears) is the same pattern as a complete keyboard program with a prompt.
Misconception: Scanner needs no import, like System
System is always available, so students skip the import. Run NoImport.java: cannot find symbol (symbol: class Scanner), reported once for each place the name appears on line 5. The fix is import java.util.Scanner; as the first line of the file. Topic 1.7 explains why some classes need an import.
Day 2 · Direct instruction: NextInt, nextDouble, nextLine
- Three reading calls (1.4.B.1, the last three rows of slide 15).
nextInt()reads the next piece as a whole number and produces anint;nextDouble()reads the next piece as a number that may have a decimal point and produces adouble;nextLine()reads everything to the end of the current line, spaces included, and produces aString(without the line break). Picture a marker that shows where theScannerreads next; every read moves it forward. Pieces are separated by spaces or line breaks, and\nin the string is a line break (Topic 1.3). - Predict:
SnackOrder.java. The input isAna Ortizon one line and4 1.25on the next. Students write the value each line stores, then the output. Trace the marker on the board:customergets"Ana Ortiz"(the space is included becausenextLinestops only at the line break),quantitygets 4,pricegets 1.25. Output:Ana Ortiz, then5.0(aninttimes adoubleis adouble). - Order matters, spacing does not. Run
OrderReaderLines.java: the numbers are spread over extra lines and spaces (3, a blank line, then2.5), and the reads still work. The output isAda Lovelace, thenCost: 7.5.nextInt()andnextDouble()skip spaces and line breaks to find their piece. The order of the calls must match the order of the input.
Misconception: nextInt rounds a decimal, or the compiler catches bad input
Run WrongInput.java: it compiles, displays Reading the quantity..., then stops with an InputMismatchException when nextInt() meets three. The compiler checks the code, not the input, so a mismatch shows up only while running. nextInt() also refuses 4.5 rather than dropping the decimal part; slide 17 shows the same crash when the second nextInt() meets 2.5. Run WrongInputFixed.java with matching input (3 2.5) to show the fix. When a real user types the input, a prompt such as How many? tells them what to type. Close with slide 18 (same code, three inputs): 6 3 and 3 6 both display 18, and 6 three throws an InputMismatchException at the second read.
Misconception: nextLine stops at a space
Students expect nextLine() to read only Ana. The number-reading calls stop at a space; nextLine() stops only at the end of the line.
Day 2 · Guided practice: Write CarWash, then break it
Students create CarWash.java in the IDE and write a program that reads a team name (one line), then the number of cars washed (a whole number) and the price per car (a decimal), and displays the team name and the money raised. They read the keyboard with new Scanner(System.in) and add a prompt with print before each read (for example System.out.print("Team name? ");). They run it and type Robotics Club, press Enter, then type 23 8.5. Expected: Robotics Club, then 195.5 (23 × 8.5).
Then, one change at a time, students predict, run, record, and undo:
- If you stored the money raised in a variable, declare it as an
intinstead of adouble. - Run it and type
twentyfor the number of cars. - Delete the
importline. - Run it and type
23and8.5on separate lines.
Debrief: (1) does not compile: possible lossy conversion from double to int, because the number of cars times the price per car is a double. (2) compiles and starts, then stops with an InputMismatchException at the nextInt() line. (3) cannot find symbol for Scanner. (4) the same output, because the number-reading calls skip line breaks.
Teacher note
CarWash.java in the examples folder is one correct solution. It reads from the string "Robotics Club\n23 8.5" instead of the keyboard so its output is fixed, and it has no prompts; a student version with System.in and prompts shows the prompts before the same two output lines. If computers are not available, write the program together on the projector and have students predict each change before you run it.
Day 2 · Independent practice: Independent practice
Puzzle worksheet questions 3, 6, 8, and 9 (snack-stand code tiles with a Scanner, be the compiler, two truths and a lie about null and "null", and who am I) are homework, about 12 minutes.
Day 2 · Closure: Closure and exit ticket
Show slide 19 (vocabulary) while students settle. Give the exit ticket (about five minutes). Question 1 checks assignment and evaluation order (1.4.A.2), question 2 compatible types, null, and assign before use (1.4.A.1, 1.4.A.3), and question 3 reading input with a Scanner (1.4.B.1). Re-teach the weakest one at the start of Topic 1.5.