Variable holds the user data. The memory will be allocated for the variables according to the data type. Value of the variable can be changed any number of times during the program execution. Syntax: <data type><var name>; or <data type><var name>=<value>;
Example: int a; int b=10; String s=”name”; String st; There are two types of variables based on the data types used to declare the variable:
- Primitive variables
- Reference Variable
Variables declared with primitive data types are called as primitive variables. Example: int a, char c, double b=10.0, etc.
Variables declared with used defined data types are called as reference variables. Example:String str; String s=”Bbs”;There are following types of variables based on the scope of the variables:
- Instance variables
- Static variables
- Local variables
int a; // Instance Variable
static int b; // static variable
int c=10; // local variable
Variables declared without using static keyword inside of a class but outside of method is called instance variables. Example: variable a in the above code. The Memory will be allocated to the instance variable only at the time of object creation. As many times as the object is created, the instance variable will get the memory.
Variables declared using static keyword inside of a class but outside of method are called static variables. Example: variable b in the above code. The Memory will be allocated to static variables at the time of object creation when the class loads. Static Variable will get the memory only once when the class loads.
Variables declared inside of a method are called as Local variables. Example: variable c in the above code.
Constants are the special variables whose value can’t be modified during the program execution. These are also called final variables. Example:final int a=99; final String s=”Bbs”; final double d=10.1;