Sunday, 6 March 2016

Static Keyword and Its usage in Java

                   In this post, we will discuss the use use of static keyword in Java. The static keyword is mainly used for memory management. This keyword is used to create static method, static class, static block and static variable. The static keyword belongs to the class than instance of the class.

1) Static variable :--

         
          Static variable value is same for all object or instances of the class, in other words we can say that all objects of the same class share a single copy of static variables. Static variable gets memory only once in class area at the time of class loading.

Example:-- Without using static,
 
       public class StaticVar {

             int a = 0;

             public StaticVar() {
                   a++;
                   System.out.println(a);
             }

             public static void main(String[] args) {

                    StaticVar o1 =  new StaticVar();
                    StaticVar o2 =  new StaticVar();

             }

        } 
 
 Output: 1
         1 
                 

Using static keyword- i.e static variable,

 
      public class StaticVar {

            static int a = 0;

            public StaticVar() {
                   a++;
                   System.out.println(a);

            }

            public static void main(String[] args) {

                   StaticVar o1 =  new StaticVar();      
                   StaticVar o2 =  new StaticVar();

            }

     }

Output:--  1
            2

                 

2) Static block:--

         
              Static blocks are nothing but a normal block of code, enclosed in braces {},preceded with static keyword. These static block will be called when JVM loads the class into memory. Incase a class has multiple static blocks across the class, then JVM combines all these blocks as a single block of code and executes it. Static blocks will be called only once, when it is loaded into memory. These are also called initialization blocks.
                Static block is mainly used for changing the default values of the static variables.

Example 1:--


    public class StaticBlk {

          static int a;

          static {

                a = 10;

                System.out.println(a);

         }

         public static void main(String[] args){

         }

   }

Output:-- 10

Example 2:-- Multiple static blocks


 public class StaticBlk {

        static int a;

        static {

              System.out.println("Static block1");

              a = 10;

        }

        static {

              System.out.println("Static block2");

              a = 20;

        }

        public static void main(String[] args){

              System.out.println("Value of a is "+a)

        }

  }

 Output:-- Static block1
                  Static block2
                  Value of a is 20

Example 3:-- Static blocks are executed before constructors.

                     public class StaticBlk {
                            static int a;
                            static {
                                    System.out.println("Static block"); 
                            }
                            public StaticBlk{
                                   System.out.println("This is constructor");
                            }
                            public static void main(String[] args){
                                     StaticBlk sb = new StaticBlk();
                            }
                     }
Output:-- Static block
               This is constructor

3) Static methods :--


             It is a method which belongs to the class not to the object. It can access only the static data.
Static method can call only other static methods not a non static methods. and it can not refer to "this" and "super" keywords anywhere.

Example:--
                        public class StaticMethod {
                                  public static void display () {
                                           System.out.println("static method");
                                  }
                                  public void disp () {
                                           System.out.println("non static method");
                                  }
                                  public static void main (String[] args) {
                                           display();    //calling without object
                                           StaticMethod obj = new StaticMethod();
                                           obj.disp(); //calling using object
                                  }
                        }
Output:-- static method
               non static method

4) Static Nested Class:--

               Nested static class is another class which is declared inside a class as a member and made static. Nested static class is also declared as member of outer class and can be  make private, public or protected like any other member. One of the main benefit of the nested static class over inner class is that instance of the static class is not attached to any enclosing instance of Outer class.

Example:
                    public class NestedClassEx {
                             private static class NestedClass {
                                       public void print () {
                                               System.out.println("Static nested class example");
                                       }
                            }
                            public static void main (String[] args) {
                                      NestedClass nc = new NestedClass();
                                      nc.print();
                            }
                    }
 Output:-- Static nested class example


Note:-- Constant variable name should be in Caps. you can use (_) in between.

Questions and answers:

1) Can we overload the static methods in Java?

         
         Yes, we can overload static methods in Java.

Example:--
                       public class StOverload {
                                 public static void display (String name) {
                                           System.out.println("Name "+name);
                                 } 
                                 public static void display (String name, int Id) {
                                           System.out.println("Name "+name+" Id "+Id);
                                 }
                                 public static void main (String[] args) {
                                            display("Anil");
                                            display("Anil" , 20);
                                 }
                       }
Output:--   Name Anil
                 Name Anil Id 20


2) Can we write main method as  static public void main(String[] args) ?

 
Yes, we can write main method like static public void main(String[] args){}.


3) What will happen if we remove the static keyword from the main method ?


No compilation error but will get run time error as "NoSuchMethodError".


 4) Can we override static methods in Java?
 

No, we can not override static methods in Java.

5) Why main method is static in Java?  

 
     Object is not required to call the static method, If it is non-static method then jvm create object first then call main() method that will lead the problem of extra memory allocation.



6) Which memory areas does instance and static variables use ?  

 
Instance variables stored in heap and static variables are stored in method area.

7) Can we serialize static variables ?

 
 No, Only object and it's members are serialized. Static variables are shared variables and doesn't correspond to a specific object.


8) What is a static import ?
    
     
         Static imports allow us to import all static fields and methods of the class, you can access them without class name reference.


9) Can we execute a program without  main() method?


     Yes, its possible in previous versions of java not in 1.7 using static block.

                      public class StaticBlockEx {
                             static {
                                    System.out.println("Static block invoked");
                                    System.exit(0);
                             }
                      }

Output :-- Static block invoked


Related Post:--
1) String Interview Questions and Answers
2) Factory Design Pattern in Java
3) Singleton Design Pattern in java with example
4) Difference between Loose Coupling and Tight Coupling in Java With Examples.
5) Internal implementation of ArrayList in Java
6) Java Vertual Machine(JVM) Architecture in Java