A variable is a container that is used for storing values.
Consider this analogy: a variable is like a vocabulary notecard. One side of the notecard is used for the word, and the other side is used for definition of that word. Here is an example of that in practice.
int amount = 3;
This line of code is called a variable declaration, and consists of a left and right-hand side.
The left-hand side of a variable declaration has a data type (
int) and a name (
amount), in that order. This tells your computer that the variable
amount has the data type
int, which will never change.
The right-hand side is the value which the variable will store. In this case, the value will be 3.
In the above example, variable
amount is the type
int. What does that mean?
As the name suggests, different data types specify what type of data can be assigned as the value to a variable. In Java, there are two kinds of data types: primitive and non-primitive.
8 different primitive data types are available in Java. They consist of:
int - an integer value
double - a decimal value
char - a Unicode character
long - like
int but used for longer numbers
float - like
double with less precision
byte - like
int but in the range of -127 to 128
short - like
byte but with a range of -32,768 to 32,767
In most cases, only the first 4 of those types are used. The other 4 are mainly used when memory consumption on your computer is of utmost importance, which is not the objective of this course.
As explained, Java has 8 primitive data types, as does the C programming language. However, this breaks the first law of pure OOP languages:
Pre-defined types are objects
Those 8 primitive data types are primitives, meaning they are not objects. Furthermore, this means that you cannot directly call methods on them, but must instead use helper classes instead.
How would you declare a variable
age? Hint: use the
int data type
int age = 15;