- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java static method
The static keyword is used to create methods that will exist independently of any instances created for the class.
Static methods do not use any instance variables of any object of the class they are defined in. Static methods take all the data from parameters and compute something from those parameters, with no reference to variables.
Class variables and methods can be accessed using the class name followed by a dot and the name of the variable or method.
Example
The static modifier is used to create class methods and variables, as in the following example −
public class InstanceCounter { private static int numInstances = 0; protected static int getCount() { return numInstances; } private static void addInstance() { numInstances++; } InstanceCounter() { InstanceCounter.addInstance(); } public static void main(String[] arguments) { System.out.println("Starting with " + InstanceCounter.getCount() + " instances"); for (int i = 0; i < 500; ++i) { new InstanceCounter(); } System.out.println("Created " + InstanceCounter.getCount() + " instances"); } }
Output
Started with 0 instances Created 500 instances
- Related Articles
- Are values returned by static method are static in java?
- Static method in Interface in Java
- Default method vs static method in an interface in Java?
- Why main() method must be static in java?
- Can we override the static method in Java?
- How to call a non-static method of an abstract class from a static method in java?
- Why the main () method in Java is always static?
- Static vs. Non-Static method in C#
- Can we overload or override a static method in Java?
- Can we call Superclass’s static method from subclass in Java?
- Can We declare main() method as Non-Static in java?
- Why can't static method be abstract in Java?
- Can we override a private or static method in Java
- Difference between default and static interface method in Java 8.
- What are the restrictions imposed on a static method or a static block of code in java?

Advertisements