Category: java
what is static in java
Published on 04 May 2026
Explanation
In Java, 'static' is a keyword used
for memory management. It is used for
variables, methods, blocks, and
nested classes. A
static member belongs to the class rather
than an instance, meaning it is shared
among all objects of that class.
Code:
class Test {
static int count = 0;
Test() {
count++;
System.out.println(count);
}
}
Explanation
Static variables are shared across all
instances
of a class. They are commonly used
for constants or shared counters.
Code:
class Company {
static String companyName = "TechCorp";
}
Explanation
Static methods can be called without
creating
an object of the class. They are
often used for utility or helper functions.
Code:
class MathUtils {
static int add(int a, int b) {
return a + b;
}
}
// Usage
int result = MathUtils.add(5, 3);
Explanation
Real-time usage: Static is widely used in
real-world applications like utility
classes (e.g., Math
class), configuration settings,
logging, and singleton design
patterns where a single shared
instance or
behavior is required.
Code:
class Logger {
static void log(String message) {
System.out.println(message);
}
}
Logger.log("Application started");
Explanation
Static blocks are used for initialization of
static variables and are executed only once
when the class is loaded.
Code:
class Config {
static int value;
static {
value = 100;
System.out.println("
Static block executed");
}
}