Scope and Lifetime of Variables

 Java allows variables to be declared within any block. Scope and Lifetime of variable is determined how and where those variable is defined.

·      In Java, the two major scopes are those defined by a class and those defined by a method.

·      a block is begun with an opening curly brace and ended by a closing curly brace. A block defines a scope. Thus, each time you start a new block, you are creating a new scope. As cope determines what objects are visible to other parts of your program, it also determines the lifetime of those objects.

·      variables defined inside scope can't be accessed outside the scope of that variable

·      Thus, when you declare a variable within a scope, you are localizing that variable and protecting it from unauthorized access and/or modification.

·      Indeed, the scope rules provide the foundation for encapsulation.


To understand the effect of nested scopes, consider the following program:

// Demonstrate block scope.

class Scope {

  public static void main(String args[]) {

     int x; // known to all code within


x = 10;

if(x == 10) { // start new scope

int y = 20; // known only to this

// block

// x and y both known here.

System.out.println("x and y: " + x + " " + y);

x = y * 2;


// y = 100; // Error! y not known here

// x is still known here.

System.out.println("x is " + x);



The output is

x and y: 10 20

x is 40

·      Here is another important point to remember: variables are created when their scope is entered, and destroyed when their scope is left. This means that a variable will not hold its value once it has gone out of scope.

·      Also, a variable declared within a block will lose its value when the block is left. Thus, the lifetime of a variable is confined to its scope.

·      If a variable declaration includes an initializer, then that variable will be reinitialized each time the block in which it is declared is entered.

For example, consider the next program.

// Demonstrate lifetime of a variable.

class LifeTime {

  public static void main(String args[]) {

int x;

for(x = 0; x < 3; x++) {

int y = -1; // y is initialized

   //each time block is entered

System.out.println("y is: " +

y); // this always prints -1

y = 100;

System.out.println("y is now: " + y);




The output generated by this program is shown here:

y is: -1

y is now: 100

y is: -1

y is now: 100

y is: -1

y is now: 100
Java Basic Data Types
Type Conversion and Casting