1.2

Variables & Data Types

AP Computer Science A

Declaring variables

java
int age;         // declaration — creates the variable
age = 17;        // assignment — gives it a value
int score = 95;  // declaration + initialization in one step
java
x = 10;  // ERROR: x hasn't been declared

Primitive data types (AP Exam)

int

java
int students = 30;
int temperature = -5;
int population = 1000000;

double

java
double gpa = 3.85;
double pi = 3.14159;
double salary = 50000.0;  // still a double even though it looks "whole"

boolean

java
boolean isRaining = true;
boolean gameOver = false;

Other types to know

Naming rules and conventions

Rules (these MUST be followed or the code won't compile)

Conventions (these SHOULD be followed for clean code)

java
// Good naming
int studentCount = 25;
double averageGrade = 88.5;
boolean isEnrolled = true;

// Bad naming (compiles but hard to read)
int x = 25;
double a = 88.5;
boolean b = true;

Constants with final

java
final double TAX_RATE = 0.08;
final int MAX_STUDENTS = 30;

TAX_RATE = 0.10;  // ERROR: cannot assign a value to final variable

Default values vs. local variables

java
public static void main(String[] args) {
    int x;
    System.out.println(x);  // ERROR: variable x might not have been initialized
}

AP Exam Tips

Common Mistakes

Key Vocabulary