-
It is a named memory location that holds the data value of a particular data type.
Declaration: dataType variableName; Initialization: dataType variableName = value; **OR** dataType variableName; variableName = value;
- cannot contain white spaces
- can begin with a special character dollar ($) and underscore ( _ )
- first letter of a variable cannot be a digit
- camelCase convention should be used
- Built in keywords ( int, for, while, class, break, continue, etc ) cannot be used
- Local:
- declared within a body of method, constructor or code block.
- scope is limited within that block.
- created within the method or block and destroyed after the method invocation.
- No initialization ( no default values ), if not initialized compile time error
- stored in stack
- Instance
- declared inside the class but outside any method, constructor or block body
- not shared between objects.
- scope is tied to the instance or object of the class.
- created with the new keyword and destroyed when the object is destroyed.
- default values are given if not initialized
- stored in heap
- Static ( Class Variable )
- declared inside a class but not inside the method, constructor or a block, with the static keyword
- shared with all instances of class.
- scope is tied to the class itself.
- created at the start of the program and destroyed at the end of the program.
- default values are given if not initialized
- stored in Method Area or Class Area
- The data items that have fixed or constant values.
int number = 20;
//int -> data type
//number -> variable
//20 -> literalTypes:
-
Integer literals
-
Floating literals
-
Boolean literals
-
Character literals
-
String literals
-
Null literal