- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 variable
The static keyword is used to create variables that will exist independently of any instances created for the class. Only one copy of the static variable exists regardless of the number of instances of the class.
Static variables are also known as class variables. Local variables cannot be declared static.
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
- What is static blank final variable in Java?
- How to access Static variable of Outer class from Static Inner class in java?
- Can we declare a static variable within a method in java?
- What is blank final variable? What are Static blank final variables in Java?
- Why Java wouldn't allow initialization of static final variable in a constructor?
- Why we can't initialize static final variable in try/catch block in java?
- Where and how to use static variable in swift?
- Can a Java array be declared as a static field, local variable or a method parameter?
- Java static keyword
- Java static method
- Java static block
- Difference between static, auto, global and local variable in C++
- Static class in Java
- Static variables in Java
- static Keyword in Java

Advertisements