How the Java visualizer in Python Tutor can help your AP Computer Science A class

Summary: This article is meant for teachers of AP Computer Science A. Python Tutor is a free website that draws step-by-step visualizations of code as it runs. Despite its name, it works well for Java and covers nearly all concepts in AP CS A: objects and references, method calls, ArrayLists, 2D arrays, searching, sorting, and recursion. The Java visualizer will always remain free to use.

Read first: one-page quick-start guide for teachers


tl;dr -- check out our new experimental apcsjava.com site for more AP CS Java materials.

Python Tutor is a free tool that has been used by tens of millions of people since 2010 to visualize and debug code step-by-step. Despite its name, it also works well for Java. If you teach AP Computer Science A, consider using it and showing it to your students.

The official Course and Exam Description (CED) directs students to hand-trace code execution step-by-step. Analyze Code questions make up the largest share of the multiple-choice section. The Java visualizer is an automatic code tracer so it can serve as an unlimited supply of worked examples for students to check their hand-traces against.

If you think it may be helpful for your students, please share this direct link in relevant course materials, chat groups, mailing lists, or discussion forums:

The rest of this article walks through the four units of the new AP CS A framework and shows what the Java visualizer can illustrate in each one. All examples below are live: drag the slider under each one to step forward and back through execution, and click "Edit Code" under any example to modify it.

These topics are just a sample: the visualizer handles nearly every topic in AP CS A. Many that don't have their own section here – conditionals, for loops, constructors, scope, the this keyword – are already shown running inside the examples below.

Lastly, How the Python Tutor visualizer can help students in your Java programming courses covers more Java features outside of AP such as inheritance and polymorphism.

Unit 1: Using Objects and Methods

Objects, references, and aliasing

This unit starts with primitive types, expressions, and calling Math and String methods, then hits the first big conceptual wall of the course: objects and references. The Java visualizer pictures references directly: primitive values (int, double, boolean) appear inline inside stack frames, while objects appear in a separate heap area with arrows pointing to them.

In this example, small and big each point to their own Circle object, and alias points to the same object as big. Stepping thru each constructor shows how radius starts at a default of 0.0 then gets assigned to. At Step 12 (shown above) the frame for the alias.grow() method call points to the same Circle that big points to, which sets radius to 15.0. That's why the call to big.getRadius() at Step 15 also returns 15.0.

Strings and immutability

Strings get an entire topic and show up every year in the free-response section, so here is a small example:

Students can watch str2 get built up by substring calls while str1 never changes, since Strings are immutable and every String method returns a new string. (By default the tool displays strings inline to reduce visual clutter. Select the "show Strings and wrappers (e.g., Integer) as objects" option to render them as objects with arrows pointing to them.)

Integer division, casts, and overflow

The visualizer can also clarify issues with primitive values such as integer division truncating, casts like (int)(q / r), and Integer.MAX_VALUE overflow wrapping around to a negative number.

Unit 2: Selection and Iteration

String algorithms with while loops

For this unit, the CED suggests having students keep trace tables. The Java visualizer works like a self-updating trace table, since every live variable is on-screen at every step. Here is one of the CED's standard string algorithms, reversing a string with a while loop:

At the current step, i is 2 and reversed has just grown to "CPA". Unlike with print statements, the visualizer shows the loop condition, accumulator pattern, and final result as they get computed step by step.

Nested loops and execution counts

Nested loops can get trickier for students. The example below prints a triangle of numbers:

The print statement outputs accumulate as the steps progress in the visualizer, so students see exactly when each row ends and why the inner loop condition k < j shrinks each time around.

Unit 3: Class Creation

Writing a class: the Class Design FRQ

This unit is where students go from using classes to writing them. The example below is adapted from the sample Class Design FRQ in the CED, where students implement a CupcakeMachine class from a specification table:

The main() method runs a shortened version of the sample execution sequence. At Step 13 (shown above) takeOrder is running: availCupcakes has already dropped from 10 to 8, and message was just rebuilt from "Order cannot be filled" to the real order confirmation. Note that the method's frame contains a this reference pointing at c1's object.

Class (static) variables vs. instance variables

Class (static) variables get their own display area. For instance:

The static variable displays as RaffleTicket.totalSold in its own area. At this step the third ticket is being constructed: totalSold has already incremented to 3, but serialNum is still 0.

Unit 4: Data Collections

This is the biggest unit, and two of the four free-response questions draw directly from it.

ArrayList basics: add, set, and remove

Let's start with ArrayList:

The step shown is right after playlist.add(1, "Cruel Summer") executed: the element that was at index 1 has been shifted right to make room. Step forward, and set replaces an element without shifting, while remove(0) shifts everything left. (Along with ArrayList, other java.util collections such as HashMap and HashSet can also be visualized if your students want to go beyond AP exam material. Things like ArrayList<Integer> also work, since autoboxing happens automatically, and each Integer displays differently than primitive int values.)

The Data Analysis with ArrayList FRQ

The Data Analysis with ArrayList FRQ always involves an ArrayList of objects, so here is the CED's own sample question: averageWithinRange must average the cost of available items whose cost falls in an inclusive range:

The enhanced for loop variable it points at the current ItemInfo object as the loop walks down the list. Here at Step 63 it points to the $40 watch and isAvailable() is about to return false to skip it. If you step forward you'll see how sum and count stay unchanged here, then the method returns 25.0.

2D arrays and row-major traversal

This example searches a seating chart in row-major order:

Depending on the display mode, the 2D array renders either as a compact [row][col] grid or as separate row arrays with arrows pointing to them. The AP exam shows 2D arrays in their conceptual form like a 2D grid, but the arrow pointer view more closely resembles what Java actually does (since a 2D array is an array of arrays). Users can toggle the "show array-of-arrays as 2D array" checkbox below the code editor to switch between these views.

Tracing recursion

Recursion is now only on the multiple-choice section, so students never need to write recursive code. Here's an example in that style:

Here at Step 8 four frames of mystery are on the stack, each holding its own copies of j and k. Step forward to watch recursion unwind and the program print 4 6 8 10.

Sorting algorithms

This is a selection sort implementation. What does the array contain after three runs of the outer loop?

Drag the slider to Step 68 and read the answer off the screen: {10, 20, 30, 60, 40, 50} – the first three positions are locked in sorted order while the rest remain shuffled. (Insertion sort and merge sort can be visualized in similar ways.)

Recursive binary search

Each recursive call narrows the range of lo and hi. Since every frame shows its own copies of them, students can see how this algorithm eliminates half of the array during each call until the element is found.

Run-time errors and off-by-one bugs

Off-by-one errors are especially common in student code:

The loop condition uses <= when it should've been <. The program prints 5, 10, and 15 fine, then throws an ArrayIndexOutOfBoundsException at i == 3. Note that the visualizer shows the exception at the exact step it happens with the value of i on screen so students can see the cause.

AP topics that the visualizer does not cover

Help spread the word!

The Java visualizer in Python Tutor can help your AP Computer Science A students practice many of the skills that the exam tests. Please share this direct link in relevant course materials, chat groups, mailing lists, discussion forums, social media, or anywhere else: