Overview
Topic 1.7 has one learning objective (1.7.A): identify the attributes and behaviors of a class found in the libraries contained in an API. The CED’s suggested skill is 4.A, describing the behavior of a code segment, so students spend most of both days reading code and documentation and saying what each part is and does, not writing new programs.
Students have been using library classes since Topic 1.3 without knowing it. This topic names what they have been doing:
- Day 1 (1.7.A.1): libraries are collections of classes, and classes are grouped into packages.
String,Math,System,Integer, andScannerall come from Java’s library; onlyScannerneeds an import line. - Day 2 (1.7.A.1, 1.7.A.2): the API specification tells programmers how to use a class without reading its code; a class’s attributes are data stored in variables and its behaviors are defined by methods; a class defines a reference type and is used to create objects.
Topic boundaryStay inside the topic boundary
- The only methods students meet are the ones the study guide uses:
Math.sqrt,Math.abs,Math.pow,length()on aString, and theScannerreads from Topic 1.4. Explain each one when it appears. The fullMathlist waits for Topic 1.11 and theStringlist for Topic 1.15. - Calls such as
Math.sqrt(144.0)andword.length()may be shown and traced. Say once that the rules for calls through a class name are taught in Topic 1.10 and calls on an object in Topic 1.14. Method headers and what goes in the parentheses are Topic 1.9. - Documentation lines show the word
staticand the program frame showspublicandstatic. Tell students they are explained in a later topic and can be read past for now. - No comments in code (Topic 1.8). A label and a value still take a
printfollowed by aprintln; joining text and numbers is Topic 1.15. newappears only as theScannerpattern from Topic 1.4. Say that it creates an object and that Topic 1.13 explains it; do not teach constructors.
Teacher note
Every program below is in the topic’s examples/ folder. 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.
- Day 1 direct instruction:
GardenPlan,ScoreBoard,LowercaseClass,TicketCount,FullName,MissingImport, andWrongPackagewithWrongPackageFixedfor the answer. - Day 1 guided practice: students type
TicketCountand change it;MissingImport,WrongPackage, andFullNameshow the results they should get.ImportLocalDateshows thejava.time.LocalDateimport from the closure question compiling. - Day 2 direct instruction:
TemperatureSwing,PowOrder,PowTry,GuessedName,IntegerLimits,CityLengths,AttributeParens,TripInfo, andTextInInt. - Day 2 guided practice:
NameLength.WordGoalis the study guide’s version of the same program, for students who finish early. - Printed only: none. The exit ticket has no code, and the puzzle worksheet and its key are separate Word files with their code printed on the page.
The Check Out the Library deck covers both days: slides 1–10 on Day 1 and slides 11–22 on Day 2. Its speaker notes hold the answers to every Pause and Try slide. Open GardenPlan, TicketCount, TripInfo, and NameLength in the IDE next to the deck before each day, and keep a scratch class open for the snippets. Compiler messages are quoted from a recent JDK; the wording can vary slightly between Java versions.
Day 1 · Warm-up: A square garden
Put this on the board: “A square garden has an area of 144 square feet. Write Java that stores the length of one side. You may use only +, -, *, /, and %.” Give two minutes.
Most students write double side = 12.0; or 144 / 12. Ask: “How did you know 12? What if the area were 150?” There is no operator that does it. Someone would have to write an algorithm that guesses, checks, and improves the guess over and over. Then ask: “Would you trust your version in every program you ever write?”
Show GardenPlan and run it: Side length in feet: 12.0. Line 6, Math.sqrt(144.0), hands 144.0 to square-root code that someone else wrote and tested. Then show slide 2 (Who wrote this code?): pairs pick out the capitalized names in Bakery and say who wrote each. Only Bakery is the programmer’s; Math.sqrt(225.0) gives back 15.0 from code nobody in the room wrote. Today is about where that code comes from.
Teacher note
Keep the warm-up to six minutes. Do not explain the call syntax yet; read Math.sqrt(144.0) as “use the Math
class’s square-root code on 144.0” and say that Topic 1.10 explains calls like this.
Day 1 · Direct instruction: Classes and libraries
Read the goals on slide 3, then start Part 1 (slide 4).
- Class. Point at
public class GardenPlan. Every program students have written is wrapped in a class: a named unit of Java code that groups related data with the actions that work on that data. Read pastpublicfor now. - Library (1.7.A.1, slide 5). A library is a collection of classes written to be used by other programs. Java comes with a large standard library. Ask the class to list capitalized names they have typed this year that they did not write. Collect
System(Topic 1.3),String(Topic 1.2),Scanner(Topic 1.4), andInteger(Topic 1.5), then addMath, and reveal the table on slide 5. None of them is part of the Java language the wayintanddoubleare; they are classes that come with every Java installation. - Spot the library classes (slide 6). Walk through
Bakeryline by line with the slide’s table:Bakeryis the programmer’s class;String,Math, andSystemare library classes.GardenPlanhas the same shape. The program has six statements and relies on three classes it never defined. Then showScoreBoard: different calculation (Math.abs(-12)gives the distance of -12 from zero,12), same lesson. One class is yours; every other capitalized class name came from the library. - Why use them? Ask for two reasons a programmer would use
Math.sqrtinstead of writing their own. Expected: it saves time, it is already tested, and the programmer can focus on their own problem. - Spelling counts. Run
LowercaseClass:math.sqrt(144.0)givescannot find symbolwithsymbol: variable math. There is no class namedmath, so Java guesses it is a variable, and there is no such variable either.
Misconception: Library classes are part of the Java language
Students treat String and Math as keywords, like int. Point to the capital letter: primitive type names and keywords are lowercase; class names start with a capital. String is a class someone wrote and shipped with Java, which is why it has documentation like any other class. This sets up Day 2, where a class turns out to be a type.
Misconception: math and Math are the same
Students who type fast write math, string, or scanner. Java is case-sensitive (Topic 1.1), and a library class has exactly one spelling. Teach students to read the symbol: line: variable math or class string means the name is spelled differently from the class.
Day 1 · Direct instruction: Packages, full names, and import
Start Part 2 (slide 7).
- Package (1.7.A.1, slide 8). Thousands of classes in one pile would be hard to search, and two classes could not share a short name. A package is a named group of related classes, like a labeled shelf. Package names are lowercase words joined by dots. Two matter in this course:
java.lang(String,Math,System,Integer) andjava.util(Scanner). - Full name. A class’s full name is its package, a dot, and its class name:
java.util.Scanner,java.lang.String. Everything before the last dot is the package. - Import. Show
TicketCount. Line 1,import java.util.Scanner;, is an import statement: “in this file,Scannermeans the classScannerfromjava.util.” It goes above the class, ends with a semicolon, and runs nothing; it is information for the compiler. Run it:Tickets: 19. - The import is only a shortcut. Show
FullName: no import line, andjava.util.Scannerwritten out twice on line 5. Same output,Tickets: 19. Programmers rarely write it this way, but it shows what the import line does. Slide 8 shows the two versions side by side. - Available by default. Ask: “Why has
Stringnever needed an import?” Classes injava.langare available by default: every program can use their short names. Every other package must be imported. - Predict (slide 9). Show
MissingImportand ask what happens. Run it:cannot find symbolwithsymbol: class Scanner, reported for eachScanneron line 5. Nothing runs. - Quick check. Show
WrongPackageand ask what is wrong with line 1.Scanneris injava.util, notjava.lang; the compiler reportscannot find symbolforclass Scannerinpackage java.lang, and then every use ofScannerfails.WrongPackageFixeddisplays15.
Misconception: Every library class is available without an import
String, Math, and System never needed an import, so students assume Scanner will not either. Only java.lang is available by default. Give students one question to ask of every class they use: “Which package is it in?” If the answer is anything but java.lang, the file needs an import line.
Misconception: The import line runs code or copies it into the program
Students picture import loading or running the Scanner code before main starts. It does neither: it only tells the compiler which class a short name means. FullName is the proof: with no import line at all, the program compiles and runs the same, because the full name gives the compiler the same information.
Day 1 · Guided practice: Break and fix the import line
Students type TicketCount into the IDE and run it (Tickets: 19). Then, one change at a time, they predict, compile, record the result, and undo the change:
- Delete line 1. Expected:
cannot find symbol,symbol: class Scanner, for eachScanneron the line that creates theScanner(as inMissingImport). Nothing runs. - Put line 1 back as
import java.lang.Scanner;. Expected:cannot find symbolforclass Scannerinpackage java.lang, then errors whereScanneris used (as inWrongPackage). - Put back
import java.util.Scanner;, then delete it again and writejava.util.Scannerin both places on the line that creates theScanner. Expected: it compiles and displaysTickets: 19(as inFullName).
Debrief: ask which change showed that the import line is a shortcut (3), and which symbol: line pointed at a missing import (1).
Teacher note
If computers are not available, make each change on the projector after students predict. Students who finish early can start puzzle worksheet question 1.
Day 1 · Independent practice: Independent practice
Hand out the Check Out the Library puzzle worksheet. Question 1 (who wrote each class in TicketBooth, its package, and whether it needs an import) and the Think First box are homework. Students keep the worksheet for Day 2.
Day 1 · Closure: Closure
Show slide 10 (How many import lines?). Students answer both questions on scrap paper: a program that uses String, Math, Scanner, and Integer needs one import line, import java.util.Scanner;; and a LocalDate class in the package java.time needs import java.time.LocalDate;. Watch for import java.time; (only the package) and the parts in the wrong order. Ask a volunteer to write the LocalDate line on the board. Run ImportLocalDate to show it compiling, but do not display its code: it contains null, which Topic 1.13 teaches.
Day 2 · Warm-up: Packages and import, from memory
Students answer three questions on scrap paper, without notes:
- What is the full name of
Scanner? (java.util.Scanner) - Which of
String,Math,Scanner, andIntegerneeds an import line? (OnlyScanner.) - A program uses
Scannerwith no import line. What does the compiler report? (cannot find symbol, withsymbol: class Scanner.)
Then ask: “Yesterday you used Math.sqrt and Math.abs. How would you find out what else Math can do, without reading its code?” Collect guesses and move on to Part 3 (slide 11).
Day 2 · Direct instruction: API documentation
- Interface. A microwave’s buttons are its interface: you use it without knowing its wiring. An application programming interface (API) is the set of classes, and the parts of those classes, that a library offers for other programs to use. The CED says “application program interface”; both mean the same thing.
- Documentation (1.7.A.1). The API specification, usually called the documentation, describes the API: which classes exist, which package each one is in, what each is for, and how to use each part. Java’s documentation is free online, with one page per class. It is how programmers learn what a class can do without reading its code.
- Read a page (slide 12). Show the simplified
Mathpage and take it apart from the top: the package (java.lang, so no import), the class name, and the Method Summary. A method is a named piece of code that does one job. Each row gives what kind of value comes back, the name, what goes in the parentheses, and what it does. Read paststatic; Topic 1.10 explains it, and Topic 1.9 teaches these method headers in full. - Find the method (slide 13, left). A weather program needs the size of a temperature change as a positive number.
41 - 63is-22. Which row does the job?abs, “the absolute value of a,” so the program displays22. RunTemperatureSwing, the same program with 58 and 71 degrees:13. - Order is in the documentation (slide 13, right). Show
PowOrderand ask for predictions before running. Thepowrow says “a raised to the power b”, soMath.pow(2.0, 10.0)is1024.0andMath.pow(10.0, 2.0)is100.0. Only the documentation tells you which value is the base.PowTryis a second example if students need one (9.0, then8.0). - Do not guess (slide 14). Slide 14’s
Math.cube(3.0)givescannot find symbolwithsymbol: method cube(double); the fix isMath.pow(3.0, 3.0). RunGuessedNamefor a second case:Math.squareRoot(144.0)fails the same way, and the fix is to look up the real name,sqrt. - Pause and try (slide 15). Students predict
6.0,9.0, and4. Students who write6and9ignored the type the documentation says comes back.
Teacher note
If you want to show the real Math page online, point only at the package line, the description, and the heading “Method Summary.” Do not walk through its rows: it lists many more methods, several with the same name, which Topics 1.9–1.11 explain. Slide 12’s page is simplified and written in the guide’s own words; say so.
Misconception: A method name can be guessed
squareRoot or power sounds reasonable, so students type it and expect Java to understand. Java knows only the names the class actually has. Make “check the documentation” the first step whenever students use a library method today, and point out that the symbol: line names the method the compiler looked for.
Misconception: The documentation shows how the method works inside
Students expect documentation to contain the method’s code, and some worry that using code they cannot see is cheating or unsafe. Documentation describes what each part does and how to use it, not its code; that is the point of an API. The microwave analogy helps: you trust the button labeled “Popcorn” without opening the case.
Day 2 · Direct instruction: Attributes and behaviors
Start Part 4 (slide 16).
- Two kinds of entries (1.7.A.2, slide 17). Describe a phone: some things are facts (its battery level, its phone number) and some are actions (make a call, take a photo). An attribute is data related to a class, stored in variables. A behavior is what the class’s objects can do, or what can be done with them, defined by methods. Test: a noun phrase (“the largest value”) is an attribute; a verb phrase (“give back the square root”) is a behavior.
- Field Summary. Sketch the
Integerentries on the board: a Field Summary withMAX_VALUEandMIN_VALUE, and a Method Summary withparseInt.MAX_VALUEandMIN_VALUEare in the Field Summary, where documentation lists the attributes programs may use; a field is Java’s name for a variable that belongs to a class.parseIntis in the Method Summary, so it is a behavior. Do not useparseIntin code; it is here only to sort. RunIntegerLimits: an attribute is read by name with no parentheses (2147483647,-2147483648), the same constants students used in Topic 1.5. - A behavior of a
String. TheStringdocumentation listslength(), “the number of characters in this string.” Slide 17 shows it on two objects:"Ada"gives3and"Grace Hopper"gives12. RunCityLengths:6and11. The space in"Kansas City"counts. A behavior is written with parentheses, even when nothing goes inside, and the result depends on which object does it. Say once that calls such ashome.length()are taught fully in Topic 1.14. - Not every attribute is listed. A
Stringmust store its characters somewhere, but that variable is hidden inside the class. The documentation describes it in words (“holds a sequence of characters”) and programs use it through behaviors such aslength(). - Watch out (slide 18). Run
AttributeParens:Integer.MAX_VALUE()givescannot find symbolwithsymbol: method MAX_VALUE(). The parentheses told Java to look for a method. Slide 18 also shows the mirror-image slip,city.lengthwith no parentheses, which givessymbol: variable length. Field Summary entries are written without parentheses; Method Summary entries with them.
Misconception: Attributes and behaviors swapped
Students remember both words but attach them to the wrong things, or think an attribute is “something you do to an attribute.” Keep the fact-or-action test on the board all period, and connect it to the two summaries: Field Summary means data in variables, so no parentheses; Method Summary means actions, so parentheses.
Misconception: Parentheses after every name
After a day of Math.sqrt(...) and length(), students add parentheses to Integer.MAX_VALUE, or drop them from length. Both give cannot find symbol; the symbol: line says method MAX_VALUE() or variable length, which tells you which kind of entry Java looked for. Puzzle worksheet question 3 has the first slip, and a decoy tile in question 4 has the second.
Day 2 · Direct instruction: Classes are types that make objects
- A class is a type (1.7.A.1, slide 19). In Topic 1.2, students sorted types into primitive and reference. Now the reason
Stringis capitalized: it is a class, and each class defines its own reference type.String citycan hold text;Scanner readercan hold a scanner; neither can hold the other. What a reference variable actually stores is Topic 1.12. - A class is a blueprint. A blueprint describes every house built from it, but you live in a house, not a blueprint. One particular thing made from a class is an object, also called an instance.
"Denver"and"Kansas City"are twoStringobjects, each with its own characters. The analogy has a limit: an object has only the attributes and behaviors its class defines. - Walk through
TripInfo. Slide 19’s table does the same for three declarations. For each declaration, ask: what type, and is an object created?milesisint(no object);cityisString, and the literal"Denver"is aStringobject;readerisScanner, andnew Scanner("3")creates aScannerobject (newcreates an object; Topic 1.13 explains it);daysisint. Run it. Mathis different. The program usesMathwithout aMathvariable or aMathobject: its behaviors are used through the class name. Topic 1.10 explains this kind of method.- Wrong type. Run
TextInInt:int city = "Denver";givesincompatible types: String cannot be converted to int. The message names the value’s type and the variable’s type. Declare it with the class that matches the object.
Misconception: String is just another primitive type
Students list String beside int and double because they use it the same way. It is a class from java.lang, so it defines a reference type, and its values are objects with behaviors such as length(). Ask, “Can an int do anything?” It cannot; a String can tell you its length.
End with slide 20 (Attribute or behavior?): pairs sort four things the Scanner documentation describes. (a) and (c) are attributes; (b) and (d) are behaviors. Push on (c): reading a number changes how far the scanner has read, so behaviors can use and change attributes.
Day 2 · Guided practice: Take apart NameLength
Show NameLength without running it. A site wants usernames that are exactly 12 characters long, and the program reports how many characters jo_rivera is away from that. Pairs:
- Circle every class name and label it “ours” or “library.”
- Fill a table with one row per library class: package, import needed, and whether the program declares a variable of that type or uses the class only through its name.
- List every behavior the program uses.
- Predict the output, then run it.
- Change
"jo_rivera"to"jordan_rivera"and predict again.
Answers: NameLength is ours; Scanner (java.util, import, type of reader and an object made with new), String (java.lang, no import, type of name and an object from the literal), Math (java.lang, no import, used only through the class name), and System (java.lang, no import, output only). Behaviors: nextInt, length, abs, println. Output 3: "jo_rivera" has 9 characters, and Math.abs(12 - 9) is 3. After the change, "jordan_rivera" has 13 characters and Math.abs(12 - 13) is 1; abs keeps the answer positive whether the name is too short or too long.
Day 2 · Independent practice: Independent practice
Puzzle worksheet questions 2–9 (reading the Math documentation, be-the-compiler, code tiles and a snippet pool with Math and length(), the attribute-and-behavior face-off, a one-token fix, two truths and a lie about reference types and imports, and who am I) are homework.
Day 2 · Closure: Closure and exit ticket
Point to slide 21’s cards and ask the class to finish two sentences aloud: “An attribute is … and a behavior is …” (data stored in variables; what objects can do, defined by methods) and “A class does two jobs: …” (it defines a type, and it is a blueprint for objects). Then show slide 22 (Look it up, don’t guess) and have one pair explain with the sentence starter. Closure takes about two minutes. Then give the exit ticket (about five minutes, timed separately). Question 1 checks sorting a class’s attributes and behaviors and writing an import line (1.7.A.1, 1.7.A.2); question 2 checks packages and import (1.7.A.1). Re-teach the weaker one at the start of Topic 1.8.