A variable is a name given to a memory location where we can store some data.
Variable Declaration:
The process of specifying what type of data is stored into the memory is called as variable declaration.
Syntax
datatype variableName;
datatype variable1, variable2, variable3,….;
Example:
int rollNo;
double marks;
char grade;
boolean result;
int custid,accontNumber,pinNo,age;
When a variable is declared, the memory for that variable will be allocated. The amount of memory allocated to a variable will depend upon the data type that is specified.
Once the memory for that variable is allocated and if we do not specify any value to that variable, then the variable will automatically contain its default value.
Byte | 0 |
Short | 0 |
Int | 0 |
Long | 0 |
Float | 0.0 |
Double | 0.0 |
Char | space |
Boolean | false |
If we declare a variable and if do not provide a value to that variable then that variable will be initialized automatically with default values. If we do not want the variable to contain default values, then we can initialize the variable with our own values.
Syntax for initializing a variable during declaration time:
datatype variableName;
datatype variable1, variable2, variable3,….;
Example:
int rollNo=123;
double marks=89.5;
char grade=’A’;
boolean result=true;
int custid=1234,accontNumber=56888,pinNo=1587,age=25;
Initialization:
The process of specifying a value to a variable for the first time is called initialization. The value of a variable can be changed any number of times during the execution of the program.
Assignment:
The process of specifying a value to variable from the second time onwards or after the initialization is called assignment.
Example:
double dollar=61.45; initialization
dollar=62.05; assignmnet
dollar=58.34; assignment
Keyword
The words that have predefined meaning in java or the words whose meaning is reserved in java are called keywords.
Note: The keyword of java language must be specified are called as literals.
Literals
The values that we store into a variable are called a literals.
Identifier
Any name that is used for the purpose of identification is called identifier.
int (keyword/datatype) age (identifier/variable) = 23 (Literal/data/value)
int age=23;
Rules for Writing an Identifier
- An identifier can be a combination of alphabets, digits, underscore and dollar
- An identifier must not begin with adigit. It can begin with either an alphabet or underscore or dollar
- Identifier should not contain any spaces
- The keyword of java language should not be used as identifier
- There is no restriction on the length of the identifier, but it is recomended to write an identifier having not more than 16 characters
- The name of the identifier should be maintaining and appropriate to the application.
int x=23; valid but not recommended
int custid=23; valid and recommended.