Summary

18 January 2012 By Nithya Vasudevan 238 views No Comment
0 Flares Twitter 0 Facebook 0 Google+ 0 0 Flares ×
  1. Static keyword can be applied to instance variable, instance method and inner classes.
  2. There is only one copy of static variable and all objects share them.
  3. Static variables are loaded and initialized when the class is loaded.
  4. class StaticDemo {
        static int a=0;
        int b=++a;
        static int c=++a;
        public static void main(String[] args){
             System.out.print(c);
        }
    }
    

    The output of the above code would be 1. When the class is loaded, variable ‘a’ would be initialized to 0 and the value is incremented and stored in variable ‘c’.

  5. Static variable are also called as static fields, class variables.
  6. Static applied with final becomes constant field. The naming convention of a constant is all uppercase and more than one word separated by underscore (_)
  7. public static final double PI = 3.14;
  8. Static method cannot access non-static (instance) methods.
  9. Static method cannot access non-static (instance) variables.
  10. package com.ibytecode.keywords.staticdemo;
    public class Student {
    	private String name;
    	int id;
    	public static void main(String[] args) {
    		System.out.println("Number of Students created: " + id);//ERROR
    	}
    }
    
  11. Static method can only access static methods and variables.
  12. A common use of static methods is to access static fields
  13. Static method cannot use this or super keyword in any way.
  14. Sub class will not inherit super-class’s static members.
  15. If you wish to access a static member (method/variable) from outside its class, you can do so using dot operator on class name.
  16. className.method( )
    or
    className.variable

    When we give the command ,
    java Hello
    to run our program, JVM calls Hello.main() to start our program execution. main() is declared static because otherwise JVM will not be able to instantiate the class due to ambiguity in calling and passing arguments to the constructor and that’s the reason main() method has static in its method signature.

Tags: ,