Variable is a placeholder (reserved
memory block) to store a value of any type. A variable is defined by its
name (identifier), type and initialization is optional.
Syntax for variable declaration:
Datatype variable_name [ = value ]; |
Two or more variables of same type can also be declared in a single line separated by commas.
Example:
int a = 5; float a,b; int i = 0, j =1; |
Types of variables in Java:
Java has 3 kinds of variables. They are,
- Local variables
- Instance variables (fields)
- Static variables (class variables)
1. Local variables:
- A local variable is defined inside a method block. A block begins with an opening curly brace and ends with a closing curly brace.
- The scope of the variable is limited within the block. In other words, local variables are visible only in the block (method) in which they are declared.
2. Instance variables:
- Instance variables are declared inside a class, but outside of any method / constructor / any block. They are also referred to as fields.
- Objects store their individual states in these fields. Their values are unique to each object (instance of class) and hence they are called as instance variables.
- Example – The ‘employeeId’ field of the Employee class will have a unique value for each of its object. (Consider Emp1, Emp2… as objects of the class Employee, then each object will have unique value for the property ‘employee-id’).
3. Static variables (Class variables):
- Static variables belong to the class rather than objects in which they are declared. The keyword ‘static’ is prefixed before the variable to represent static variables. Only one copy of this variable is maintained for all the objects.
- Example – static int width; would now indicate that the width of all the boxes (b1,b2… -instances of the Box class) would have the same value. One one copy of variable ‘width’ is maintained by all the objects of class Box.
Example:
class VariableExample {
int num; //instance variable
static int num2; //static variable
void method1(){
int i; //local variable
System.out.println(i);
}
}
|
0 Comments:
Post a Comment