Static variables in Java

Previous
Next

Static variable:

  • Declaration of variable inside the class and outside to methods and blocks.
  • We must define the variable with static keyword.
  • We access static variable from all methods and blocks.
  • We can access the variable using class name.
public class Pro
{
    static int a=10;
    static
    {
        System.out.println("In block : " + Pro.a);
    }
    public static void main(String args[])
    {
        System.out.println("In main : " + Pro.a);
    }
}
  • If we are not assigning any value to static variable, it is initialized with default values.
  • Default values depend on data types.
Data typeDefault Value
Int0
CharBlank
Float0.0
BooleanFalse
Pointer – Referencenull
public class Pro
{
    static int a;
    static char b;
    static float c;
    static boolean d;
    static String e;  // String = char*
    public static void main(String args[])
    {
        System.out.println("int default val : " + Pro.a);
        System.out.println("char default val : " + Pro.b);
        System.out.println("float default val : " + Pro.c);
        System.out.println("boolean default val : " + Pro.d);
        System.out.println("pointer default val : " + Pro.e);
    }
}
  • We can define both static and local variables with same identity.
  • When we access the variable directly inside the block, it is looking for local variable first.
  • If the local is not present, it access static variable.
public class Pro
{
    static int a=10;
    static
    {
       int a=20;
       System.out.println("In block : " + a);
       System.out.println("In block : " + Pro.a);
    }
    public static void main(String args[])
    {
        System.out.println("In main : " + a);
        System.out.println("In main : " + Pro.a);
    }
}

Write the output of following code:

public class Pro
{
    static int a=10;
    public static void main(String args[])
    {
        int a=20;
        
        Pro.a = a + Pro.a ;
        
        a = Pro.a + a ;
        System.out.println(a + Pro.a);
    }
}

Above code execution flow:

Previous
Next

Add Comment

Courses Enquiry Form