Variables are the fundamental building blocks of any Java program. Think of a variable as a labeled container that holds a specific value in the computer's memory.
In Java, there are different types of variables meant to store different kinds of data. Here are the most commonly used ones:
Stores text, such as "Hello". Text must be surrounded by double quotes.
Stores integers (whole numbers), without decimals, such as 123 or -123.
Stores floating-point numbers, with decimals, such as 19.99 or -19.99.
Stores single characters, such as 'a' or 'B'. Values are surrounded by single quotes.
Stores values with two states: true or false.
To create a variable, you must specify the type and assign it a value.
type variableName = value;
As the name suggests, "variables" can change. You can assign a value to a variable and change it later in the program.
final Keyword:If you don't want others (or yourself) to overwrite existing values, use the final keyword. This makes the variable a "constant".
You can declare more than one variable of the same type in a single line using a comma-separated list.
You can also assign the same value to multiple variables in one line:
All Java variables must be identified with unique names. These unique names are called identifiers.
| Rule | Example |
|---|---|
| Names can contain letters, digits, underscores, and dollar signs. | myVar_1, $price |
| Names must begin with a letter (or $ and _). | score (Good), 1score (Bad) |
| Names are case-sensitive. | myVar and myvar are different |
| Reserved words (like Java keywords) cannot be used as names. | int, boolean (Cannot be names) |
Depending on where they are declared, Java variables are categorized into three types:
static keyword. They belong to the class and are shared by all objects.Variables are the heart of your data processing. Once you understand how to name and store them, you need to understand the memory they consume. In the next chapter, we will explore Data Types in detail to see how Java optimizes memory for different values.
Next: Java Data Types →