Variables in JAVA
• declaration – how to assign a type to a variable
• initialization – how to give an initial value to a variable
• scope – how the variable is visible to other parts of the
program
• lifetime – how the variable is created, used and
destroyed
• type conversion – how Java handles automatic type
conversion
• type casting – how the type of a variable can be
narrowed down
Basic Variable Declaration:
• datatype identifier [=value];
• datatype must be
– A simple datatype
– User defined datatype (class type)
• Identifier is a recognizable name confirm to
identifier rules
• Value is an optional initial value.
We can declare several variables at the same time:
type identifier [=value][, identifier [=value] ...];
Examples:
int a, b, c;
int d = 3, e, f = 5;
byte g = 22;
double pi = 3.14159;
char ch = 'x';
Variable Scope
• Scope determines the visibility of program elements with respect to other program elements.
• In Java, scope is defined separately for classes and methods:
1) variables defined by a class have a global scope
2) variables defined by a method have a local scope
A scope is defined by a block:
{
...
}
A variable declared inside the scope is not visible outside:
{
int n;
}
n = 1;// this is illegal
Variable Lifetime
• Variables are created when their scope is entered by
control flow and destroyed when their scope is left:
• A variable declared in a method will not hold its
value between different invocations of this method.
• A variable declared in a block looses its value when
the block is left.
• Initialized in a block, a variable will be re-initialized
with every re-entry. Variables lifetime is confined to
its scope!