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" Tutorial:

  1. […] coming to the static import part. Like the above ugly line we have been unknowingly using (abusing) the java static […]

  2. Aatish says:

    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. Virat Gandhi says:

    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. java tutorial for beginners says:

    nice tutorial good job

  5. Anonymous says:

    It is a nice website
    very helpful website
    thanks alot

  6. […] Instance Variable Java variables that are declared without static keyword are instance […]

  7. […] As given in the last line, method area is part of non-heap memory. It stores per-class structures, code for methods and constructors. Per-class structure means runtime constants and static fields. […]

  8. Tri Nguyen Minh says:

    A good tutorial !
    Thanks for sharing.

  9. […] initialization block. That too you have seen in it a class for initialization. You may have used a static initialization block. When you use the initialization block for an anonymous inner class it becomes […]

  10. Ronak says:

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

  11. raghavareddy says:

    it is not clearly, please provide full information with example

  12. […] To specifically denote that the instance variable is used instead of static or local variable.That […]

  13. Muhammad Waqas says:

    @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. Muhammad Waqas says:

    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. Muhammad Waqas says:

    what are static fields

  16. harry says:

    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?

  17. indian says:

    nice one

  18. Kannan says:

    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.

  19. Shazz says:

    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.

  20. Joe says:

    Shazz, thanks for replying to users questions.

  21. ThreadLocal says:

    […] global access. It can be accessed from anywhere inside the thread. Also note that, it is declared static and […]

  22. mcajavaprogramer says:

    what is the difference between class variable and static variable ?

  23. […] a final class and cannot be instantiated. Therefore all its memebers (fields and methods) will be static and we understand that it is an utility class. As per javadoc, “…Among the facilities […]

  24. VJ says:

    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?

  25. Raj says:

    This was Very Useful

  26. Renjith says:

    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?

  27. rajesh says:

    hi joe,

    can you explain about auto boxing&un boxing concept?

  28. Jyotish says:

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

  29. shubham singh says:

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

  30. Shilpi Agrawal says:

    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

  31. vignesh says:

    very nice

  32. Taslim says:

    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

  33. Anonymous says:

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

  34. guru mani says:

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

  35. Vipul Aniya says:

    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.

  36. […] the library HelloWorld using static keyword. This library file will be compiled out of the C source in the coming […]

  37. Raghava says:

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

  38. Anonymous says:

    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.

  39. Anonymous says:

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

  40. Anonymous says:

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

  41. Anonymous says:

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

  42. Anonymous says:

    explain with simple exampe pls

  43. Ram Ramachandran says:

    can you include the example code for static

  44. Naulehshraj says:

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

  45. Naulehshraj says:

    thank a lot for this website …..

  46. Harjinder says:

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

  47. sumeet123 says:

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

  48. Binayak Nanda says:

    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.

  49. Binayak Nanda says:

    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.

  50. Binayak Nanda says:

    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.

  51. Binayak Nanda says:

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

  52. Binayak Nanda says:

    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 .

  53. amy says:

    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

  54. Mayuresh says:

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

  55. Amit says:

    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

  56. Sanjeev says:

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

  57. Anonymous says:

    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…

  58. Anonymous says:

    what is static modifiers with program plz upload

  59. Anonymous says:

    ur answers are not statisfied for me

  60. Neha Arora says:

    Gud..nice tutorial..

  61. Skanda says:

    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.

  62. Anonymous says:

    it is really very helpful…

  63. Harsha says:

    Hi,

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

  64. Anonymous says:

    more information plz………….

  65. Anonymous says:

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

  66. Shiv says:

    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.

  67. Sumeda says:

    useful post
    Thanks

  68. raj says:

    can u give me full detailed explanation for static keyword

  69. […] file is compiled to a binary class, compiler inserts a field into java class file. It is a public static final field named ‘class’ of type […]

  70. nolan says:

    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.

  71. Anonymous says:

    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

  72. hemanth says:

    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

Comments are closed for this "Java Static" tutorial.

↑ Go to top