We use variables in Java to save data, and they must be declared with the data type and name before we can use them. The variable can only contain values that are compatible with its data type.
In programs, we store data in variables, and each variable corresponds to a memory location in the computer. A variable is a quantity that you introduces yourself, you give a name to it, and you can also assign values to it. Because we can use variables over and over again, they become beneficial. Variables are a part of the foundation of programming.
Variable in Java
Because we can use variables over and over again, they become beneficial. Variables are a part of the foundation of programming.
Furthermore, to make it easier to visualize what a variable is, consider the variable as a box that we have given a name. In this box, we can then save different values that we will use.
We will now see how we can declare some variables with different data types. Additionally, how we assign the variables an initial value. If you do not remember what a data type is, you can read more about it in the previous page. Moreover, note the differences in the declarations between different data types. We will later in chapter 7 (classes and objects) look at different visibility classes for variables. But now let’s focus on how we can declare different variables.
To create a variable in Java, write:
Data type name = value;
To create a variable in Java, you must
Below are a few examples of how to create different variables of a particular data type.
int varOne = 10; double varTwo = 15.0; boolean varLogical = false;
In this example, we have created three different variables:
If we illustrate it with the previously mentioned boxes
Declaring variables of characters and texts have the same basic principle but note the apostrophes (‘) for characters and quotes (“) for texts. This is needed around the value of the variable to declare it, but IntelliJ is helpful in giving characters and texts a green color if they are properly declared.
char varCharacter = 'e'; String varWord = "Hello";
The last thing we will take a look at before moving on from variables is that it is also possible to declare variables without an initial value. The computer will then give the variable a random value. A variable without an initial value declared quickly by writing.
Data type name; int varOne; double varTwo;