What is static in Java

Static methods

The methods that a class definition has will be static methods called. (You also will be Class methods called. A static method is a characteristic of the class, not of the objects that created it.

Important:A program can execute a static method without creating an object first! All other methods (those that are not static) must be part of an object. An object must exist before they can be executed.

Here is the sample program again:

// The file StringTester.java // class StringTester {public static void main (String [] args) {String str; // str is a variable that designates an object, // but the object does not yet exist. int length; // length is a primitive variable of type int str = new String ("Random Notes"); // create an object of the type string length = str.length (); // Calling the method length () of the object str System.out.println ("The string is" + length + "characters long"); }}

The application is comparable to many that you have seen so far. But now you can do more Details understand of what is going on. Assume that a file named contains the source code above.

  • The file defines a class with the name .
  • The class has one static methodthat is called.
  • There one static method is, she is a Characteristic of the class. Objects of the class have no method.
    • Since it is a static method, there is only one method.
  • After the file has been compiled, the generated bytecode is replaced by the Virtual machine (VM) run by Java.
    • The user executes the program by typing.
  • The Virtual machine of Java looks for the method in the bytecode version of the class definition of.
    • At this point in time there are no objects.
  • The method begins to start creates an objectby using it, calls the method and gets the stuff done.

Think of the idea of object-oriented Programming: An application consists of a collection of cooperative software objects whose methods are executed in a certain order in order to do something useful. The above steps describe how to get the collection of objects up and running. (In this case only one object was created.)


For example, suppose you create a file that contains a class definition, but the class does not contain a method. Can the methods of this class ever be executed?