Static Keyword, Variables and Static Methods: C. Vybbhavee 23R11A0599
Static Keyword, Variables and Static Methods: C. Vybbhavee 23R11A0599
STATIC METHODS
C.Vybbhavee
23R11A0599
STATIC K EYWORD
• • Static variables are shared among all instances of a class, meaning they have a
single copy for all objects.
• • They are initialized only once, when the class is loaded, and retain their values
across all instances.
• • This feature makes static variables ideal for constants or settings that should
be consistent across all instances.
EX AMPLE PROGRAM FOR STATIC
VARIABLE S
class Example {
// Static variable
static int count = 0;
// Constructor to increment count
public Example() {
count++;
} // Static method to display the count
public static void displayCount() {
System.out.println("Count: " + count);
}
}
public class StaticDemo {
public static void main(String[] args) {
// Create two objects of the Example class
new Example();
new Example();
// Call the static method to display the count
Example.displayCount(); // Output: Count: 2
}}
STATIC METHODS
• • Static methods are functions that belong to the class itself and not to any
specific instance of the class.
• • They can access static variables and other static methods directly, but cannot
access instance variables or methods without an object reference.
• • Static methods are commonly used for utility functions that perform
operations without needing to modify instance data.
EX AMPLE PROGRAM FOR STATIC
METHODS