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.

25 Responses to “What do you mean by static in Java?”

  1. pepestudios Says:

    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. aradhana singh Says:

    you didn’t decleared the main meaning of static?

  3. aradhana singh Says:

    so plz declear it immeadetly….

  4. Blink Says:

    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.");
    
  5. Demonray Says:

    Why is main static in java?

  6. Blink Says:

    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.

  7. Stephen Akandwanaho Says:

    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.

  8. Blink Says:

    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.
    :-)

  9. sankar Says:

    what is static in java?

  10. ghanashaym Says:

    can we overwrite main()

  11. ghanashaym Says:

    what is the difference between interface and abstract class

  12. Prathyush Says:

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

  13. Sameer Says:

    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

  14. Nitesh Hissaria Says:

    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.

  15. ramana Says:

    very nice and thank you

  16. Sarvesh Narayan Says:

    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?

  17. meyya Says:

    good effort .

  18. kenneth Says:

    good job. thanks guys!

  19. Chithra Says:

    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.

  20. Deepa Jalistgi Says:

    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.

  21. Bashed Sarker Says:

    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.

  22. Suriya Says:

    Really useful

  23. Kalpana Says:

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


Leave a Reply