APCSA 1.2 — Variables and Data Types

A quick, student-friendly guide (Java)

Unit 1 • Program Design & Development

Overview

In Java, a variable is a labeled box in memory that stores data your program can use and change. Each variable has a name, a type, and a value.

  • Name — what you call it (e.g., age)
  • Type — what kind of data it holds (e.g., int, double, String)
  • Value — the actual data stored (e.g., 17)

Declaring and Initializing Variables

Declaration introduces a variable’s type and name:

int age;      // declaration
age = 17;     // initialization

Or do both at once:

int age = 17; // declare + initialize

Primitive Data Types (APCSA Core)

Type Example What it Represents
int 42 Whole numbers (no decimals)
double 3.14 Decimal (floating-point) numbers
boolean true / false Logical truth values
char 'A' Single Unicode character (single quotes)
int score = 95;
double price = 19.99;
boolean isPassing = true;
char grade = 'A';

Reference Types (Objects): String

String holds text and is a reference (object) type. Use double quotes.

String name = "Shrek";
System.out.println(name.length());     // number of characters
System.out.println(name.toUpperCase()); // SHREK
Note: Strings are objects, not primitives. You can call methods on them.

Assignment and Type Rules

You can change a variable’s value but not its type. Some assignments are safe:

int x = 5;
double y = x;   // OK: int → double (widening)

Others may lose information and are not allowed without a cast:

double y = 5.7;
int x = y;      // NOT OK: double → int (narrowing)

String Concatenation

String greeting = "Hello, ";
String name = "Donkey";
System.out.println(greeting + name);
// Hello, Donkey
System.out.println("Score: " + 100);
// Score: 100

Type Casting

Casting converts between compatible numeric types (you decide when narrowing):

double price = 9.99;
int dollars = (int) price; // explicit cast; drops decimals

Key Takeaways

  • A variable is a named storage location in memory.
  • Every variable has a type that restricts what it can hold.
  • Primitives store raw values; reference types store objects.
  • You must declare a variable before using it.
  • String is an object (with methods), not a primitive.