Thursday, 29 November 2018

Java - Variables and Scopes


Three Scopes and Life time of Variable
1.   Instance Variable(Class Scope)
2.   Local Variable(Method Scope)
3.   Static variable
Instance Variables
Instance variables are already discussed
Local Variable (Method Scope)
Variables declared within method can be known as local scope. When run time invokes the method, the local scope variable has the memory and the memory destroys after runtime exits from method. Other methods can’t use the local variables.
Block scope is another feature of local scope. Variable declaration within if block, for block, while block can be known as block scope. The block scope variables can’t be visible in other blocks.
Example
   if (x==5)
         int y=10;
   S.o.p(y); // error
Static variable
Static variables are having common memory for all objects. It can be accessed by using objectname.varname or classname.varname. There are no differences to use two different syntaxes to access the static variables. Static variables can only be declared outside of methods and constructors. Static variable will have default values.
Consider following examples
Example 1
class A
{
static int x; // static variable
int b; // instance variable
   A()
         {
              static int y; //error
         }
   void get()
         {
              static int z; //error
         }
   public static void main(String arg[])
         {
              static int p; //error
              System.out.println(x);
         }
}
Example 2
class A
{
   static int a=100;
}
class B
{
   public static void main(String arg[])
         {
              System.out.println(A.a); // classname.variablename
              A ob=new A();
              System.out.println(ob.a); //objectname.variablename
         }
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.