Variables are devices that store data in memory (much like short our short term memory), they are an essential feature that all programming languages share.
Primitive vs Reference
There are two main types of variables.
- Primitive - this data is stored directly in memory, every primitive data type is a number of varying ranges. There are eight primitive data types in Java: byte, short, int, long, float, double, boolean, and char.
- Reference - also known as objects, a reference does not contain the actual data, rather it contains a "pointer" to where the data is held. The examples are Object, Vector, and String.
To use a variable we must first declare it. In Java we do use the following structure (formally known as syntax):
<variable type> <variable name>;
You will learn about types later in this chapter.
It's name can be anything as long as it's made up of only letters, numbers, "_" and "$". Variables are case sensitive (so "message" is different from "Message").
Java is what's known as a "strongly typed" language, which means each variable explicitly a certain type (e.g. number, string etc).
These represent whole numbers (1, 2, 3...). The "int" type is the most commonly used integer, and has a range of about ± 2.1 billion.
As seen before, strings store textual data.