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.
- 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).
| Type | Holds | Example values | Use it for |
|---|---|---|---|
int | Whole numbers | 0, -12, 2048 | Counts, indexes, scores |
double | Real numbers | 3.75, -0.5, 2.0 | Measurements, averages, money in examples |
boolean | Truth values | true, false | Yes/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.
int students = 28;
double gpa = 3.75;
boolean isEnrolled = true;
String name = "Ada";
System.out.println(name + " " + students + " " + gpa + " " + isEnrolled);OutputAda 28 3.75 trueConstants 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.
final int MAX_PLAYERS = 4;
// MAX_PLAYERS = 5; // compile-time error: cannot assign a value to final variable
System.out.println(MAX_PLAYERS * 2);Output8- Three primitive types are tested:
int,double,boolean. - A reference type (like
Stringor 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.
- Pick
intfor counts,doublefor measurements,booleanfor yes/no. Stringstarts with a capital S because it is a class. It is not a primitive.
- "Most appropriate type" questions hinge on whether the value can have a fractional part or only two states.
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.
- The other five primitive types (long, short, byte, float, char) are not on the exam.