Jump to page content Jump to navigation

College Board

AP Central

AP Exam Reader
Siemens Awards for Advanced Placement

APAC 2010
Print Page
Home > AP Courses and Exams > Course Home Pages > Java as a Pre-AP Strategy in Computer Science

Java as a Pre-AP Strategy in Computer Science

by James Aldridge, Ph.D.
Fort Worth Country Day School
Fort Worth, Texas

Part I

This is the first in a series of articles designed to take a computer science teacher in the Pre-AP years through the more difficult and confusing first components of teaching computer science in Java. We begin with an article discussing and supporting Java as a first language. Additional articles will discuss the logistics of getting the classroom ready, designing the course structure and the role of lectures and labs, integrating student projects in the course, and evaluating student assignments and projects.

Choosing an Implementation Language
The choice of an implementation language for computer science in the Pre-AP years is a hot topic among teachers. Indeed, whether such a course ought to even have a specified implementation language is up for discussion. To move the debate from the ivory tower to the secondary school classroom, I've observed that students as a group are more motivated to investigate program design, algorithms, data structures, and such when they are able to code applications that actually do something interesting.

Among the candidate languages for the Pre-AP years, Scheme, BASIC (including Visual Basic), Pascal, C/C++, Microsoft's .NET languages C# and J#, and Sun's Java might be included. These latter two are noteworthy as their attachment to certain companies gives them a proprietary air. I think this attachment says more about the nature of the relationship between the two companies than it says about any particularly proprietary quality of the languages themselves. Indeed, C#, J#, and Java are all object-based languages that share a C++-like syntax and a determined adherence to object design philosophy. This commonality makes all of them good candidates for a Pre-AP language.

I chose Java for a number of reasons.
  1. The compiler is free.
  2. There are several good, free integrated development environments (IDEs) available (indeed, it's easy to get up and running using only a simple text editor for writing source code; an IDE is optional).
  3. The language is a de facto standard for writing Web-based applications (applets).
  4. In the marketplace, C++ and Java run neck and neck as important languages.
  5. Java is seamlessly available in Linux and Apple versions, an important consideration among my students.
  6. Java is the language used on the AP Computer Science Exams as of 2004.
In addition to these five items, Java, along with several other of the languages mentioned, equips users with a rich supply of graphical user interface (GUI) components. The use of a GUI greatly enhances the language in the eyes of many students even if it is largely beside the point in a consideration of basic computer science ideas. Finally, in specific contradistinction to C++, Java removes a lot of potholes: no pointers, no operator overloading, no multiple parameter passing techniques, and no need to explicitly reclaim (delete) dynamically allocated memory.

Java can be used to implement two distinct categories of programs: applets and applications. Java applets are intended to be loaded as part of a Web page. As such, their functionality is extremely limited by security requirements. After all, do you want Fred R. Hacker's applet to have control over your local file system? Java applications are much like any other computer programs; they generally have full access to your local system resources, and they are very network (LAN or Internet) savvy. My students work mostly with Java applications.

In the line of practical advice to beginning Java teachers, I offer a few suggestions. First, get to know Sun's Java Web site (available below in "See also"). Second, become comfortable with the Java API documentation, available online and for download in HTML format. Third, run through at least the initial parts of Sun's online Java Tutorial.

In Part II of this series, I will describe the practical side of getting a classroom up and running for Java.


Please note: Some topics covered in this series of articles are not included in the defined curriculum. Refer to the current official AP CS Course Description for the topics that will be tested on the AP Exams.


Part II

This is Part II in a series of articles designed to take a computer science teacher in the Pre-AP years through the more difficult and confusing first components of teaching computer science in Java. In Part II we discuss how to get started with the course logistics: how we prepare the machines for the course, where to find information on IDEs and textbooks, and how to compile and execute a Java program without an IDE. Additional articles will discuss designing the course structure and the role of lectures and labs, integrating student projects in the course, and evaluating student assignments and projects.

The Java Software Development Kit
Under the SDK Hood
Textbooks and References

The logistics of getting a classroom up and running in Java is surprisingly easy and inexpensive, hardware aside. My experience is with workstations running some later versions of Microsoft Windows, though this information should also be generally applicable if you work with Apple or Linux workstations.

The Java Software Development Kit
The Java language Software Development Kit (SDK) is distributed for free by its developer, Sun Microsystems (a link to this and the other sites mentioned is available in "More," below). Go to their site and download the latest SDK. This is a 38 MB zipped file. You will want the Standard Edition (J2SE 1.4.1 is current as of this writing). Versions are available for Windows and Linux machines. Apple computers offer outstanding out-of-the-box support for Java, and further information can be obtained from Apple. Installation of the software is straightforward and includes both the software development tools and the runtime software needed to execute Java applets and applications.

You will also want to download and install the documentation. It is available in a variety of formats, including Windows help file and PDF formats, but I've found the HTML version to be the easiest to use. This is a 32 MB zipped file. Install the documentation files in a subdirectory of the SDK directory. I use the default install directory for the SDK: j2sdk1.4.1_01, and I place the documentation files in a \docs subdirectory.

If you are on a network, maintain a copy of the SDK install file and documentation file so that it can easily be installed on new or upgraded workstations throughout the year. Otherwise, or perhaps additionally, burn a CD with these files. Students might also like the CDs for installing the software at home.

The main Java executable files that you will be working with are located in the j2sdk1.4.1_01\bin subdirectory. The bin is short for binary, as opposed to, say, text or source files. The binaries include javac.exe (the Java compiler that processes Java source code to Java metacode) and java.exe (the Java runtime program that interprets Java metacode into native code). It is helpful to go into the j2sdk1.4.1_01\docs\api subdirectory and drag a shortcut for the file index.html onto the desktop. This will make the API documentation readily available as you work. You will quickly find that in this very object-oriented language, the API docs are your best friend.

Under the SDK Hood
To understand the basics of the Java SDK, I've found it helpful to do some simple command-line work. You may want your students to do this as well. It seems a little masochistic, but it's nice to know some of the things those smart editors and IDEs do for you behind the scenes. Let's do this to write and run the traditional Hello World! code.
  1. Invoke a simple text editor such as Windows Notepad and enter and save the following source code (save it as the file HelloWorld.java to a near-root subdirectory so that pathnames don't get overly long). Note that Java source files must be named exactly like the name of their public class: HelloWorld in our case.

    public class HelloWorld
    { 
    		public static void main(String args[])
    		{
    			System.out.println("Hello World!");
    		}
    }
  2. Drop to a command-line prompt (Start menu: Programs/Accessories/Command Prompt in Windows XP).
  3. Navigate to the directory containing your source file. Mine is in c:\my documents\, so I type cd c:\my documents.
  4. Enter the command to compile the source code to metacode:
    c:\j2sdk1.4.1_01\bin\javac HelloWorld.java
    You may need to modify the path for your particular installation.
  5. Do a directory listing (dir Hello*.*), and you should see entries for both your Java source file (HelloWorld.java) and the Java metacode file (HelloWorld.class) created by the Java compiler. This metacode file can be executed on any platform supported by Java. That's one of the real benefits of Java: portability.
  6. To execute the metacode file, enter:
    c:\j2sdk1.4.1_01\bin\java HelloWorld
    You should see those traditional words displayed on the console.
There, that's the full, basic Java development cycle. It is a lot easier to use an intelligent "programmer's" text editor such as TextPad for source code writing and for invoking both javac.exe and java.exe. My students and I typically use a full-blown integrated development environment (IDE) to edit source code, manage files, and invoke the proper Java executables. I am particularly fond of JCreator, which is available in both free and professional versions. If you monitor the AP Computer Science electronic discussion group (EDG), you will hear about a number of other editors and IDEs. You can find direct links to various available IDEs on Debbie Carter's Java Resources for AP Computer Science Teachers Web page.

Textbooks and References
There are many good textbook and reference possibilities, and I again refer you to the AP Computer Science EDG for suggestions and guidance. AP Central's Teachers' Resource Catalog posts teacher reviews of many of the more popular introductory Java texts. These reviews link to the publishers' Web sites to provide easy access to more information about the books being reviewed. Sun's online Java Tutorial is also an excellent source of information. My computer science students use Java: How to Program, 4th ed. by Harvey Deitel and Paul Deitel. The book is out (or about to be out) in the fifth edition now. It is a large text, but I like the fact that it starts by assuming no programming experience and yet has tremendous scope for more advanced studies. I also like that its code examples are fully executable small programs; my students find this very satisfying as well. If you don't choose to use it for class, I suggest a copy for your reference bookshelf.

In Part III of this series, I will write about how you might structure a year-long computer science course in Java.


Please note: Some topics covered in this series of articles are not included in the defined curriculum. Refer to the current official AP CS Course Description for the topics that will be tested on the AP Exams.


Part III

Quarter I: Basics
Quarter II: Introduction to Data Structures and Small Applications
Quarter III: Larger Applications
Quarter IV: Special Topics

This is Part III in a series of articles designed to take a computer science teacher in the Pre-AP years through the more difficult and confusing first components of teaching computer science in Java. In Part III we discuss the design of a typical, yearlong course. Additional articles will discuss the role of lectures and lab work, the integration of student projects into the course, and the evaluation of student assignments and projects.

It is difficult to generalize about a suitable yearlong course design. Different types of schools and different collections of students will dictate course variations. However, I think it's useful to discuss a general course design from which such variations can depart as appropriate. Certainly for the beginning Java teacher, such a design would serve as a baseline for modification.

Any approach to Java has to recognize the essential object-oriented nature of the language and its emphasis on encapsulated modules (classes) of code. I feel that it is especially important for students with some introduction to programming in a less object-oriented language to quickly gain an understanding of and an appreciation for the strength of object-oriented design.

At my school, we operate on a quarter system, with nine weeks per quarter, and each class meets for 45 minutes a day, five days a week. The timing in this article assumes this sort of class structure. While this would in theory provide 180 class days, the reality is that we have about 160 class days of actual instruction time. I suspect this is not an uncommon scenario.

In teaching programming, it is especially difficult to sequence the presentation. Do you present the idea of user-defined types before primitive data types, operators, and control structures, or do you delay the higher-level discussions? An attempt must be made to lay things out as needed, yet there are some issues that need to be introduced a bit all-at-once. The course outline that follows seeks to balance some of these various objectives. In some ways, it is more scope than sequence, as each year's unique student mix inevitably forces some alterations.

Quarter I: Basics
  • Computers and computing: I begin the year with a historical overview of computing and the general nature of computer hardware and software. We also discuss some of the ethical issues surrounding computer use, especially within the context of wide area networks such as the Internet.
  • Introduction to the Java development cycle:
    • Writing source code: Here I introduce the use of a text editor (often TextPad) and, in our case, an IDE (JCreator). The general structure of *.java source files is introduced. As we develop early classes, I try to keep test classes implementing the main() method separate from our working classes. Indeed, even the Hello World application introduced in Part II can be cast as a general String display class exercised by its own, separate test class.
    • Compilation to metacode: The use of metacode to achieve a high degree of platform independence is discussed. The production of the *.class file is demonstrated.
    • Execution of metacode: Platform-specific Java virtual machines are explained. Here, metacode is used to generate native code.
    • Rewriting/debugging: In my introductory courses I avoid the use of a formal debugger environment. I think it does more to obscure than to clarify basic principles. This same argument can be made against the use of IDEs in general, and I think it's easy to dispense with their use in an introductory course in favor of a rather simple text editor. I do find keyword highlighting useful, and most programming text editors implement that. Students are introduced to the use of embedded calls to System.out.println() and other rudimentary forms of debugging. They suffice.
    • Console i/o: Java's support of console i/o is rudimentary. It is a GUI-oriented language. Calls to System.out.print() or System.out.println() are fine for console output much of the time, but console input is more problematic. Many people are making simple i/o classes available specifically for teaching. I recommend their use. See the AP Computer Science Electronic Discussion Group (EDG) for some excellent guidance.
    • Applications and applets: Java applications and applets are compared and contrasted. Students are often more interested in applets than I am. The Java3D API (which can be downloaded separately from Sun's Web site) provides a MainFrame class (com.sun.j3d.utils.applet.MainFrame) that permits applets to be displayed as applications. In any case, applets are fun, and they are especially appropriate in a Pre-AP class that does some Web authoring.
  • Introduction to object-orientation: Introduce the concept of user-defined types and require careful thinking about objects as an application is designed. The general guideline to think of object nouns as fields and object verbs as methods is helpful. It may be useful to have students begin to document their code using Sun's Javadoc facility. Personally, I find it not very useful for small applications, and it can, like IDEs, get in the way of more central issues. In any case, have students document their code briefly but effectively from the onset.
    • User-defined types: classes
      • Fields
      • Methods (including Object methods that should frequently be overridden, like the toString() method)
      • Public interface
        • Constructors
        • Other public methods
    • Reusability
    • Encapsulation
    • Data hiding
  • Primitive data types (and their wrapper classes): Many people feel that the existence of primitive data types in Java is contrary to the general principles of objected-oriented design. However, they're here, and we all use them. This is probably a good time to introduce the Java API class documentation. Students can study, for example, the documentation for class Integer to discover goodies like parseInt() and intValue(). I also usually introduce one-dimensional arrays here.
    • Integers
      • byte (class Byte)
      • short (class Short)
      • int (class Integer)
      • long (class Long)
    • Floating point numbers
      • float (class Float)
      • double (class Double)
    • Special
      • boolean (class Boolean)
      • char (class Character)
  • Operators
    • Assignment
      • =
      • +=, -=, *=, /=, %=
    • Increment and decrement
      • pre ++, pre --
      • post ++, post -
    • Grouping: ()
    • Unary +, -
    • Multiplication: *, /, %
    • Addition: +, -
    • Comparison: <, <=, >, >=, ==, !=
    • Boolean &, ^, |
    • Logical &&, ||
  • Control structures
    • if, if/else
    • while
    • for
    • switch
    • do/while
    • break, continue
  • Object-orientation details
    • Inheritance
    • Interfaces
    • Polymorphism
    • Static fields and methods
    • Java API documentation; a more extensive overview
Quarter II: Introduction to Data Structures and Small Applications
During the second quarter of the year, we study some basic data structures (arrays, lists, stacks, and queues), and we do a half-dozen small applications to exercise the language and gain some practice with class design. Whether or not you choose to do this sans GUI or choose to introduce GUIs early on or indeed at all is a matter of some considerable debate. Personally, I find event-driven GUIs fascinating, and I think that students like them as well. On the other hand, I wouldn't deal with them to the detriment of more fundamental concepts.

In any case, I introduce simple Swing GUIs pretty early on, and we cover the general concept of Java interfaces as we implement various listeners (especially ActionListener). I also introduce the Java2D API so that we can do some custom painting in conjunction with graphing applications. Through all of this, maintain a strict separation between graphical, view-related elements and nongraphical modeling elements. Nongraphical components should stand alone well.

There are many good choices for small applications: games, simulations (we've done pendulum motion and free fall, for example), database applications (biological inventory of a region), simple encryption/decryption schemes, ASCII graphics data displays, statistical analyses, and so forth.

This quarter allows students to consolidate their mastery of Java basics while tackling a variety of small-scale assignments.

Quarter III: Larger Applications
This quarter we do a cooperative project of fairly large scale. The careful design of class interfaces and project specifications is emphasized. Small groups of students are given responsibility for subsets of the project and for ultimate project integration. To facilitate testing, streams are introduced along with file i/o.

This quarter's work will be a major topic in the penultimate article of this series: the integration of student projects into the course.

Quarter IV: Special Topics
I have a lot of fun with this. We start with some basic networking, including a classwide chat system. Threads are introduced with an eye toward using at least the Timer class to facilitate some animation exercises. Some students work with Java2D, some with photographic image manipulation. Studies within the Java3D API are becoming increasingly popular as the instructor (!) becomes more familiar with this interesting tool. This year several students worked on an MP3 audio player. Networked gaming applications have also been popular.

Students leaving Pre-AP Java are well prepared for the more focused studies that comprise the AP Computer Science curricula. Most of my students go on to take AP CS AB in their senior year.


Please note: Some topics covered in this series of articles are not included in the defined curriculum. Refer to the current official AP CS Course Description for the topics that will be tested on the AP Exams.


Part IV

Handouts
Electronic Presentations
Real Lectures
Lab Work

This is Part IV in a series of articles designed to take a computer science teacher in the Pre-AP years through the more difficult and confusing first components of teaching computer science in Java. In Part IV we discuss the role of lectures and lab work. Additional articles will discuss the integration of student projects into the course and the evaluation of student assignments and projects.

I generalize the term lecture to refer to the teacher's formal organization and presentation of the course, aside from actual student program design, implementation, and testing, which I refer to as lab work. This lecture component of the course can take many forms, including handouts, electronic presentations (e.g., Web-based, PowerPoint-style, or Java applets), and actual "listen to me" lectures.

As a side note, the new USB flash "hard drives" are very useful for allowing portability of work between school and home. You can maintain JCreator workspaces, PowerPoint presentations, and so forth on the device. I've found the capability extremely useful for grading student work as well. I use a Fuji 256 MB USB Drive, but there are lots of other vendors. These devices are very small -- mine fits on a key chain. Windows XP automatically recognizes the device as a removable hard disk. Other operating systems may require driver software. If your machine supports USB 2.0, try to get a USB 2.0-compatible flash device -- they're faster.

Handouts
After the Hello World application is done using console output, we normally have a look at it using a simple GUI implementation. The Nascent Java: GUI handout below is an example of the handout that accompanies that presentation. It is implemented here as an HTML document, though it was originally distributed as a Word document. Over the years, I have found that it helps to adopt some conventions with programming handouts, much as programming authors do with their books.

Nascent Java: GUI
  • Each handout is headed with a specific topic and a subheading identifying the class. This helps with student organization and also makes it easy to refer to the handout by topic rather than as "that handout I gave you about simple GUIs."
  • I use subsection headings to allow students quick access to specific subtopics.
  • Writing is broken into small bites of information separated by blank lines. This is a holdover from my early journalism training -- large blocks of text are intimidating.
  • Keywords are boldfaced.
  • I often use hyperlinks to link to related documents, both those of my own making and others available on the Internet.
  • Programming statements are set in a nonproportional font, usually Courier New.
  • Program segments, set in Courier New, are placed in boxes to clearly define their extent.
  • I try to keep the narrative tone light. Programming is inherently ponderous enough without my encouragement!
I typically make all handouts available electronically. This makes it easier for students who are absent or who misplace handouts.

Electronic Presentations
Most of my electronic presentations are either PowerPoint-type slide shows over various topics or Java applets whose animation ability helps students follow a particular idea. In our early discussions of classes and inheritance, I use a Spacecraft class as an illustration. (A zipped PowerPoint version of the presentation is available below.) I later add an appropriate toString() method to this class that is not included in this PowerPoint presentation. This style of presentation, particularly with well-chosen images, animation, video, and sound, can both enliven a presentation and make its content clearer. A ceiling-mounted video projector makes electronic presentations very effective and easy to integrate into other class activities.

Java IV PowerPoint Presentation (.zip/119KB)

In the category of Java applets, there are a lot of possibilities. I like the idea of using Java to learn Java. I use these more in AP Computer Science, where we deal with a number of rather complicated algorithms and data structures. There are many applets for presenting ideas like recursion and binary search trees that truly help make the topics easier to understand.

I maintain a class Web site that keeps students up to date on assignments. As mentioned earlier, I also make handouts available online. Java applets and PowerPoint presentations used in class are also made available for later study on the site. Finally, I often put together self-study units of links to my own work or other Internet sites for studying particular topics (say, Monte Carlo methods).

Real Lectures
I usually introduce new concepts, at least briefly, in a lecture and discussion format. For something like a for loop, this might take five or 10 minutes. For the concept of inheritance, an entire period or two might be needed. I do try to get in and get out rather quickly. Once students have read a bit on the topic and then heard me hold forth on it for a while, they are usually ready to jump into lab and get their feet wet. I spend about 45 minutes a week in lectures, and they are usually supported, at least in part, by some sort of electronic media. Lectures are more common earlier in the year.

Lab Work
Lab work comprises the bulk of our class time, especially in the second half of the year. Students work on individual workstations equipped generally with Microsoft Windows XP and Internet Explorer, TextPad, JCreator LE, and Sun's Java SDK. Several of my students work on Linux workstations. Under my supervision, they installed double-boot systems on these machines, and they enjoy working with this alternative operating system. Several faculty members have audited the course using Apple laptops.

All workstations are connected to the school's network, and I have direct access to the computer science directories in students' network storage areas. This simplifies keeping up with what they're doing. The workstations also have high-speed Internet access and access to a classroom laser printer.

We begin the year with short, highly focused lab work: implement a class, implement a test class, or demonstrate the use of primitive data types, wrapper classes, inheritance, simple GUIs, and so forth. In the second quarter we move on to small, fully developed applications. Here, I encourage students to help one another. There will inevitably be students who are faster or more adept than others, and they often make excellent teachers. I do have to monitor this closely; help is one thing, crutching is another. It is very important to set firm deadlines for this early class work, otherwise students can get spread out all over the place. If some students finish early, I have files of additional small projects that earn them bonus credit.

In the larger, cooperative project of quarter three, deadlines are still made, but with greater flexibility. The emphasis is on various time points: design deadline, deadlines for team development, and finally a deadline for the fully integrated application.

The special topics of the fourth quarter are assessed on a portfolio basis. One student might be working on fractals, another creating a Java3D simulation of the solar system, and a pair of students developing a networked, interactive video game. Weekly assessments and daily monitoring and direction keep everyone (well, nearly everyone!) on track.

Please note: Some topics covered in this series of articles are not included in the defined curriculum. Refer to the current official AP CS Course Description for the topics that will be tested on the AP Exams.

Part V

Object-Oriented Program Design
Utilization of Developing Student Skills
Engagement of Student Interest

This is Part V in a series of articles designed to take a computer science teacher in the Pre-AP years through the more difficult and confusing first components of teaching computer science in Java. In Part V we discuss the possible role of projects in a computer science course at this level. The final article in this introductory series will discuss methods of student assessment.

In the early part of a course, it seems appropriate to limit assignments to short, focused code that illustrates a specific concept. As students get more Java under their belts (caffeine-free, of course!), longer projects become both possible and, in my opinion, generally desirable.

Longer projects may work best in smaller classes and among highly motivated students. In larger classes, which can be a lot like herding cats, shorter projects may be better suited. Likewise, if students are less motivated to stay on task without frequent deadlines, shorter projects may also be in order.

Short or long, the projects need to be designed with three goals in mind: (1) the promotion of object-oriented program design, (2) the utilization of developing student skills, and (3) the engagement of student interest.

Object-Oriented Program Design
For beginning Java teachers, this may be the most elusive of the three goals. Solid object-oriented design takes a lot of experience for mastery, a prerequisite not met by a lot of secondary computer science teachers. Having faced that head-on, it must be said that careful attention in the design stages of a project will give the work the essentials of good object orientation. That will suffice: computer science for the Pre-AP years is, after all, an introduction to an introductory course, AP Computer Science.

You might begin with a small project to illustrate the essential nature of objects: the encapsulation of both form and function (fields and methods, respectively) into a class structure. Toss in the idea of data hiding and you're off to a good start. The primary motivation behind class structure is to promote easy code maintenance and frequent code reuse. Structuring code as a group of related classes makes it easier to follow, easier to modify, and easier to reuse parts in new, often quite different programs.

Last year I used a Spacecraft class to begin:
public class Spacecraft
{
   // private, hidden fields

   private String name;   // i.e.,  USS Challenger
   private int speed;   // m/s
   private int maxSpeed;   // m/s
   private int fuel;   // L
   private int maxFuel;   // L
   private double position;  // m traveled from 
                             //start of trip (like an odometer)
	
   private final int mpL = 2000;   // fuel mileage in m/L
	
   // a constructor ================================================

   public Spacecraft(String n, int maxS, int maxF)
   {
	   name = n;
	   speed = 100;   // default speed
	   maxSpeed = maxS;
	   fuel = 1000;   // default fuel
	   maxFuel = maxF;
	   position = 0.0;
   }
	
   // get methods ==================================================
	
   public String getName()
   {
	  return name;	
   }	
	
   public int getSpeed()
   {
	   return speed;	
   }
	
   public int getMaxSpeed()
   {
	   return maxSpeed;	
   }
	
   public int getFuel()
   {
	   return fuel;	
   }
	
   public int getMaxFuel()
   {
	   return maxFuel;	
   }
	
   public double getPosition()
   {
	   return position;	
   }
	
   // set methods ==================================================
	
   public boolean setSpeed(int s)
   {	
	   boolean resultFlag = false;
	
	   if (s <= maxSpeed)
	   {
		   speed = s;	
		   resultFlag = true;
	   }
		
	   return resultFlag;
   }
	
   // some other public methods ====================================
	
   public boolean addFuel(int f)
   {
	   boolean resultFlag = false;
	
	   if ((fuel + f) < maxFuel)
	   {
		   fuel += f;	
		   resultFlag = true;
	   }
	   else
	   {
		   fuel = maxFuel;	
	   }
		
	   return resultFlag;
   }
	
   public boolean travel(int t)   // travel time in s
   {
	   boolean resultFlag = false;

	   int requestedTravel = speed * t;   // in m
	   int maxTravel = fuel * mpL;   // in m

	   if (requestedTravel < maxTravel)
	   {
		   position += requestedTravel;
		   fuel -= ((speed * t) / mpL);
		   resultFlag = true;
	    } 
	   else
	    {
		   position += maxTravel;
		   fuel = 0;
	   }
		
	   return resultFlag;
   } 
	
   public String toString()
   {
	   String s1 = " Spacecraft name: " + name + "\n";
	   String s2 = "           speed: " + speed + " m/s \n";
	   String s3 = "   maximum speed: " + maxSpeed + " m/s\n";
	   String s4 = "            fuel: " + fuel + " L \n";
	   String s5 = "    maximum fuel: " + maxFuel + " L\n";
	   String s6 = "current position: " + position +
	   " m traveled so far.";
	   return (s1 + s2 + s3 + s4 + s5 + s6);
   }
}
And here is the associated test file:
public class TestSpacecraft
{
   public static void main(String args[])
   {
	   Spacecraft sc1 = new Spacecraft("USS Challenger", 10000, 4000);
		
	   System.out.println(sc1);
		
	   if (sc1.travel(1000))
	   {
		   System.out.println("\nTravel fully successful!\n");
	   }
	   else
	   {
		   System.out.println("\nTravel not fully successful.\n");
	   }
		
	   System.out.println(sc1);
   }	
}
These two classes cover a lot of ground. Some notes:
  • The final variables cannot be given a new value; they're essentially constants.
  • The get and set methods provide read and write access to private fields.
  • Most classes implement a toString()method that overrides the simple one inherited from Object (all Java classes are descendants of class Object).
  • TestSpacecraft's only method is static; this means that it can be used without creating an instance of the enclosing class; in this case, the Java Virtual Machine invokes main() without creating any instance of class TestSpacecraft.
We go on to play around by creating several instances of Spacecraft and then extending the class to introduce inheritance:
public class SuperSpacecraft extends Spacecraft
{
   // private, hidden fields
	
   private int photonTorpedoes;   // count
   private int phaserMegaJoules;   // in MJ

   // a constructor ================================================

   public SuperSpacecraft(String n, int maxS, int maxF,
   int torps, int phaserCharge)
   {
	   super(n, maxS, maxF);
		
	   photonTorpedoes = torps;
	   phaserMegaJoules = phaserCharge;	
   }	
	
   // get methods ==================================================
	
   public int getTorpedoes()
   {
	   return photonTorpedoes;
   }
	
   public int getPhaserCharge()
   {
	   return phaserMegaJoules;	
   }

   // some other public methods ====================================

   public void addTorpedoes(int t)
   {
	   photonTorpedoes += t;
   }
	
   public void addCharge(int c)
   {
	   phaserMegaJoules += c;	
   }
	
   public boolean firePhotonTorpedoes(int t)
   {
      // implementation here
	  
	  return true;
   }
	
   public boolean firePhasers(int p)
   {
	   // implementation here	
		
	   return true;
   }
	
   public String toString()
   {
	   String s1 = super.toString();
	   String s2 = "\n     photo torps: " + photonTorpedoes + "\n";
	   String s3 = "   phaser charge: " + phaserMegaJoules + " MJ\n";
	   return (s1 + s2 + s3);
   }
}

And here is the associated test file:

public class TestSuperSpacecraft
{
   public static void main(String args[])
   {   
	   Spacecraft craft[] = new Spacecraft[10];
		
	   for (int index = 0; index < 10; index += 2)
	   {
		   craft[index] = new Spacecraft("USS Enterprise " +
		   index, 5000, 12000);
		   craft[index + 1] = new SuperSpacecraft("USS Voyager " +
		   index, 5000, 12000, 50, 4525);
	   }
		
	   for (int index = 0; index < 10; index ++)
	   {
	   	   System.out.println("Craft " + index + "\n:"
		   + craft[index].toString() + "\n==========\n");
	   }
		
   }	
}
Some notes:
  • There's a superclass call in the constructor and in the toString() method.
  • The test file uses arrays and introduces polymorphism by using references to Spacecraft objects to refer to both Spacecraft and SuperSpacecraft objects.
After the various spacecraft are up and running, students are encouraged to use them in creative ways: some set up races using random travels, while others fashion games by adding old-fashioned "adventure-type" gaming commands. Some students extend travel to three dimensions and add planets and so forth. This is a good prelude to the AP Marine Biology Case Study.

After a series of small projects like this, students generally have made their way through most Java basics. Some additional topics for these small projects include simulations (we do one on simple harmonic motion and one on projectile motion), statistical analyses, probability simulations (rolling dice, card games), databases, simple text encryption/decryption, text analysis (e.g., "Did Shakespeare write this?"), and many others. The AP Computer Science Electronic Discussion Group is a great source for more inspiration.

As the year progresses and language basics are mastered, you can move on to more complex projects. I suggest at least one project in which portions are divvied up among several students. This enforces the need for clear design goals and well-communicated public interface specifications. Ideally, each student would have the responsibility to code one or several classes making up the project. Students are responsible for integration and testing the final application.

Utilization of Developing Student Skills
It is important that all assignments, including medium and large projects, key on developing student skills, especially early in the learning curve. As students master most of the basics of Java, more integrated projects become possible.

I make a list of skills that I would like to emphasize with each project. Some of these are design skills, some are language skills, and some are more algorithmic or problem-solving skills. Then I lay out the project and inventory the skills necessary to complete it. I compare the skills required to those taught and either do some more teaching or modify the project if the skill lists do not match. This sort of project assessment is crucial to the design of high-quality student projects.

Engagement of Student Interest
This can be a challenging one. Early on, code that deals with interesting scenarios like spacecraft can be helpful. Later in the course, I think it's important to introduce graphical user interfaces. Students expect applications to be GUIs, and rightly so. I also think it's important to let advanced or "gifted and talented" students investigate more sophisticated aspects of Java, including such topics as images, sound, networking, and Java3D. Through all of this, it's important to stay focused on the essentials of good program design. Teaching linked lists in the context of an MP3 player is a lot more interesting to students than using some arbitrary data. Java3D is based on a tree-traversal rendering model, and the advanced use of tree data structures can be studied in this context. Networking and animation provide good platforms for discussing the importance of multithreaded code. Art-oriented students will like playing with Java2D and Java3D; there's room for lots of didactic fun in those APIs. Enjoy!


Please note: Some topics covered in this series of articles are not included in the defined curriculum. Refer to the current official AP CS Course Description for the topics that will be tested on the AP Exams.


Part VI

Quizzes
Short Code Assignments
Projects
Examinations


This is Part VI in a series of articles designed to take a computer science teacher in the Pre-AP years through the more difficult and confusing first components of teaching computer science in Java. In Part VI we discuss the evaluation of student assignments and projects.

The evaluation of student work is one of the more time-consuming and less rewarding parts of teaching for me. While I enjoy working with my students, guiding their efforts, I don't enjoy the more formal evaluation process known, albeit somewhat pejoratively, as "grading." Indeed, I'm inclined to launch off on a sort of heretical and ultimately dismissive essay on the subject.

However, the need for evaluation cannot be dismissed, either practically or even, truth be told, ideally. However, in a programming class, efforts can be made to make the evaluations focused, meaningful, and yet not overly laborious. My evaluations tend to fall into four distinct categories: multiple-choice quizzes, short code assignments, programming projects, and large-scale examinations. Let's have a look at each of these in turn.

Quizzes
The beauty of multiple-choice quizzes is that they are focused and easy to grade. However, the thoughtful production of the quiz can take quite a while. Avoid the temptation to provide one right answer and several junk answers. It's important to the evaluative strength of the quiz to provide attractive wrong answers, and even to my devious mind, this can be a challenge. Often, the "answers" are substantial segments of code rather than only one or a few statements.

Short Code Assignments
This category would include assignments that involve designing classes and perhaps implementing some specific methods within classes. In an effort to focus student attention on one or only a few specific programming tasks, I try to take a lesson from some of my English teacher colleagues. In their writing classes, assignments are classified to focus students on particular tasks: for example, a certain type of paper might only be scored for overall organization, with little attention being paid to spelling or grammar, while another paper may be evaluated primarily for sentence structure, grammar, and spelling with little attention to higher-order affairs.

In programming, a short code assignment might call for a demonstration of method overloading, class inheritance, or perhaps a display of simple recursion. It might be a demonstration of the proper use of certain loops or logical evaluations. In any case, the merits of good focus are in easy evaluation and quick feedback for the student aimed at specific aspects of programming. It's a win-win strategy.

Projects
Projects are very difficult to evaluate bit-by-bit on a 100-point scale. Even if it were desirable, one is apt to miss the forest for the trees by taking such an approach. I think a portfolio approach is easier and more useful to the student. As each project is begun, students keep a project journal in a loose-leaf binder. All papers relating to the project are kept there in chronological order, including hard copies of source code. As the project proceeds, I make written comments in the journals on a regular basis as I "work the room" during class. For larger classes, it might be better to take up the journals for comment writing. I try to make only two or three comments at each cycle. Again, I think that a clear focus is essential for beginning programmers.

Students know ahead of time that I will evaluate their projects in distinct areas -- typically design, general coding quality, and finally implementation "success." The weighting for these areas is usually something like 50 percent, 30 percent, and 20 percent, respectively. I place a high premium on thoughtful design and a lower emphasis on producing code that runs exactly to specs. Students can score a B on a project with good planning and generally strong coding skills even if a small logic error causes the program not to execute quite right. Project grades run from 1 to 5, roughly equivalent to the F, D, C, B, A scale.

Examinations
I give examinations that mirror the general multiple-choice plus free-response style of the AP Computer Science Exams. The multiple-choice section is generally a reworked collection from past quizzes, and the free-response section typically consists of short code assignments that build on similar class assignments during the quarter. By following this format, students simply extend their experience with normal term quizzes and short coding assignments. Nothing about the exams is very new, and so the process isn't too intimidating. Major exams are given about every three weeks, and they usually take two days (1.5 hours) to complete.

A student's quarter grade is generally calculated by taking 25 percent each from quizzes, short code assignments, projects, and major exams. In the latter part of the year when projects grow larger and begin to crowd out exams, I adjust the scheme to take into account the greater emphasis on project work.

For beginning teachers, I suggest that if you have to limit time on some aspect of the course, take it out of grading and not out of class preparation. Do more multiple-choice work, and let coding be guided more by in-class feedback and less by formal evaluation. If you do yourself in trying to grade too much work, and you are ill-prepared to teach class, you will be doing your students a disservice. In my experience students benefit more from a well-prepared teacher at their side than from a constant stream of (often hastily) graded work.


Please note: Some topics covered in this series of articles are not included in the defined curriculum. Refer to the current official AP CS Course Description for the topics that will be tested on the AP Exams.

James Aldridge, Ph.D., is a science and computer science teacher at Fort Worth Country Day School in Fort Worth, Texas. He has taught computer programming for 10 years and currently teaches AP Computer Science using Scheme, Java, and C++. James also teaches AP Chemistry and has special computer science interests in the area of real time data acquisition and control subsystem hardware and software design.



  ABOUT MY AP CENTRAL
    Course and Email Newsletter Preferences
  AP COURSES AND EXAMS
    Course Home Pages
    Course Descriptions
    The Course Audit
    Sample Syllabi
    Teachers' Resources
    Exam Calendar and Fees
    Exam Questions
    FAQs
  PRE-AP
    Teachers' Corner
    Workshops
  AP COMMUNITY
    About Electronic Discussion Groups
    Become an AP Exam Reader

Back to top