Contents:
- What is a variable?
- How to declare a variable in java?
What is a variable?
In layman’s terms, When you think of Java variable, think of an empty container that you can put values in.
“A variable is container. It holds something.”
Whenever, we need a data to get stored in computer memory for further processing, we have to allocate memory space for storing that data and later we can reuse that data multiple times if required for calculation. So, to do all these things, we need to create a variable and assign value to the variable. In Java, you have to give your variable a name. Also, Java variables have associated types that is either primitive or non-primitive. Type defines the size of variable and what kind of values a variable is allowed to hold. When you declare a variable by assigning a value, a memory space is allocated based on the data type you mentioned before variable name and value is stored in memory area. It means, When you declare any variable in Java, you must declare it with a specific type.
“Technically, a variable is a storage location where your data is going to be stored.”
How to declare a variable in Java?
In java, variables must be declared before they can be used. The basic form of variable declaration is shown here:
type identifier [=value] [, identifier = [value] … ] ;
Here, the matter written inside [ ] is optional. The type written before identifier is Java data type which can be primitive or non-primitive. Data type decides how much memory space need to be allocated and what kind of data a variable of that kind will hold. Identifier is the name of variable. You can initialize the variable by specifying an equal sign and a value.
int a, b, c ;
int k = 3, p, r = 18 ;
byte z = 56 ;
Happy Learning !