1.02 Variables and Data Types
Declare and initialize variables with Java's primitive types, and pick the right type so values like averages keep their decimals.
1. Reference Guide
| Term | Definition / Example | College Board Requirement |
|---|---|---|
| Variable | Named storage location in memory for data: int age = 16; |
Unit 1, Topic 1.2, 1.2.B.2, p. 32 |
| Declaration | Creating a variable with a type: double price; |
Unit 1, Topic 1.2, 1.2.B.2, p. 32 |
| Initialization | Giving the variable a value at creation: double price = 4.99; |
Unit 1, Topic 1.4, 1.4.A.2, p. 35 |
| Assignment | Giving a value later (after declaration): price = 5.99; |
Unit 1, Topic 1.4, 1.4.A.2, p. 35 |
| Primitive type | Basic data types built into Java: int, double, boolean, char |
Unit 1, Topic 1.2, 1.2.A.1 and 1.2.B.1, p. 32. char is outside the AP CSA exam subset. |
| Reference type | Points to objects (more complex): String, Scanner |
Unit 1, Topic 1.2, 1.2.A.1, p. 32 |
- Primitive types don’t have methods
- Reference types are objects and have methods associated with them
College Board Requirements
AP CSA Unit 1, Topic 1.2 Variables and Data Types. Quoted from the course and exam description (College Board, 2025, p. 32):
- 1.2.A.1 “A data type is a set of values and a corresponding set of operations on those values. Data types can be categorized as either primitive or reference.”
- 1.2.B.1 “The three primitive data types used in this course are int, double, and boolean. An int value is an integer. A double value is a real number. A boolean value is either true or false.”
- 1.2.B.2 “A variable is a storage location that holds a value, which can change while the program is running. Every variable has a name and an associated data type.”
The College Board also says char is “outside the scope of the AP Computer Science A course and exam” (College Board, 2025, p. 32). This lesson still uses it because it is handy in real code, but it will not be on the exam.
Reference: College Board, AP Computer Science A Course and Exam Description (2025), Unit 1, Topics 1.2 and 1.4, pp. 32 and 35.
2. Real-Life Application
When the Wrong Type Breaks the Real World
A Java int can only hold numbers up to 2,147,483,647. In 2014, the music video “Gangnam Style” got close enough to that number that YouTube had to upgrade its view counter to a bigger type. Picking a type is not just homework: it decides what values your data can ever hold. Everyone pick one piece of data on your phone right now (a step count, a contact, a battery level) and decide its type before you read the table!
| Real Case | The Data | What Went Wrong | The Type That Fits |
|---|---|---|---|
| YouTube view counter (2014) | Views on one video | Close to the largest value a 32-bit int can hold |
A bigger whole-number type (long, not on the AP exam) |
| ZIP codes in spreadsheets | 02134 |
Stored as a number, the leading zero disappears and it becomes 2134 |
String: you never do math on a ZIP code |
| Gene names in Excel (renamed in 2020) | SEPT1, MARCH1 |
Spreadsheets turned them into dates, so scientists renamed the genes SEPTIN1 and MARCHF1 |
String: it is a name, not a date |
| A grade average | 87.33 |
Stored as an int, it becomes 87 |
double |
The takeaway: ask “what values go in, and what will I do with them?” before you pick int, double, boolean, or String.
3. Tech Talk
Learning Objective: Pick the best data type for a piece of information and declare, initialize, and assign variables correctly.
Success Criteria: You can choose a type from what the data means, use final for values that never change, and explain the difference between primitive and reference types.
A variable is a labeled box that holds a value. Every variable has a name and a type.
Pick the type by asking two things: what values go in, and what will I do with them?
int siblings = 2; // whole numbers you count
double gpa = 3.75; // decimals you average
boolean isHungry = true; // only true or false
String name = "Alex"; // text you display
final int DAYS_IN_YEAR = 365; // never changes
Java Data Types
| Type | Meaning | Example | Notes |
|---|---|---|---|
int |
Whole numbers | int year = 2025; |
Range: about -2 billion → 2 billion |
double |
Decimal numbers | double price = 4.99; |
More precise than float |
boolean |
True/False | boolean done = false; |
Used for conditions |
char |
Single character | char grade = 'A'; |
Always single quotes |
String |
Text (sequence of chars) | String name = "Paul"; |
Not primitive (it’s a class) |
This lesson only stores and prints values inside small standalone classes. Nothing is read from outside the program; input comes in lesson 1.4.
Code Examples
A. Variable basics. The VariableBasics class is defined to Declare, Assign, Print sample variables
Three steps get mixed up a lot:
int number; // declaration: makes the box
number = 10; // assignment: puts a value in
int age = 16; // a declaration with initialization: both at once
Terminology:
int, double, and boolean are primitive: they hold the value itself and can never be null. String is a reference type: it points at an object, so it can be null.
Code Runner Challenge
Run it, then change a value and predict the new output
View IPYNB Source
// CODE_RUNNER: Run it, then change a value and predict the new output
// Simple Variable Examples
public class VariableBasics {
// Step 1: Declare variables (create empty boxes)
String name;
int age;
double gpa;
boolean isStudent;
// Step 2: Make a method to print the values of the variables
void printVariables() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("GPA: " + gpa);
System.out.println("Is student: " + isStudent);
}
public static void main(String[] args) {
// Step 3: Create an instance of the class to access instance variables
VariableBasics basics = new VariableBasics();
// Step 4: Print initial values of the variables
System.out.println("Initial values:");
basics.printVariables();
System.out.println("-------------------");
// Step 5: Put values in the declared variable boxes
basics.name = "Alex";
basics.age = 16;
basics.gpa = 3.77;
basics.isStudent = true;
// Step 6: Print the values
System.out.println("Updated values:");
basics.printVariables();
}
}
VariableBasics.main(null);
B. Variable comparison. The TypeComparison class shows the difference between Primitive and Reference
Common comparison mistake:
number1 == number2 // primitives use ==
string1.equals(string2) // string uses .equals
Terminology:
Primitives hold the value. References point at an object, so they either contain an address, or they default to null.
Code Runner Challenge
Run it, then try int emptyNumber = null; and see what the compiler says
View IPYNB Source
// CODE_RUNNER: Run it, then try int emptyNumber = null; and see what the compiler says
// Simple vs Fancy Variable Types
public class TypeComparison {
// Simple types (primitives) - store the actual value
int number1 = 5;
int number2 = 5;
// Fancy types (reference) - more complex
String word1 = "Hello";
String word2 = "Hello";
// String can be empty (null), but int cannot
String emptyText = null;
// This would cause an error:
// int emptyNumber = null; // NOT ALLOWED!
public static void main(String[] args) {
TypeComparison types = new TypeComparison();
System.out.println("Same number? " + (types.number1 == types.number2)); // true
System.out.println("Same word? " + types.word1.equals(types.word2)); // true
System.out.println("Empty text: " + types.emptyText);
}
}
TypeComparison.main(null);
Hacks & Practice Tasks
Lesson: CSA 1.2 Variables and Data Types
MCQ 1.2: <paste the copied result line, such as 3/4 | answers: A,C,B,A>
Popcorn: six variables declared (String, int, double, boolean, char, final int), runs and prints (yes/no); values = <your six values>; prediction for height 5 = <your prediction>
Homework Hack 1: final student name and final class name, three int scores, check prints true (yes/no)
Homework Hack 2: average printed = <value>, both checks print true (yes/no)
Homework Hack 3: average = <value>, letter grade = <letter>, all three checks print true (yes/no)
Submission Safety Rules (Read First)
- One class per cell, ending with
ClassName.main(null);. - Run each cell and leave the output showing.
- Use your own values, not the sample answer.
- Include your MCQ score.
- Use
##headings or smaller. - Do not use a real classmate’s name or grades.
Popcorn Hack (In-Class)
2-minute challenge: make variables for your favorite things, then run the cell.
- Favorite food (text)
- Your age (whole number)
- Your height in feet (decimal)
- Do you like pizza? (true or false)
- First letter of your favorite color
- Your birth year (this never changes, so which keyword do you add?)
- Answer the question in the Popcorn checker under the runner before you run. When every check passes, copy its line into your submission notes
Replace the sample values with your own.
Code Runner Challenge
Replace the sample values with your own, then run it
View IPYNB Source
// CODE_RUNNER: Replace the sample values with your own, then run it
// Practice #1 - Try it yourself first!
public class MyFavoriteThings {
// Try writing your own code here first!
// Sample answer:
String favoriteFood = "Pizza";
int myAge = 16;
double heightInFeet = 5.5;
boolean likesPizza = true;
char colorFirstLetter = 'B'; // Blue
final int BIRTH_YEAR = 2008; // Never changes
public static void main(String[] args) {
MyFavoriteThings me = new MyFavoriteThings();
System.out.println("Favorite food: " + me.favoriteFood);
System.out.println("Age: " + me.myAge);
System.out.println("Height: " + me.heightInFeet + " feet");
System.out.println("Likes pizza: " + me.likesPizza);
System.out.println("Favorite color starts with: " + me.colorFirstLetter);
System.out.println("Born in: " + me.BIRTH_YEAR);
}
}
MyFavoriteThings.main(null);
Before you press Run, predict this output.
4. MCQ Check
4 questions, one at a time. Answer, check, then go to the next one. At the end, copy the score line into your submission notes.
5. Homework Hack
Task: Build a grade calculator one piece at a time. Store the student’s name and the class name in final variables, store three test scores as int, then print the average and the letter grade. Each starter compiles before you edit it, so you can run the initial version and compare its incorrect output with the expected output. Change only what the TODO asks for, and keep going until every check prints true.
Solution Skeleton:
Hack 1: Pick the Right Types (5 minutes)
Variables and data types. Add final to the student name and the class name, and use your own name. Then change the three test scores from String to int. While the scores are text, + joins them into 809092; as int values, + adds them to 262.
Code Runner Challenge
Fix the types so the check prints true.
View IPYNB Source
// CODE_RUNNER: Fix the types so the check prints true.
public class StudentInfoHack {
// TODO: add final so these two values can never change, and use your own name.
String STUDENT_NAME = "Your Name";
String CLASS_NAME = "AP CSA";
// TODO: these scores are stored as text. Store them as whole numbers instead.
String test1 = "80";
String test2 = "90";
String test3 = "92";
public static void main(String[] args) {
StudentInfoHack info = new StudentInfoHack();
System.out.println(info.STUDENT_NAME + " in " + info.CLASS_NAME);
// After you add final, this line must NOT compile. Try it, then comment it out again.
// info.CLASS_NAME = "Some other class";
// + joins Strings but adds ints, so the total only reads "262" once the type is right.
String total = "" + (info.test1 + info.test2 + info.test3);
System.out.println("Total: " + total);
System.out.println(total.equals("262"));
}
}
StudentInfoHack.main(null);
Hack 2: Average Without Losing Decimals (5 minutes)
Expressions and types. Replace 0.0 with the average of the three scores. Dividing two int values drops the decimals, so the first check stays false until your math keeps them.
Code Runner Challenge
Replace 0.0 with the average so both checks print true.
View IPYNB Source
// CODE_RUNNER: Replace 0.0 with the average so both checks print true.
public class AverageHack {
int test1 = 80;
int test2 = 90;
int test3 = 92;
// TODO: average the three scores. Keep the decimals.
double average = 0.0;
public static void main(String[] args) {
AverageHack scores = new AverageHack();
System.out.println("Average: " + scores.average);
System.out.println(scores.average > 87.3);
System.out.println(scores.average < 87.4);
}
}
AverageHack.main(null);
Hack 3: Letter Grade (5 minutes)
Combined. Put the pieces together: copy your average from Hack 2, then finish letterFor so it returns the letter grade (90 = A, 80 = B, 70 = C, 60 = D, else F). The extra checks try other averages, so the letter has to be worked out, not typed in.
Code Runner Challenge
Copy in your average, then finish letterFor so all three checks print true.
View IPYNB Source
// CODE_RUNNER: Copy in your average, then finish letterFor so all three checks print true.
public class GradeCalculator {
final String STUDENT_NAME = "Your Name";
final String CLASS_NAME = "AP CSA";
// 1. Three test scores as whole numbers
int test1 = 80;
int test2 = 90;
int test3 = 92;
// 2. TODO: copy your average from Hack 2
double average = 0.0;
// 3. Pick the letter grade (90 = A, 80 = B, 70 = C, 60 = D, else F)
String grade = letterFor(average);
static String letterFor(double average) {
// TODO: return the letter for this average.
return "?";
}
public static void main(String[] args) {
GradeCalculator calculator = new GradeCalculator();
System.out.println(calculator.STUDENT_NAME + " in " + calculator.CLASS_NAME);
System.out.println("Average: " + calculator.average);
System.out.println("Grade: " + calculator.grade);
System.out.println(calculator.grade.equals("B"));
System.out.println(letterFor(95.0).equals("A"));
System.out.println(letterFor(59.9).equals("F"));
}
}
GradeCalculator.main(null);
Grading Plan (1 Point Total)
| Part | Points | What earns the points |
|---|---|---|
| Popcorn | 0.2 | Six variables with fitting types, including a final birth year, and the cell runs. The Popcorn checker line is in the notes. |
| MCQ | 0.2 | 4 correct. 0.15 for 2 or 3, 0.1 if every question was answered. |
| Homework Hack 1 | 0.15 | Student name and class name stored in final variables, three test scores stored as int, and the check prints true. |
| Homework Hack 2 | 0.2 | Average of the three scores keeps its decimals and both checks print true. |
| Homework Hack 3 | 0.25 | Average copied from Hack 2, letterFor returns the right letter for any average, and all three checks print true. |
| Total | 1.0 |
Quick Validation Checklist
- Each cell ends with
ClassName.main(null);and shows output. - Popcorn checker line in the notes.
- MCQ score in the notes.
finalon the birth year and on both names.- Every homework check prints
true.
6. LxD Cycle Process
Empathize: Students pick a type by how the data looks, not by what they will do with it, so phone numbers become ints and averages lose their decimals. Interviews with first-year students found misconceptions about memory and about what happens when a primitive is declared (Kaczmarczyk et al., 2010).
Define:
- POV: CSA students need to choose a type from what the data means, because the type decides what values fit and what you can do with them, and a wrong choice spreads through the whole program.
- Learning Goal: Students will declare variables with int, double, boolean, and String, use final for values that never change, and say why String is a reference type.
Ideate:
- HMW Question: How might we get students to ask “what will I do with this value?” before they pick a type?
- HMW Question: How might we show that an int or boolean can never be null, but a String can?
- Activity: Make variables for your own favorite things, choose types for everyday data in the MCQ, then build a small grade calculator.
Prototype:
- A reference guide, runnable Java examples, personalized variable practice, an MCQ knowledge check, three scaffolded grade-calculator hacks with self-checking output, and a grading rubric.
- Students revise variable declarations after seeing compiler output or feedback.
- Excellence means explaining why each type fits the data, using
finalappropriately, and improving the first attempt rather than only producing working code.
Test:
- Ask peers in peer review to complete the practice without additional explanation.
- Observe whether peers choose types based on meaning and intended operations.
- Compare your lesson with another that is posted.
- Use the findings to revise any instruction or rubric criterion that did not guide students clearly.
- On submission, collect evidence from runner output, MCQ results, AI grading and student explanations.
- After teaching, grading and analysis, come back and revise lesson to complete teaching cycle for continuous improvement.
7. References/Citations
College Board. (2025). AP Computer Science A course and exam description [Effective fall 2025]. https://apcentral.collegeboard.org/media/pdf/ap-computer-science-a-course-and-exam-description-effective-fall-2025.pdf
Kaczmarczyk, L. C., Petrick, E. R., East, J. P., & Herman, G. L. (2010). Identifying student misconceptions of programming. In Proceedings of the 41st ACM Technical Symposium on Computer Science Education (pp. 107–111). Association for Computing Machinery.
Submit Assignment
Rate the lesson during class in the 💬 Microblog panel's Ratings tab. Anything you skipped there is finished here.
Need to update a submission later? Open the submissions dashboard.