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 type | Default Value |
| Int | 0 |
| Char | Blank |
| Float | 0.0 |
| Boolean | False |
| Pointer – Reference | null |
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: