Short on time? This page is the recap. For explanations and worked examples, use the full study guide.
Recap
- A data type is a set of values and a set of operations on those values. Types are primitive or reference.
- The primitive types used in this course are
int(an integer),double(a real number) andboolean(trueorfalse). - A reference type defines objects.
Stringis a reference type: aStringvariable holds a reference to aStringobject. - A variable is a storage location with a name, a data type and a value. The value can change while the program runs; the type cannot.
- A variable of a primitive type holds a primitive value of that type.
- The compiler checks that the value stored in a variable is of a compatible type.
Key relationships
| Idea | How to use it |
|---|---|
| Declare | int count; gives the type and name |
| Declare and initialize | int count = 12; |
| Change the value later | count = 20; (no type on the left) |
| int in a double variable | allowed: double rate = 4; stores 4.0 |
| double in an int variable | not allowed: int size = 3.0; fails to compile |
String in a boolean or int variable |
not allowed |
| Valid name | letters, digits, _ or $; cannot start with a digit; cannot be a keyword |
| Case | count and Count are different names |
| Choosing a type | count with int, measure with double, yes/no with boolean, text with String |
Assumptions and conventions
- The other five Java primitive types (
long,short,byte,float,char) are outside the course and exam. - Variable names start with a lower-case letter by convention, with later words capitalised (
totalPrice). - A value written with a decimal point (such as
4.0) is adouble; one without (such as4) is anint. - Text values are called string literals and are written in double quotes.
Mistakes to avoid
- Treating
4and4.0as identical. They have different types and print differently. - Storing a
doublein anint. The compiler rejects it. - Leaving out the quotes around a
Stringvalue, or putting quotes around a number ortrue. - Declaring the same name twice in the same method, or mixing up
countandCount. - Starting a name with a digit or using a keyword as a name.
- Expecting
double x = 9 / 2;to give 4.5. The integer division happens first, soxholds4.0.
Quick self-check
- Which type is best for the number of pages in a book? (
int) - Which type is best for a mass of 62.4 kg? (
double) - Does
boolean open = "true";compile? (No:"true"is aString, not aboolean.) - What do
aandbhold afterint a = 6; double b = a; a = 10;? (aholds 10 andbholds 6.0;bhas its own copy.) - Is
int total = 5; int Total = 9;allowed? (Yes: they are two different variables.)
Next: practice questions.