Beginning Java/Variables

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 edit

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.

Declaration edit

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.

Its name can be anything as long as it is made up of only letters, numbers, "_" and "$". Variables are case-sensitive (so "message" is different from "Message").

The following demonstrates an example of variable declaration
String message;
This will create a new String variable called "message".


Types edit

Java is what's known as a "strongly typed" language, which means each variable explicitly a certain type (e.g. number, string etc).

Integers edit

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.

Strings edit

As seen before, strings store textual data.

Boolean edit

Floats and Doubles edit

Exercise edit