Variables serve as containers for holding data values.
In Java, various types of variables exist, including:
When creating a variable, you need to define its type and assign it a value.
type variableName = value; |
The type refers to one of Java’s data types (like int or String), and variableName is the chosen identifier for the variable (such as x or name). The equal sign (=) is employed to assign values to the variable.
Consider the following example to create a variable intended for storing text:
Declare a variable named “name” of type String and initialize it with the value “John”:
|
For creating a variable intended to store a number, refer to the following example:
Declare a variable named “myNum” of type int and initialize it with the value 15:
|
It's also possible to declare a variable without assigning a value initially, and then assign a value later:
|
Keep in mind that assigning a new value to an existing variable will replace the previous value:
Update the value of myNum from 15 to 20 :
|
To prevent others, or yourself, from altering existing values, employ the final keyword. This designates the variable as “final” or “constant,” rendering it immutable and read-only.
|
An illustration showcasing the declaration of variables of different types:
|
In the next section, you’ll delve deeper into understanding various data types. |