How can JVM load the class into memory?


When you are trying to use the class then JVM loads the class into main memory.
When JVM is loading the class into the main memory following task will happen:-
1.      Memory will be allocated for static variable.
2.      Static blocks will be executed.

When you are trying to create object for the class following task will happen:-
1.      Memory will be allocated for reference variable.
2.      Memory will be allocated for instance variable.
3.      Instance block will be executed.
4.      Corresponding constructors will be invoked.
5.      Object address will be assigned to reference variable.
We explain here using one of example as
class  HelloWord{
                        int x=5;
                        Static int y=10;
                        System.out.println(“This is non static block”);
                        System.out.println(“x”);
                        System.out.println(“y”);
                        Static {
                                    System.out.println(“This is  static block”);
                                    //System.out.println(“x”); instance variable can’t called in static block.
                                    System.out.println(“y”);
                                    }          
                        }
            class Testing{
                                    public static void main(String as[]){
                                                            HelloWord h1 = new Helloword();
                                                            HelloWord h2= new HelloWord();
                                                            HelloWord h3 = new HelloWord();
                                                                        }
                                    }


Output:
                        --This is static block.
                        --10
                        --This is non static block.
                        --5
                        --10
                        --This is non static block.
                        --5
                        --10
                        --This is non static block.
                        --5
                        --10

0 comments :

Post a Comment