In Java, the "static" keyword is used to declare members (variables and methods) that belong to the class itself, rather than to individual instances (objects) of the class.
When a member is declared as "static", it is shared by all instances of the class and can be accessed directly using the class name, without the need to create an instance of the class.
Here's how the static keyword is used:
A static variable, also known as a class variable, is a variable that belongs to the class itself rather than to instances of the class.
Static variables are declared using the static keyword and are initialized only once when the class is loaded into memory.
All instances of the class share the same copy of the static variable.
public class YourClass { // Static variable public static int count = 0; // Other members of the class... }
public class YourClass { // Static method public static void printMessage() { System.out.println("Hello, world!"); } // Other members of the class... }
A static method, also known as a class method, is a method that belongs to the class itself rather than to instances of the class.
Static methods are declared using the static keyword and can be called directly using the class name, without creating an instance of the class.
Static methods cannot access instance variables directly because they do not operate on any specific instance of the class.
public class YourClass { // Static variable public static int count; // Static block static { count = 0; System.out.println("Static block executed."); } // Other members of the class... }
A "static" block is a block of code enclosed within curly braces "{}" and preceded by the "static" keyword.
It is executed only once when the class is loaded into memory before any "static" variables or methods are accessed.
"Static" blocks are typically used to initialize "static" variables or perform other initialization tasks.
The "static" keyword in Java provides a way to define members that are shared among all instances of a class, allowing for efficient memory usage and facilitating the organization and management of class-level data and behaviour.
However, it's important to use "static" variables and methods judiciously, as they can lead to tight coupling and reduced flexibility in certain scenarios.