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.
- Names are identifiers for variables, classes, methods, packages, interfaces etc.
- Java identifiers used for naming variables, methods, classes and other programming elements must follow specific rules:
Allowed characters: letters (A-Z, a-z), digits (0-9), the underscore character (_), and the dollar sign ($).
Starting Character: must begin with a letter, an underscore (_), or a dollar sign ($).
Case Sensitivity: Java is case-sensitive, means identifiers Myvar and myvar are treated different.
Reserved Keywords: Identifiers can not be reserved keywords(e.g. int, char, class, for, if etc.)
Length: No strict limit on length, but keep it concise for readability.
- 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 initialise the variable by specifying an equal sign and a value.
Examples:
int a, b, c ;
int k = 3, p, r = 18 ;
byte z = 56 ;
Happy Learning !