java online - Scope of variable in Java Programming language

Programming languages or concepts

 Scope of variable in Java Programming language :-

 scope of variable define the region of visibility for availability for variable out of which we cannot reference that variable.  

     Scope of variable is the part of the program where the variable is accessible.

    Variable declared inside main( ) function cannot be accessed outside the main( ) function scope of a variable is limited to the curly  brackets containing it, if you tried to access that variable outside those {then you will get compilation error.

Variables can be following two types based on their scope.
  • Local variable
  • Instance variable
  • Class / static variable


1) local variable in Java

        Local variable declared inside a method, constructor or block of code are called local variable.

They can be accessed only inside that method or block of code.

   Local variable are not available outside the function.

  Local variable defined in a block begin with an opening Curly brace & ends with a closing Curly brace.

  Access specifiers cannot be used for local variables.

Ex.

    Public class student

     {

         Public void getdata ( )

            {

                int id = 99;

           System.out.println (" Student id is : " + id);

              }

         Student st = new student ();

         st.getdata();

       }


2) scope of instance variable in Java:-

      The scope of instance variable inside the class.

    They are visible inside all the methods, constructors and from the beginning of its programming block to the end of programming block in the class.

  Values of instance variable can be assigned during the declaration or or within the constructor.

   The instance variable can be accessed directly by calling the variable name inside the class.

   But for static methods they should be called using the fully qualified name.

Syntax;

       ObjectReference.VariableName;


  Instance variable are created when object is created and destroyed once the object is destroyed.

  They are also referred to as fields.

  Access specifiers can be given for instance variable and if nothing is  mentioned the default specifier is used


3). Scope of static variable:-

        The scope of static variable is within the class.

    All the methods constructors and blocks inside the class can access static variable by using the class name.

 Syntax:

        ClassName.VariableName;

 

Tags:
close