Table of contents
Introduction
In a java program we have the following things a. static variables b. static block c. static methods
e. Non-static Variables f. Non-static block g. Non-static methods
Variable Access
- If a variable is declared as static then a.It can be accessed in the static method, static block b. It can also be accessed in the non-static method, non-static block
- If a variable is declared as non-static then c. It can be accessed in the nonstatic block and nonstatic methods only
How A Java Program gets executed
- When we finish writing the Java program the first step in execution is compiling the program
- After the compilation is complete then we get a byte code of the program which is then given to the Java Virtual Machine to begin the execution
- The JVM is further divided into 3 areas a. Class Loader b. Runtime Data Areas c. Execution Area
- Static Variables are allocated memory by the class loader and default values are assigned
- Static Block will also be executed by the class loader
- Static Method will be loaded onto the stack of the class Loader, If we have more than two static methods then always the main method is called first
- Then the other static methods are called and executed
Note: We have not created any object while executing the static variables as still we are in the class loader phase and objects are created at runtime and are allocated memory at run-time - After class loading is complete objects are created, When we create an object then the constructor will be called
- Suppose we have non - a static block then what will happen before we start executing the statements written inside the constructor of the non-static block will get executed first\
- After the non-static block is executed, the constructor is executed
- Then the non-static method will be executed
- Whenever we create an object every time memory will be allocated for non-static variables
- When to use static variables, when we have a common value that is shared between all the instances of the class then we use static variables
- Use of static block is to initialize main method and when we want to perform some action before the main method is executed we use static block
Example Of All Above In A Single Code
class HelloWorld {
HelloWorld(){
System.out.println("I am constructor ");
}
static int a=10;
static{
System.out.println("no object created yet");
System.out.println(a);
}
public static void disp(){
System.out.println("static block called after main ");
}
int b=20;
{
System.out.println(b);
System.out.println(" i AM NON -STATIC BLOCK");
}
public static void main(String[] args) {
System.out.println("calling main");
disp();
System.out.println("after creating an object");
HelloWorld object= new HelloWorld();
System.out.println("using static variable from non-static block");
System.out.println(a);
}
}