Aigle_Notes

Java - Variables

Variables in Java are classified into primitive and reference variables. Since Java are statically-typed, they must be declared [with their type and all] before usage.

Primitive variables

A primitive variable is any variable having a primitive [or pre-defined] data type. It stores as value any information related to it.

int value = 10;
String name = "Michael Jackson";

When we say int value = 10, we mean ‘reserve a location in memory called value and copy the value 10 to it’.

When we declare a primitive variable, the computer reserves memory to store the value assigned to the variable [the amount of storage required depends on the datatype].

Primitive variables are immutable. This means their internal state can’t be changed, unlike reference variables.

This is due to their values being stored directly in that variable.

Primitive data types

These are the pre-defined data types found in Java.

Reference variables

A reference variable points to an object and lets you access its value [i.e. it holds the memory address of that object in order to refer it, like a pointer].

Its value points to a location that contains information relating to the given variable.

coffee java = new coffee("java", 35);

Reference variables are mutable. This means their internal state is mutable, thanks to them being a reference to the variable’s data.