static variable and method


Static variable: 
Variable which are declared inside the class with static keyword are called static variable. Memory will be allocated for static variable when JVM is loading the class into main memory. Only one copy of memory will be allocated for static variable.


Static method:
When you don’t have instance variables in the class then creating a object for that class is useless and waste of some memory, to avoid that you can declare method as “static method” when the method is static, we can called that method is static method of that class.
Example:
class Hello{
                        int a=3;
                        static int b=50;
                        //instance method
                        void method1(){
                                                     System.out.println(“method1”);
                                                      System.out.println(a);
                                                       System.out.println(“b”);
                                                       }
            static void method()
                           {                                                                                                                                                System.out.println(“method1”);
           //System.out.println(a); instance variable can’t access
              System.out.println(“b”);
                            }
                   }   

0 comments :

Post a Comment