Scope of Variables

Scope of Variables:

  • The scope of a variable is the part of the program where the variable is accessible. 
  • Java programs are organized in the form of classes. 
  • Every class is part of some package.
  • There are three types of scope.

1. Class level scope

  • These variables must be declared inside class (or outside any function). 
  • They can be directly accessed anywhere in class. 
  • Class level scope applicable to member variables.
  • Example:

public class MyClass
{
    int a;
    private String b;
}

2. Method level scope

  • Variables declared inside a method have a method-level scope.
  • It is can’t be accessed outside the method.
  • Example:

public class MyClass
{
    int a;
    void display(int y)
    {
       int x;
    }
}

3. Block-level scope

  • A block begins with an open brace, followed by zero or more statements, followed by a close brace.
  • A. Zero statements

Example:
{
}

  • B.One statement

Example:
{
System.out.println("Hello World");
}


  • C. N-statements

Example:
{
System.out.println("Hello World 1");
System.out.println("Hello World 2");
System.out.println("Hello World 3");
System.out.println("Hello World 4");
}


  • You can declare local variables anywhere in a method body. 
  • However, if you declare a variable within a block, then it only has scope within the block.
  • Example:

public void display()
{
   int x = 3 ;
   {
      int y = 4 ;
      System.out.println( "Sum is " + (x + y) ) ;
   }
   System.out.println( "x is " + x ) ;
   System.out.println( "Sum is " + (x + y) ) ;
}

Thanks a lot for query or your valuable suggestions related to the topic.

Previous Post Next Post

Contact Form