Variables
Variable is the container which holds user data. Memory will be allocated for the variable while executing the program.
Values of the variable can be changed any number of times during the program execution.
Syntax:
<DataType> <variableName>;
<DataType> <variableName> = <value>;
Example:
int a;
int a=10;
String str;
String str="Hello";
Types of Varibles - Based on Data Types
There are two types of variables based on data types used to declare the variable.
- Primitive Variables
- Reference Variables.
Primitive Variables
Variables declared with primitive data types are called primitive variables.
Example:
int a;
int b = 99;
double d1;
double d2=9.9;
Reference Variable
Variables declared with user defined data types are called as reference variables. Example:
String str1;
String str2="Hello World";
Primitive Variables | Reference Variables |
---|---|
Variables declared with Primitive data types are called as primitive variables. | Variables declared with user defined data types are called as reference variables. |
Memory allocation for primitive variables depends on the primitive data types. | Always 8 bytes of memory will be allocated for reference variable(JVM dependent) |
Default value for primitive variables depends on the primitive data types. | Always null will assigned as default value for reference variables. |
Primitive variables hold valid literals or value in the allocated memory. | Reference variables hold either null or address of an object in the allocated memory. |
Types of Varibles - Based on Scope of the Variable.
There are three types of variables based on the scope of the variables.
- Instance variables.
- Static variables.
- Local variables.
Instance variables.
Variables declared inside the class without using static keyword are called as instance variables.
Static variables.
Variables declared in the class using static keyword are called as Static variables.
Local Variables.
Variables declared in the member of the class like method etc are called as Local variables.
TODO: More...