Lesson 1.2 · Unit 1 · CED topic 1.2

Variables and data types

A variable is a named storage location that holds a value. In Java every variable has a name and a data type, and the type is permanent: a variable declared to hold whole numbers holds whole numbers for its whole life. The compiler enforces that promise, which is why so many Java mistakes are caught before the program ever runs.

A data type is a set of values together with the operations you can perform on those values. Java sorts data types into two categories. Primitive types hold a single plain value. Reference types define objects, and a variable of a reference type holds a reference to an object stored elsewhere.

Required content · LO 1.2.A, LO 1.2.B

Learning objectives.

  • 1.2.A. Identify the most appropriate data type category for a particular specification.
  • 1.2.B. Develop code to declare variables to store numbers and Boolean values.

Essential knowledge.

  • 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.A.2. The primitive data types used in this course define the set of values and corresponding operations on those values for numbers and Boolean values.
  • 1.2.A.3. A reference type is used to define objects that are not primitive types.  
  • 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.
    Outside the course: The other five primitive data types (long, short, byte, float, and char) are outside the scope of the AP Computer Science A course and exam.
  • 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. A variable of a primitive type holds a primitive value from that type.

The three primitive types in this course

TypeValuesExamples of literalsTypical use
intwhole numbers, positive, negative, or zero0, 42, -7counting, indexes, ages, scores
doublereal numbers, with a fractional part3.14, -0.5, 2.0measurements, averages, prices
booleanexactly true or falsetrue, falseyes or no questions, conditions

7 and 7.0 are different values of different types. They print differently, they divide differently (Lesson 1.3 shows how), and they are stored differently. String is the reference type you meet first: a variable of type String holds a reference to a sequence of characters, and you write one in double quotes.

Declaring and initializing

A declaration gives a variable a type and a name. An initialization gives it its first value; you can do both in one statement.

int quantity = 3;                 // whole number
double unitPrice = 12.50;         // number with a fractional part
boolean taxExempt = false;        // exactly true or false
String itemName = "Notebook";     // reference type: a String object

Names follow rules and habits.

  • A name starts with a letter and contains letters, digits, and underscores. quantity and item2 are valid; 2ndItem is not.
  • A reserved word such as int, class, new, public, or return cannot be a name.
  • Names are case sensitive: total and Total are two different variables.
  • By convention names for variables use camelCase: unitPrice, not UnitPrice or unit_price.
  • The same name cannot be declared twice in the same block of code.

A variable of a primitive type holds the value itself. A variable of a reference type holds a reference, so it can also hold the special value null, meaning no object (Lesson 1.4 explains it).

Key idea · a variable holds one value at a time

A variable can change while the program runs, but it holds a single value at any moment. When a new value is stored, the old one is gone. The data type fixes what kind of value fits: an int variable cannot hold 3.5, and a boolean variable cannot hold 1.

Worked example · a receipt

Declare one variable of each type and print a receipt line for each.

String itemName = "Notebook";
int quantity = 3;
double unitPrice = 12.50;
boolean taxExempt = false;

double subtotal = quantity * unitPrice;
System.out.println("Item: " + itemName);
System.out.println("Quantity: " + quantity);
System.out.println("Unit price: " + unitPrice);
System.out.println("Subtotal: " + subtotal);
System.out.println("Tax exempt: " + taxExempt);
Item: Notebook
Quantity: 3
Unit price: 12.5
Subtotal: 37.5
Tax exempt: false

Notice that 12.50 printed as 12.5. The trailing zero in the literal is formatting, not part of the value: a double stores a number, never a number of decimal places.

Worked example · choosing the type from a specification

For each quantity, choose the most appropriate type and write the declaration.

QuantityTypeDeclarationWhy
number of students in a classintint students = 24;counted in whole units
the average of three test scoresdoubledouble average = 87.5;an average can have a fractional part
whether a door is lockedbooleanboolean locked = true;exactly two possibilities
a person's nameStringString name = "Maya";text, so a reference type
the number of miles driven, to the tenthdoubledouble miles = 12.4;a measurement with a fractional part

The rule is: counted values are int; measured values are double; yes or no values are boolean; text is String.

Worked example · what the compiler refuses

Each line below breaks a rule, and the compiler rejects the program at that line.

public class Main {
    public static void main(String[] args) {
        int wholeNumber = 3.5;
    }
}
Main.java:3: error: incompatible types: possible lossy conversion from double to int
        int wholeNumber = 3.5;
                          ^
1 error

A double value would lose its fractional part if it were forced into an int, so Java refuses to do it silently. A similar refusal happens for boolean flag = "yes"; (a String is not a boolean) and for int 2ndPlace = 2; (a name cannot start with a digit).

Exam focus

The exam asks you to pick the most appropriate data type for a given specification, so practice the counted, measured, yes or no, and text rule until it is automatic. It will also show code with a mismatch (a double assigned to an int, a String assigned to a boolean) and ask why it will not compile. Only int, double, and boolean are tested among primitive types; long, short, byte, float, and char are outside the course and the exam.

Practice
  1. Which type is most appropriate for the number of tickets sold in a day?
    Show answer

    int. A count of tickets is a whole number, and no fractional ticket exists.

  2. Which type is most appropriate for a student's grade point average such as 3.67?
    Show answer

    double. It is a real number with a fractional part.

  3. Which declaration compiles?
    A.  int score = 9.5;
    B.  double score = 9;
    C.  boolean score = 1;
    D.  String score = 9;
    Show answer

    B. A whole number is accepted where a double is expected (the int 9 becomes 9.0), so B compiles. A would lose the fractional part, C stores an int in a boolean, and D stores a number where a String object is required.

  4. What is printed?
    int a = 7;
    double b = 7.0;
    System.out.println(a);
    System.out.println(b);
    Show answer

    7 on one line and 7.0 on the next. The two variables hold values of different types, and a double always prints with a decimal point.

  5. What is wrong with this program, and when does the problem show up?
    int count = 1;
    int count = 2;
    Show answer

    The name count is declared twice in the same block, so the compiler rejects the code. It is a syntax-level error found at compile time, before anything runs.

  6. Which of these is a reference type: int, boolean, String, double?
    Show answer

    String. The other three are primitive types. A variable of type String holds a reference to a String object rather than the characters themselves.

← 1.1 Algorithms, programs, and compilers1.3 Expressions and output →

Keep going in the full AP Computer Science A course

All of U1 (Using Objects and Methods) is free to everyone, with no account. The course has 58 lessons, each with worked examples and practice problems that come with full solutions. A free account can also start a free month of the whole course, with no card.

Open this lesson in the courseSee the whole course