1.2 - Variables and Data Types
A data type is basically a set of possible values plus the operations you’re allowed to do on them. Data types fall into two buckets:
- Primitive types: numbers and booleans
- Numbers (
intanddouble) work with arithmetic operators like+and-, andbooleanvalues work with logical operators like&&and||(Unit 2).
- Reference types: everything else, used to define objects
- Examples:
String,Scanner, and any class someone writes, like aDogorStudentclass. An object can hold much more than one value (aStringholds a whole sequence of characters, for example).
The three primitive types you need for this course are:
Type | Holds |
int | a whole number |
double | a real (decimal) number |
boolean | true or false |
Note: Java has other primitives too (
long, short, byte, float, char), but those are outside the scope of this course.A variable is a named storage location that holds a value, and that value can change while the program runs. Every variable has a name and a data type attached to it.
A variable of a primitive type holds the actual value itself. After
int age = 16; runs, the variable age stores the number 16. (Reference type variables work differently, see 1.12.)You declare a variable by writing its type and then its name. You can give it a value on the same line or later, but once a variable is declared, its type can’t change.
int age = 16; double gpa = 3.85; boolean isEnrolled = true;
int students; // declared, no value yet students = 28; // now it holds 28 students = 30; // the value can change while the program runs double height = 1.75; // declared and given a value on one line
Variable names can use letters, digits, and the
_ symbol, but they can’t start with a digit, can’t contain spaces, and can’t be a Java keyword like int or class. Names are case sensitive, so score and Score are two different variables. By convention, Java programmers use camelCase: start lowercase and capitalize each new word, like totalScore.Choosing a Data Type
You’ll often need to pick the best type for a value. Ask yourself what kind of value it is:
int: whole numbers you count, like the number of students in a class or the score in a game.
double: values that can have a decimal part, like a GPA, an average, or a temperature.
boolean: anything with only two options, like whether a door is locked or whether a player has won.
- Reference type: anything that isn’t a single number or true/false, like a name (a
String) or a whole student record (an object of a class).