x

Java – Variables

Prev     Next

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,


  1. Local variables
  2. Instance variables (fields)
  3. 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;
    It indicates that the width of all boxes (b1,b2… – instances of the Box class) would have the same value. Only one copy of variable ‘width’ is maintained by all the objects of class Box. i.e. Memory will be allocated for that variable only once regardless of how many objects created for that class. If the value of the static variable is changed from 3 to 4, then all the objects will refer to the same new value ‘4’. Only one copy of variable ‘width’ is used by all the objects of class Box.

Example:

Prev     Next



Like it? Please Spread the word!