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.

«

»

Comments on “Java Static”

  1. Aatish

    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,

  2. Virat Gandhi

    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.

  3. java tutorial for beginners

    nice tutorial good job

  4. Anonymous

    It is a nice website
    very helpful website
    thanks alot

  5. Tri Nguyen Minh

    A good tutorial !
    Thanks for sharing.

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

  7. raghavareddy

    it is not clearly, please provide full information with example

  8. Muhammad Waqas

    @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

  9. Muhammad Waqas

    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

  10. Muhammad Waqas

    what are static fields

  11. harry

    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?

  12. Kannan

    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.

  13. Shazz

    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.

  14. mcajavaprogramer

    what is the difference between class variable and static variable ?

  15. VJ

    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?

  16. Raj

    This was Very Useful

  17. Renjith

    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?

  18. rajesh

    hi joe,

    can you explain about auto boxing&un boxing concept?

  19. Jyotish

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

  20. shubham singh

    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??

    • Binayak Nanda

      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.

      • amy

        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

  21. Shilpi Agrawal

    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

  22. vignesh

    very nice

  23. Taslim

    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

  24. Anonymous

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

  25. guru mani

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

  26. Vipul Aniya

    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.

  27. Raghava

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

    • Binayak Nanda

      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.

      • nolan

        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.

  28. Anonymous

    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.

  29. Anonymous

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

  30. Anonymous

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

  31. Anonymous

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

    • Binayak Nanda

      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.

  32. Anonymous

    explain with simple exampe pls

  33. Ram Ramachandran

    can you include the example code for static

    • Binayak Nanda

      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 .

  34. very-very…..good site for java teaching …..

  35. thank a lot for this website …..

  36. Harjinder

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

  37. sumeet123

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

    • Binayak Nanda

      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()

  38. Mayuresh

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

  39. Amit

    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

  40. Sanjeev

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

  41. Anonymous

    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…

  42. Anonymous

    what is static modifiers with program plz upload

  43. Anonymous

    ur answers are not statisfied for me

  44. Neha Arora

    Gud..nice tutorial..

  45. Skanda

    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.

  46. it is really very helpful…

  47. Harsha

    Hi,

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

  48. Shiv

    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. Sumeda

    useful post
    Thanks

  50. raj

    can u give me full detailed explanation for static keyword

  51. Anonymous

    static members will be executed at the tile of loading byte code of a class and will fallow the execution order which we have given in the class

  52. hemanth

    static members will be executed at the time of loading byte code of a class and will fallow the execution order which we have given in the class

Your Comment