Java Static

Java Static Variables

  • Java instance variables are given separate memory for storage. If there is a need for a variable to be common to all the objects of a single java class, then the static modifier should be used in the variable declaration.
  • Any java object that belongs to that class can modify its static variables.
  • Also, an instance is not a must to modify the static variable and it can be accessed using the java class directly.
  • Static variables can be accessed by java instance methods also.
  • When the value of a constant is known at compile time it is declared ‘final’ using the ‘static’ keyword.

Java Static Methods

  • Similar to static variables, java static methods are also common to classes and not tied to a java instance.
  • Good practice in java is that, static methods should be invoked with using the class name though it can be invoked using an object. ClassName.methodName(arguments) or objectName.methodName(arguments)
  • General use for java static methods is to access static fields.
  • Static methods can be accessed by java instance methods.
  • Java static methods cannot access instance variables or instance methods directly.
  • Java static methods cannot use the ‘this’ keyword.

Java Static Classes

  • For java classes, only an inner class can be declared using the static modifier.
  • For java a static inner class it does not mean that, all their members are static. These are called nested static classes in java.

This Core Java tutorial was added on 13/05/2008.

previous post: Difference between static and non-static java inner class.

next post: JSP Comments

72 comments on “Java Static

  1. Pingback: What is a static import in java?

  2. Good, concise answer.

    But, I would want one more thing to be added to it:
    Static methods can’t be overridden, which implies they are final methods. Rather, the concept of overridden itself should never arise because static methods are part of a class and not of an object.

    But, because of the notation we abuse by writing obj.staticMethod(), people generally get confused.

    Thanks,

  3. hi…!

    If you would use static methods and fields only, you would end up programming procedural like you would do with C or Pascal, loosing all the benefits of oop..so static method is used only when required and instance method is used elsewhere to get the benefit of oop.

  4. nice tutorial good job

      • STATIC can be:
        Variable.
        Method.
        Block.
        Nested class.
        Non object.
        static keyword.
        this and super cannot be used in static context.

  5. It is a nice website
    very helpful website
    thanks alot

  6. Pingback: How many types of java variables are there?

  7. Pingback: Java (JVM) Memory Types

  8. A good tutorial !
    Thanks for sharing.

  9. Pingback: Java Double Brace Initialization

  10. Thanks to whomsoever it may concern..This is a good material,which seemed to be useful to me.

  11. it is not clearly, please provide full information with example

  12. Pingback: Java this Keyword

  13. @Anonymous:i cannot understand your point ll u please explain it

    thanks

    no access modifier – Subclasses in other package wont allow.

    But in protected will can be accessed subclasses in another pacakge.
    Anonymous on October 14th, 2010 12:47 pm

  14. By last point in java Instance Variables

    When the ” value of a constant is known at compile time ” it is declared ‘final’ using the ‘static’ keyword.

    i would like to ask one thing according to double quotes
    there are how many to give a value to a variable or a Constant
    1. Compile time
    2….
    3…

    there are how many possible ways?
    thanks

  15. what about this
    Class A{//something here}
    public Class B{
    static A obj= new A(); // a static object to //class

    ****
    can you explain this how this works?

  16. Pingback: Java Keyword & Some Important Notes « Java World

  17. Hi Joe,

    I have doubt about Static.

    When we go for static and why we need static? In which situation we need to go for static.?.

    Thanks a lot for your Great work. your blog helped me to clear all level interview.

  18. Hi Kannan,

    Static are basically class variable, they are not stored on the heap but in the special area called method area, unlike object which when allocated occupied area in heap.

    Static variable are loaded just once when the class is loaded by the JVM at the same time static variable is also created. So all the content which will be common to all the method and object are stored as static variable.

  19. Pingback: ThreadLocal

  20. what is the difference between class variable and static variable ?

  21. Pingback: System.out.println

  22. Hi Joe,

    I am a Java newbie. This page is very helpful.

    The question I have is about Static Methods is…..’Java static methods cannot access instance variables or instance methods directly.’

    Why in the Main() method which is a Static Method, we can access other methods (part of that class) that are not defined as Static?

  23. static methods can only call other static methods/access static data …
    [Complete Java Reference Ed2 Pg176]
    But main is static, in which we call all static and non static methods.
    How come?

  24. hi joe,

    can you explain about auto boxing&un boxing concept?

  25. Java instance variables & methods are given separate memory for storage.what is the name for such type of specified memory

  26. class PRO15
    {
    public static void main(String[] args)
    {
    static int i=10;
    static int j=i;
    System.out.println(i);
    System.out.println(j);
    }
    }

    why static method can’t be define in main??

    • As the java rules says that local variables can not be declared as static
      so i,j are local inside main so it is error. If local variables are static they can not be shared among objects as it is not available in heap area where instance variables are stored.

      • if the local variable is declared as static then it will be stored in the method area is what i have understood. in that case all the objects can access it.This contradicts your explanation.Please sort my doubt

  27. 1.As we know main method is static in java and there is some restriction for static keyword
    2.static methods can call static methods and static variables only
    3.so my question is this how main method can access the class variables and methods as they are not static

  28. To Shilpi Agrawal,
    As joe have written above that. staic method cannot invoke the instance method directly.. but it can invoked by creating an object of the class and then using . operator to invoke the method of the object created

  29. please write some examples also that we can better understand the concepts….

  30. sir we want u to explain the examples with coding b’coz we r the beginners in java…

  31. You have mention all kind of terms very beautiful but I need example with coding so that I can explain very well. I am beginners in java.

  32. Pingback: How to call a C program from Java?

  33. Can you please explan to me one real time scenario.Means where i want to use static variables.

    • When there is a requirement that all the instances of a class must have a common data with same value then we should declare static variable instead of instance variable as a single memory is available for static variables and can be shared among all the instances instead of multiple copy of variables as that of instance variables.

      • Mr Nanda
        I understand your explanation here and it’s well put.But don’t you think the question lies partially unanswered? Can you give a real life instance where static variables would be useful? it’s oop after all.

  34. Hey, You wrong buddy:

    1)Using Instances or Obects you can’t access static variables and metods in Java.

    2)To access the static variables and methods, you can do this by using (Classname.method/variable) or can directly access the method or variable without using the Classname.

    3)You also stated “Static methods can be accessed by java instance methods.”
    Yaa, here I agree, but what is the use and utility then , one example is below:

    public class C {
    static String a[] = { “2″, “3″ };

    public static void method() {
    System.out.println(“Welcome to Java”);
    }

    public void met() {
    C.method();
    }

    public static void main(String[] args) {

    C c1 = new C();
    c1.met();
    }

    }

    Please Reply for this.

  35. For my 1st point.. is appended in the last ” directly by . operator”).

  36. For the 3rd point , we can do this directly using class name , right.

  37. What is the basic difference between usage of static and final?

    • if we declare a variable as static that means multiple instance of a class has to share a single variable but the value of the variable can be changed. If we declare a variable as final its value can not be changed i.e it becomes a constant. One important difference is that local variables can be final but not static.

  38. can you include the example code for static

    • class A{
      private static int x=10;//static
      private int y=20;//instance
      public static void main(String[] args){
      A a1=new A();
      A a2=new A();
      a2.y=200;
      System.out.println(a1.y);//20
      System.out.println(a2.y);//200
      a1.x=500;
      System.out.println(a1.x);//500
      System.out.println(a2.x);//500
      }//main()
      }//class
      As static variables are shared among all the objects where as each object is having their separate copy of instance variable .

  39. Very good website.. nice job.. keep helping .. :)

  40. Thanks for this info joe……but why static methods are used????…can you please give me an example…thanks

    • If we declare methods as static no need of creating object of that class methods can be directly called by class name. Good example is our main() method it is static so it is directly called on the class by jvm.
      class A{
      p s v m(String[] args){

      }
      }
      while executing we ar writing in cmd as
      java A
      but actually it is
      java A.main()

  41. Nice article…
    Please mention about static block also.
    That is the only thing remaining in this description on static…

  42. class Amit{
    static {
    System.out.println(“This java program has run without the main method”);}
    public static void main(String args[])
    {}
    }
    Explain me this static() method.
    Thanx

  43. In order to use the class, that class should be available inside a memory ?

  44. Mayuresh said on 07/02/2013,

    Nice article…
    Please mention about static block also.
    That is the only thing remaining in this description on static…

  45. what is static modifiers with program plz upload

  46. Hi Joe,
    Could you please explain the need of having static classes? This question popped up when I had gone through implementation of LinkedList in java. It uses static class, I tried to create code similar to it without static nested class, still it is working. So I am puzzled with the usage of static nested classes.

  47. Hi,

    Good post, I think we are missing the explanation for static blocks of code.

  48. Why do we use Static methods at all when we can do the same thing with instance methods.For the argument that static methods declared final cannot be changed so can be the instance variable declared as final.Presuming that the static method can be used by a single object at any instance wouldn’t it be beneficial to create an instance method instead which can be instantiated any number of times and can be used by any number of objects.This would improve the performance as well.And for the argument that latter may create more objects there’s garbage collector for our help.

  49. can u give me full detailed explanation for static keyword

  50. Pingback: Java Class Loader

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>