Create Object in Java static block

Previous
Next
  • Local variable belongs to the same block in which it has defined.
  • We cannot access local variable of one block from another block.
public class Pro
{
    static
    {
        int x=10;  // 'x' is local
        System.out.println("x in block : " + x);
    }
    public static void main(String args[])
    {
        System.out.println("x in main : " + x); // Error:
    }
}

Creating object in static block:

  • After object creation in static block if we assign address to local reference variable, we can access only from the same block.
public class Pro
{
    static
    {
        Pro obj = new Pro();  // 'obj' is local
        System.out.println("obj in block : " + obj);
    }
    public static void main(String args[])
    {
        System.out.println("obj in main : " + obj); // Error:
    }
}

Static variable:

  • Defining a variable outside to all blocks and methods.
  • We access static variable throughout the class using the identity of that class.
public class Pro
{
    static int x = 10;  // 'x' is static variable
    static
    {
        System.out.println("x in block : " + Pro.x);
    }
    public static void main(String args[])
    {
        System.out.println("x in main : " + Pro.x);
    }
}
  • After creating the object, we can assign the address to static variable.
  • We access the static variable using class name.
public class Pro
{
    static Pro x = new Pro();  // 'x' is static variable
    static
    {
        System.out.println("x in block : " + Pro.x);
    }
    public static void main(String args[])
    {
        System.out.println("x in main : " + Pro.x);
    }
}
Previous
Next

Add Comment

Courses Enquiry Form