What do you mean by static in Java?

When I was learning Java, I always get confused what static variables and static methods mean. I read a lot of books explaining static and still it’s not clear to me. Let’s consider the “Hello World” class and program in Java.

// HelloWorld.java
public class HelloWorld {
	public static void main (String args[]) {
		System.out.println ("Hello World!");
	}
}

and consider the following class,

// HelloWorld.java
public class HelloWorld {
	public void main (String args[]) {
		System.out.println ("Hello World!");
	}
}

Are these two classes the same?  Of course, they are not the same. The first class has a static keyword in its main method and the other one is simply a method without this keyword static.As always Java follows this signature in the first class. And we consider this as a complete and a running program in Java. The static main method means that all objects created out from this class has only one method main. And you can call main method without instantiating the class and directly invoke this method with the name of the class (HelloWorld.main()).All instance variables and methods of the class that are declared as static are global variables or global methods. And we can call them directly without creating an object from a class by putting it’s class name in front of a variable and a method name in between the dot operator.Let’s consider a class counter example. We define a class, Song, and define the global variable count that increments every time we create an instance of the class, Song.

// Song.java
public class Song {
	private String title;
	// global variable
	public static int count;

	public Song (String title) {
		this.title = title;
		// Increment class variable count every time song is created.
		Song.count++;
	}

	public String toString () {
		return title;
	}
}

// SongDriver.java
public class SongDriver {
	public static void main (String args[]) {
		Song hello = new Song ("Hello");
		System.out.print ("Song " + Song.count + ": ");
		System.out.println (hello);
		Song elMundo = new Song ("El Mundo");
		System.out.print ("Song " + Song.count + ": ");
		System.out.println (elMundo);
	}
}

The program simply increments count when the hello object is created. And it increments again when elMundo is created. And we display the value of count by invoking count with it’s class name, Song.count.Therefore, when we say static, it is global and we can also call them class variable or class methods.

About these ads

72 responses »

  1. Some important things to note on Java’s static modifier:
    1. Sometimes its not safe to use static functions or variables on a multi-threaded java program. This is because static functions and variables are made global. Thus java threads should at least need to provide mutex for these functions and variables.

    2. Static variables and functions are inherited but not in a strong sense as how instance variables and functions are. At runtime you may explicitly call a function or reference a variable from the heirarchy of classes that inherited and overriden it. For example, there is a base class called Animal with a static member variable called eat(). A class called Snake is subclassed from class Animal and it also overrides function eat(). At runtime you may call Animal.eat() to get the base class’s eat() function and Snake.eat() to Snake class’s eat function. See the difference? If eat() is not static you can’t explicitly call eat(), you need to instantiate an object to access it. Calling eat() from a Snake object will call the overriden eat() function if eat is not static.

    3. Java’s static modifier may also declare static nested classes. Wherein these classes(inner class) are declared inside a class(enclosing class) without having a relationship with the enclosing class.

  2. If the member variables and methods of a class are static, meaning, all objects that are instance of that class shares that variables and methods. And those static variables and methods can be used or invoked without instantiating that class that where they belonged. They can be invoked using the class name (dot) variable or method.

    Consider the following example:

    Song s1 =new Song ("s1");
    Song s2 =new Song ("s2");
    Song s3 =new Song ("s3");
    Song s4 =new Song ("s4");
    
    System.out.println ("There are " + Song.count + " created.");
    
    • In java main is declared as a static becoz object is created from main method and we have to need the object before calling main method so here we have problem how jvm call to the main now static keyword tell the jvm you have not need the object to call main method instead of you can call main ClassName.main() so here jvm can call without creating any object of the class.

  3. main() is a special method in Java where your program basically start. It should always static because all instantiated objects out from a class should have always only one method. They all shares one main method because it will not have different main to be executed.

    • but without main programme also execute

      like–
      class jaim
      {
      static
      {
      System.out.println(“hiii”);
      }

      }
      but it gives runtime error
      but one way that u run this programme without runtime error

      class
      {
      static
      {
      System.out.println(“hiii”);
      System.exit();
      }
      }

      that means programme first check static block then after goes to main method.

  4. In the context of JAVA, static means Unique. You can not have two main methods in a program( I think), It is unique to that particular program. Actually, at this point of the program, it’s where the execution starts.

  5. You are right Stephen. static could also mean UNIQUE because every class will shares it. And also, there should always be one and only main method. But I think, main as identifier is not reserved. I tried it once in a variable identifier. :-)

    • Yes you are right blink. Main is just a general terminology(or a identifier, we can say) to indicate the method which has to be executed first.

  6. Any static element in java signifies that its public within that class .. its global .. hence it has to be unizque

  7. This Java programming example will teach you the way to define a static methods. In java we have two types of methods, instance methods and static methods. Static methods can’t use any instance variables. The this keyword can’t be used in a static methods. You can find it difficult to understand when to use a static method and when not to use. If you have a better understanding of the instance methods and static methods then you can know where to use instance method and static method.

    A static method can be accessed without creating an instance of the class. If you try to use a non-static method and variable defined in this class then the compiler will say that non-static variable or method cannot be referenced from a static context. Static method can call only other static methods and static variables defined in the class.

    The concept of static method will get more clear after this program. First of all create a class HowToAccessStaticMethod. Now define two variables in it, one is instance variable and other is class variable. Make one static method named staticMethod() and second named as nonStaticMethod(). Now try to call both the method without constructing a object of the class. You will find that only static method can be called this way.

    The code of the program is given below:
    public class HowToAccessStaticMethod{
    int i;
    static int j;
    public static void staticMethod(){
    System.out.println(“you can access a static method this way”);
    }
    public void nonStaticMethod(){
    i=100;
    j=1000;
    System.out.println(“Don’t try to access a non static method”);
    }
    public static void main(String[] args) {
    //i=100;

    j=1000;
    //nonStaticMethod();
    staticMethod();
    }
    }

    Output of the program is given below:
    C:\java>java HowToAccessStaticMethod
    you can access a static method this way

  8. You can define a variable in a class ( outside from all methods) but it has to be static..

    Class a
    {
    static int i;
    }
    By default, the value assigned to int is 0 and to string is null.

    You can not define a static variable inside a method and a simple variable can’t be used without initialization.

  9. Hi Buddy,

    Do u know, what is the greatest advantage of working in java that i have experienced?. In java, each and every word/keyword is self explanatory I mean if you u analyze any keyword of java for few minutes you can understand what could be the use of that keyword in java even you r new in this tech. For example static mean sth that should be fixed or unchanged but this is in term of memory. Means static keyword has privileged of being one and only one in memory rather you have create uncountable instances of a class, So it becomes instance free i.e. you would not be dependable on instance. However you can access it any where and can be changed by any instance but memory space will not vary.

    any remark?

  10. Hi all,
    I was searching some thing and happen to visit this forum. I have to tell you all that what ever written above on static is completely correct.

    Let me explain you.
    1) Its mentioned that static is unique. Its right. But unique doesnt mean that you cannot have two same static methods. In java you can never can have two methods [static/non static] with same signature.

    By unique it means the static variable,block or method is been shared across. When you make more than one object for class , normally each object will have a reference for eah method/variable. But if its static it is shared across all. So if obj1 change the value of a static varible and if we try to print the value thr obj2 — it will print the modified value.

    2) Static variable/method/block exist even before the class exist. Means variable/method/block has life before a call to new Class ().and that’s why we access the static variable as ClassName.variableName.

    3)We cannot use this in static method because this means the current instance of class. But as static method has got life before the class even exist, we cannot use this. More clearly this means current object [new ClassName()], but for accessing static we use ClassName.method nt thr an object, So this/object doesnt exist.

    4) This means the method is part of its class and not part of objects.

    5) On the point : You can not define a static variable inside a method and a simple variable can’t be used without initialization. –> a local variable inside a method can have only final as specifier. We cannot declare static because a method exist through object only but a static variable will exist long before an object exist.

    Hope these point help you all.

  11. hi
    I’m Deepa here i want to know about public static void main(String[] a).Please explain each key word and why they are using java.

  12. Public:
    public is a keyword that is used from every class and here public used because main()method is used any class.
    Static:
    Static is also Keyword “static” is used in without object method. here main()method has no any object.so that without method must be use static Keyword.
    Void:
    “Void” is Return type keyWord. do u understand “Return type”? any method want to return any value but main()method can not return value.sothat main()method must be use void Keyword.
    String:
    “String args[]” is a String type array argument which we can pass string Argument.

  13. I searched in many websites but didn’t get clear idea. This is a clear explanation about “static”. Very useful. Thanks a lot.

  14. wow. all of a sudden I understand it completely. After spending months and months on Java courses and not really “getting” the idea behind ‘static’.

    very very impressive. Mayor compliments!

  15. Thanks all of your information . Every of the comments is so informative to everybody that hasn’t known the meaning of any word .

    Thanks Sincerely,

  16. So… in short, it seems that static means that the value will carry through multiple instance of an object. As you can count the number of instances with your Song example.

  17. 1.Every function or method which is written inside in a class of a java program can be called by its object name .

    2.so ,since main is also a method which is wrritten inside the class , has to be called by its object name.

    3.In order to call the main function ,we need to create an object(for main function) first.say suppose if we created an object(for main function) in the main function itself,

    4.But,actually every java program execution starts with main so we can cannot call the main function by its object name (main),why bcoz we created an object for main inside the main function,mainfuction looks for an object and object looks for main both to execute
    viceversa which is impossible.

    5.so,wat java people is recommending u is that the main function can be called by inserting the keyword “static” before the main

    ie public static void main(string args[])

    6.so,finally static is the key word which is used to call the main function on the class name but not by its object name,in order to execute our java program .

    7.It is the job of the class loader which is reside in the jvm tells to the system,in which it loads the class file which includes the main fuction ,so atlast our java program gets executed.

    with love,
    learner in java…
    GOPIKRISHNA.B

  18. well simply put yeah, static members have class scope while non static members have object scope. you cannot access a static member via an object of a class.

    • I am able to access a static member via object of class..
      See below code :

      class Monostate {
      private static String str = “Default”;
      public static String getString() {
      return str;
      }
      public void setString(String s) {
      str = s;
      }
      }

      public class StaticKeywordUsed {
      public static void main(String[] args) {
      Monostate obj1 = new Monostate();
      obj1.setString(“OBJECCT-1″);
      System.out.println(“1.0………”+obj1.getString());

      }
      }

      Compile the code.

      Thanks in advance

      ha ha ha

      Cheers,

  19. Here is source code to understand the “Static” keyword :
    if we make variable as ” static ” than they all share the same object.

    Just compile and see :
    1. compile with “Static”.
    2. Now remove “Static”

    class Monostate {
    private static String str = “Default”;
    public String getString() {
    return str;
    }
    public void setString(String s) {
    System.out.println(“1.2………”+str);
    str = s;
    System.out.println(“1.3………”+str);
    }
    }
    /*
    * Then you are free to create as many instances of the monostate as you like,
    * but they all share the same object due to the static reference.
    */
    public class StaticKeywordUsed {
    public static void main(String[] args) {
    Monostate obj1 = new Monostate();
    Monostate obj2 = new Monostate();
    obj1.setString(“OBJECCT-1″);
    obj2.setString(“OBJECCT-2″);
    System.out.println(“1.0………”+obj1.getString());
    System.out.println(“1.1………”+obj2.getString());
    }
    }

    Thanks in advance
    Cheers,

    • Order Of Execution Of Static

      1.Static Variables
      2.Static Block
      3.Static Method

      1.Static Block :Whenever you want to excute a code before execution of main mehtod, you can write a code using static block.

      2.Static Method: The Static Methods are also called as Class Methods.So that as we know Invoking a Static Method, by using class name also.(Most cases invoked by class name).

      3.Static Variable : Static Variable will have a single copy per class.

      or

      Static members are created purpose of get sharing.When a common value is existing in the the class.It is better to declare the member as static.

  20. >>All instance variables and methods of the class that are declared as static are global >>variables or global methods

    Just to be clear… They are not instance members if the are static… Instance members are only members that can be accessed by an instance of the type which is an object.

  21. Hello sir,
    whtat is meant by following statement ?
    static ClassName objcetName=new ClassName()
    What is the use of using static before ClassName?
    Could you help me?

  22. you said you can access the variables without the use of the object can someone brief me on objects and is it possible to use private static ? u said the static keyword is used to invoke the main method when compiling the program is it also that the classes that use static are invoked by the using the static keyword without referring to the object itself

  23. /*static is a java keyword
    * 1.when we want to a aceess class data without object we use it
    * 2.when they write simple java first progrm hello we use static
    * public static void main(String arg[])
    {
    System.out.println(“hello”);
    }
    *in this progrm we not requred a object bt run our progrm
    *there were 3 types are availble to declred static
    * 1.static variable
    * 2.static function
    * 3.static block
    * 1.static function=
    * syntex= static method name()
    * {
    * ,,,,,,
    * }
    * exmpl=
    * static void jaipal()
    * {
    * system.out.println(“hi jaipal singh Dungarpur”)
    * }
    * Rule=1.when we used Static function it should be declared globle variable static
    * 2.static key word write before declared method name
    * 3.to Acess static function on other class(outer class)
    * syntex= class name.function name
    * exmple= A.jaipal();
    ****point==using static word we acees method of class without object
    * they are able to acess to it via only class name
    *2.Static block===
    * syntex= static
    * {
    * ,,,,
    * }
    * exmple=
    * static
    * {
    * system.out.println(“hi jaipal singh dungarpur “)
    * }
    * why== 1. when we use static block it execute witout object
    * 2.when it execute it first lode
    */

    public class A
    {

    static int i; //Static variable
    static int j;

    static void jai() //static function(method 1)
    {
    System.out.println(i);
    System.out.println(i);
    }
    static void jai1() //static function(method 2)
    {
    i++;
    System.out.println(i);
    System.out.println(j);

    }
    static //static block “it lode first when progrm run”
    {
    System.out.println(“this is A exmpl of static”);
    }

    }

    public class B
    {
    public static void main(String arg[])
    {
    A.i=10;
    A.j=12;
    A.jai();
    A.jai1();
    }
    }

    try it it’s simple to understading static

  24. /* static is a java keyword
    * 1.when we want to a aceess class data without object we use it
    * 2.when they write simple java first progrm hello we use static
    * public static void main(String arg[])
    {
    System.out.println(“hello”);
    }
    * in this progrm we not requred a object bt run our progrm
    * there were 3 types are availble to declred static
    * 1.static variable
    * 2.static function
    * 3.static block
    * 1.static function=
    *
    *
    * syntex = static method name()
    * {
    * ,,,,,,
    * }
    * exmpl =
    * static void jaipal()
    * {
    * system.out.println(“hi jaipal singh Dungarpur”)
    * }
    * Rule=
    1.when we used Static function it should be declared globle variable
    static
    * 2.static key word write before declared method name
    * 3.to Acess static function on other class(outer class)

    * syntex= class name.function name
    * exmple= A.jaipal();

    ****point==

    using static word we acees method of class without object
    * they are able to acess to it via only class name

    *2.Static block===
    * syntex= static
    * {
    * ,,,,
    * }

    * exmple=
    * static
    * {
    * system.out.println(“hi jaipal singh dungarpur “)
    * }
    * why==
    1. when we use static block it execute witout object
    * 2.when it execute it first lode
    */

    //// program is start/////////

    public class A
    {

    static int i; //Static variable
    static int j;

    static void jai() //static function(method 1)
    {
    System.out.println(i);
    System.out.println(i);
    }
    static void jai1() //static function(method 2)
    {
    i++;
    System.out.println(i);
    System.out.println(j);

    }
    static //static block “it lode first when progrm run”
    {
    System.out.println(“this is A exmpl of static”);
    }

    //main classs//

    public class B
    {
    public static void main(String arg[])
    {
    A.i=10; //change value of local class static variable=i
    A.j=12; //change value of local class static variable=j
    A.jai(); //with out object & only help of class name& function name
    A.jai1();//& function name access method
    }
    }

    }

  25. public class Ap13 {

    Ap13() {
    System.out.println(“hello”);
    }

    {
    System.out.println(“how”);
    }
    static
    {
    System.out.println(“r u”);
    }

    }
    public static void main(String[] args) {
    Ap13 ob=new Ap13();

    }

    }

    what will output and why?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s