ACSA Exam Prep
Unit 1 · Using Objects and Methods · Topic 1.2

Variables and Data Types

Skill 1.ASkill 2.A

Big idea: A variable is a named box that holds one value of a fixed type. Choosing the type means choosing what kind of values the box can hold.

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

Primitive and reference types

A data type is a set of values plus the operations you can do on them. Java has two categories. A primitive variable holds its value directly. A reference variable holds a reference to an object (think: the object's address).

TypeHoldsExample valuesUse it for
intWhole numbers0, -12, 2048Counts, indexes, scores
doubleReal numbers3.75, -0.5, 2.0Measurements, averages, money in examples
booleanTruth valuestrue, falseYes/no conditions
String (reference)Text"Ada", ""Names, words, messages

Declaring and initializing

A declaration gives the type and the name. You can give the first value (initialize) in the same line. Names start with a letter and use camelCase by convention (totalScore). Keywords like int or class can't be names.

Code
int students = 28;
double gpa = 3.75;
boolean isEnrolled = true;
String name = "Ada";
System.out.println(name + " " + students + " " + gpa + " " + isEnrolled);
Output
Ada 28 3.75 true

Constants with final

Adding final makes a variable a constant: once it has a value, any attempt to change it is a compile-time error. Constants are usually named in ALL_CAPS.

Code
final int MAX_PLAYERS = 4;
// MAX_PLAYERS = 5;   // compile-time error: cannot assign a value to final variable
System.out.println(MAX_PLAYERS * 2);
Output
8
Key points
  • Three primitive types are tested: int, double, boolean.
  • A reference type (like String or any class) defines objects. The variable holds a reference, not the object itself.
  • A variable is a named storage location with a fixed data type. Its value can change unless it is final.
Watch out
  • Pick int for counts, double for measurements, boolean for yes/no.
  • String starts with a capital S because it is a class. It is not a primitive.
Exam tip
  • "Most appropriate type" questions hinge on whether the value can have a fractional part or only two states.
Quick check
Which type fits the number of seats left on a flight? The average rating of a movie? Whether a seat is taken?
Show answer
int, double, boolean.
Is String a primitive type?
Show answer
No. String is a class, so it is a reference type.
Not on the exam
  • The other five primitive types (long, short, byte, float, char) are not on the exam.