Static Method in Java
Static Method
- By declaring a method using the static keyword, you can call it without first creating an object because it becomes a class method (i.e. a method that belongs to a class rather than an object).
- Static methods are used for methods that do not need to access to an object's state or only use static fields. For example, the main method is a static method.
- It is the starting point for a Java application and does not need to access an object's state. In fact, there aren't any objects created at this point. Any parameters that it needs can be passed as a String array.
Learn Java - Java tutorial - Static Method in Java - Java examples - Java programs
How do you call a static method ?
- If a method (static or instance) is called from another class, something must be given before the method name to specify the class where the method is defined.
- For instance methods, this is the object that the method will access. For static methods, the class name should be specified.
What is static method in Java with example ?
- Static method in Java is a method which belongs to the class and not to the object.
- A static method can access only static data. It is a method which belongs to the class and not to the object(instance) A static method can access only staticdata. It can not access non-static data (instance variables)
Syntax:
Static method main is accessing static variables without object
Sample Code
Output
Static method accessed directly in static and non-static method
Sample Code
Output
What is the use of static method ?
- If you apply static keyword with any method, it is known as static method. A static method belongs to the class rather than object of a class.
- A static method invoked without the need for creating an instance of a class. static method can access static data member and can change the value of it.