Skip to the content.

Variables and Data Types

AP CSA Lesson 1.2 – Variables and Data Types


Learning Objectives

  • Understand what variables are and how they store data in memory.
  • Learn the main primitive data types in Java (int, double, boolean, char).
  • Differentiate between primitive types and reference types (like String).
  • Practice declaring, assigning, and using variables.
  • Gain hands-on experience with code demos, popcorn hacks, and homework challenges.

Key Vocabulary


Term Definition Example
Variable Named storage location in memory for data. int age = 16;
Declaration Creating a variable with a type. double price;
Initialization Giving the variable a value at creation. double price = 4.99;
Assignment Giving a value later (after declaration). price = 5.99;
Primitive type Basic data types built into Java. int, double, boolean, char
Reference type Points to objects (more complex). String, Scanner
  • Primitive types don’t have methods
  • Reference types are objects and have methods associated with them

Concept Overview

What is a Variable?

Think of a variable as a labeled container that stores data.

  • You can store numbers, text, or true/false values.
  • Java requires you to specify the type (what kind of data goes in the box).

Java Data Types (AP CSA Focus)

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)

Declaration vs Initialization vs Assignment

int number;           // declaration (creates variable)
number = 10;          // assignment (stores 10 later)
int age = 16;         // initialization (declaration + assignment)

// Simple Variable Examples
public class VariableBasics {
    public static void main(String[] args) {
        // Step 1: Declare variables (create empty boxes)
        int age;
        double price;
        
        // Step 2: Put values in the boxes
        age = 16;
        price = 4.99;
        
        // Step 3: Create and fill boxes at the same time
        String name = "Alex";
        boolean isStudent = true;
        
        // Print the values
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Price: $" + price);
        System.out.println("Is student: " + isStudent);
    }
}

Final Variables (They Never Change!)

Sometimes you want a variable that never changes. Use the word final.

Rules:

  • Use final at the beginning
  • Give it a value
// Final Variables - Values That Never Change
public class FinalVariables {
    public static void main(String[] args) {
        // These values will NEVER change
        final int MAX_STUDENTS = 30;
        final double TAX_RATE = 0.08;
        final String SCHOOL = "My High School";
        
        System.out.println("Maximum students: " + MAX_STUDENTS);
        System.out.println("Tax rate: " + TAX_RATE);
        System.out.println("School: " + SCHOOL);
        
        MAX_STUDENTS = 25; // ERROR! Can't change final variables
    }
}

|           MAX_STUDENTS = 25; // ERROR! Can't change final variables

cannot assign a value to final variable MAX_STUDENTS

How to Pick the Right Type

It’s like choosing the right size box for different things:

For Numbers:

  • Whole numbers (1, 2, 100) → use int
  • Decimal numbers (1.5, 3.14) → use double

For Words and Letters:

  • One letter (‘A’, ‘B’) → use char
  • Words or sentences → use String

For Yes/No Questions:

  • True or False → use boolean
// Picking the Right Data Type
public class DataTypeExamples {
    public static void main(String[] args) {
        // Student info - pick the best type for each
        String studentName = "Sarah";        // Words → String
        int grade = 10;                     // Whole number → int
        double gpa = 3.8;                   // Decimal → double
        char team = 'A';                    // One letter → char
        boolean hasPhone = true;            // Yes/No → boolean
        
        // More examples
        int numberOfPets = 2;               // Counting → int
        double temperature = 72.5;          // Decimal → double
        boolean isRaining = false;          // True/False → boolean
        
        System.out.println(studentName + " is in grade " + grade);
        System.out.println("GPA: " + gpa + ", Team: " + team);
        System.out.println("Has phone: " + hasPhone);
        System.out.println("Pets: " + numberOfPets);
        System.out.println("Temperature: " + temperature + "°F");
    }
}


Two Types of Variables

Primitive Types (Simple boxes):

  • Store the actual value
  • Basic types: int, double, boolean, char
  • Can’t be null (empty)

Reference Types (Fancy boxes):

  • Point to more complex things
  • Examples: String
  • Can be null (by default)
  • Have special actions (methods) you can use
// Simple vs Fancy Variable Types
public class TypeComparison {
    public static void main(String[] args) {
        // Simple types (primitives) - store the actual value
        int number1 = 5;
        int number2 = 5;
        System.out.println("Same number? " + (number1 == number2)); // true
        
        // Fancy types (reference) - more complex
        String word1 = "Hello";
        String word2 = "Hello";
        System.out.println("Same word? " + word1.equals(word2)); // true
        
        // String can be empty (null), but int cannot
        String emptyText = null;
        System.out.println("Empty text: " + emptyText);
        
        // This would cause an error:
        // int emptyNumber = null; // NOT ALLOWED!
    }
}


🍿 [Popcorn Hack] Practice #1: Your Favorite Things

Make variables for your favorite things:

  1. Your favorite food (text)
  2. Your age (whole number)
  3. Your height in feet (decimal)
  4. Do you like pizza? (True/False)
  5. First letter of your favorite color
  6. Your birth year (this never changes… what type of variable will you make it??)

Answer is below:

// Practice #1 Solution
public class MyFavoriteThings {
    public static void main(String[] args) {
        // My favorite things
        String favoriteFood = "Sushi";
        int myAge = 17;
        double heightInFeet = 5.8;
        boolean likesPizza = true;
        char colorFirstLetter = 'G';  // Green
        final int BIRTH_YEAR = 2007;  // Never changes
        
        // Print everything
        System.out.println("Favorite food: " + favoriteFood);
        System.out.println("Age: " + myAge);
        System.out.println("Height: " + heightInFeet + " feet");
        System.out.println("Likes pizza: " + likesPizza);
        System.out.println("Favorite color starts with: " + colorFirstLetter);
        System.out.println("Born in: " + BIRTH_YEAR);
    }
}

// Run the code
MyFavoriteThings.main(null);
Favorite food: Sushi
Age: 17
Height: 5.8 feet
Likes pizza: true
Favorite color starts with: G
Born in: 2007
Age: 17
Height: 5.8 feet
Likes pizza: true
Favorite color starts with: G
Born in: 2007

🍿 [Popcorn Hack] Practice #2: Pick the Best Type

What type should you use for each of these?

  1. Number of siblings
  2. Your first name
  3. Are you hungry?
  4. Your favorite letter
  5. Your height in inches
  6. Number of days in a year (never changes)

Think about it, then check below!

// Practice #2 Solution
public class PickTheType {
    public static void main(String[] args) {
        // 1. Number of siblings (whole number)
        int siblings = 1;
        
        // 2. First name (text)
        String firstName = "John";
        
        // 3. Hungry status (yes/no)
        boolean isHungry = false;
        
        // 4. Favorite letter (single character)
        char favoriteLetter = 'Z';
        
        // 5. Height in inches (decimal possible)
        double heightInches = 67.5;
        
        // 6. Days in year (constant whole number)
        final int DAYS_IN_YEAR = 365;
        
        // Print all values
        System.out.println("Siblings: " + siblings);
        System.out.println("Name: " + firstName);
        System.out.println("Hungry: " + isHungry);
        System.out.println("Favorite letter: " + favoriteLetter);
        System.out.println("Height: " + heightInches + " inches");
        System.out.println("Days per year: " + DAYS_IN_YEAR);
    }
}

// Run the code
PickTheType.main(null);
Siblings: 1
Name: John
Hungry: false
Favorite letter: Z
Height: 67.5 inches
Days per year: 365
Name: John
Hungry: false
Favorite letter: Z
Height: 67.5 inches
Days per year: 365

🏠 Homework Hack: Simple Grade Calculator

Make a program that calculates a student’s grade:

What you need to store:

  1. Student’s name (make this final)
  2. Three test scores (whole numbers 0-100)
  3. The class name (make this final)

What to calculate:

  • Average of the three test scores
  • Show what letter grade they earned
// Homework Hack Solution: Grade Calculator
public class GradeCalculator {
    public static void main(String[] args) {
        // Student information (constants)
        final String STUDENT_NAME = "John Smith";
        final String CLASS_NAME = "AP Computer Science A";
        
        // Test scores (0-100)
        int test1 = 95;
        int test2 = 88;
        int test3 = 92;
        
        // Calculate average
        double average = (test1 + test2 + test3) / 3.0;
        
        // Calculate letter grade
        char letterGrade;
        if (average >= 90) {
            letterGrade = 'A';
        } else if (average >= 80) {
            letterGrade = 'B';
        } else if (average >= 70) {
            letterGrade = 'C';
        } else if (average >= 60) {
            letterGrade = 'D';
        } else {
            letterGrade = 'F';
        }
        
        // Print results
        System.out.println("Grade Report for " + CLASS_NAME);
        System.out.println("Student: " + STUDENT_NAME);
        System.out.println("\nTest Scores:");
        System.out.println("Test 1: " + test1);
        System.out.println("Test 2: " + test2);
        System.out.println("Test 3: " + test3);
        System.out.println("\nAverage Score: " + String.format("%.2f", average));
        System.out.println("Letter Grade: " + letterGrade);
    }
}

// Run the code
GradeCalculator.main(null);
Grade Report for AP Computer Science A
Student: John Smith

Test Scores:
Test 1: 95
Test 2: 88
Test 3: 92

Average Score: 91.67
Letter Grade: A
Student: John Smith

Test Scores:
Test 1: 95
Test 2: 88
Test 3: 92

Average Score: 91.67
Letter Grade: A

Summary

// Making Variables:
int age = 16;           // Whole number
double price = 4.99;    // Decimal number  
boolean isReady = true; // True or false
char grade = 'A';       // One letter
String name = "Alex";   // Words/text
// Final Variables (Never Change):
final int MAX_SCORE = 100;
final String SCHOOL = "My School";

Picking Types:

  • Counting thingsint
  • Money, measurementsdouble
  • Yes/No questionsboolean
  • One letterchar
  • Names, sentencesString

Remember:

  • Use good names for your variables (age not a)
  • Final variables use ALL_CAPS
  • Strings need double quotes: "hello"
  • Chars need single quotes: 'A'

🎯 Now you know how to store information in Java! Complete the HW to test your skills.

Submission form: https://forms.gle/EJaB8hb5kRYhrYd79