In Java, objects are stored with their states in variables. They are acting as containers to hold values during object’s life scope.
How to declare a variable?
To declare variable, we require to assign some data type for that variable. Data type defines what kind of value this variable can hold (int, long ,float,String etc.).Variable names are case-sensitive.
What is the scope of a variable?
1) Instance Variable
Syntax
ClassScope ClassName { DataType varName; }
Example
class Person{ String personName; }
Here, personName is an instance variable, Each instance of class Person will have separate copy for personName.
2) Class variable
Syntax
ClassScope ClassName { static DataType varName; }
Example
class Person{ static String personName; }
Here, personName is a class variable, It is also known as static variable, All instances of class Person will share the same personName attribute.
3) Local Variables
Syntax
ReturnType MethodName{ DataType localVariable; }
Example
void showLocalVariable(){ String personName; }
Here, personName is a local variable, its scope is within method only.
4) Parameters
Syntax
ReturnType showParameter(DataType1 parameter1,DataType2 parameter2,..,DataType3 parametern){ //logic part of this method. }
Example
int addition(int firstNumber,int secondNumber){ return firstNumber+secondNumber; }