static keyword in Java. The static keyword is primarily used to define class-level members that belong to the class itself rather than to its instances. It can be applied to variables, methods, blocks, and nested classes. Proper use of the static keyword can also help optimize memory usage by allowing all instances of a class to share the same static members.1) Static variable :--
A static variable has the same value for all objects (instances) of a class. In other words, all instances of the same class share a single copy of a static variable. A static variable is created only once when the class is loaded into memory and is stored in the class area. Any changes made to the static variable by one object are visible to all other objects of that class.
public class StaticVar { int a = 0; public StaticVar() { a++; System.out.println(a); } public static void main(String[] args) { StaticVar o1 = new StaticVar(); StaticVar o2 = new StaticVar(); } }
Output: 1
1
Using static keyword- i.e static variable,
public class StaticVar { static int a = 0; public StaticVar() { a++; System.out.println(a); } public static void main(String[] args) { StaticVar o1 = new StaticVar(); StaticVar o2 = new StaticVar(); } } Output:-- 1 2
2) Static block:--
A static block is a block of code enclosed in braces ({}) and preceded by the static keyword. It is executed automatically by the JVM when the class is loaded into memory, before any objects of the class are created or any static methods are invoked.If a class contains multiple static blocks, the JVM executes them once in the order in which they appear in the class. These blocks are commonly referred to as static initialization blocks.
Static blocks are primarily used to initialize static variables or perform one-time initialization tasks that need to be executed when the class is loaded.
Example 1:--
public class StaticBlk { static int a; static { a = 10; System.out.println(a); } public static void main(String[] args){ } }
Output:-- 10
Example 2:-- Multiple static blocks
public class StaticBlk { static int a; static { System.out.println("Static block1"); a = 10; } static { System.out.println("Static block2"); a = 20; } public static void main(String[] args){ System.out.println("Value of a is "+a) } }
Output:-- Static block1
Static block2
Value of a is 20
Example 3:-- Static blocks are executed before constructors.
public class StaticBlk {
static int a;
static {
System.out.println("Static block");
}
public StaticBlk{
System.out.println("This is constructor");
}
public static void main(String[] args){
StaticBlk sb = new StaticBlk();
}
}
Output:-- Static block
This is constructor
3) Static methods :--
It is a method which belongs to the class not to the object. It can access only the static data.
Static method can call only other static methods not a non static methods. and it can not refer to "this" and "super" keywords anywhere.
Example:--
public class StaticMethod {
public static void display () {
System.out.println("static method");
}
public void disp () {
System.out.println("non static method");
}
public static void main (String[] args) {
display(); //calling without object
StaticMethod obj = new StaticMethod();
obj.disp(); //calling using object
}
}
Output:-- static method
non static method
4) Static Nested Class:--
A static nested class is a class declared inside another class and marked with thestatic keyword. Like any other member of the outer class, a static nested class can be declared with the public, protected, private, or package-private access modifier.One of the main advantages of a static nested class over a non-static inner class is that it is not associated with an instance of the enclosing (outer) class. As a result, an object of a static nested class can be created without creating an instance of the outer class.
Example:-public class NestedClassEx {
private static class NestedClass {
public void print () {
System.out.println("Static nested class example");
}
}
public static void main (String[] args) {
NestedClass nc = new NestedClass();
nc.print();
}
}
Output:-- Static nested class example
Note:-- Constant variable name should be in Caps. you can use (_) in between.
Questions and answers:
1) Can we overload the static methods in Java?
Yes, we can overload static methods in Java.
Example:--
public class StOverload {
Output:-- Name Anil
Name Anil Id 20
2) Can we write main method as static public void main(String[] args) ?
Yes, we can write main method like static public void main(String[] args){}.
3) What will happen if we remove the static keyword from the main method ?
No compilation error but will get run time error as "NoSuchMethodError".
4) Can we override static methods in Java?
No, we can not override static methods in Java.
5) Why main method is static in Java?
An object is not required to invoke a static method because static methods belong to the class rather than to its instances. This is one of the reasons why the
main() method is declared as static.If the main() method were non-static, the JVM would first need to create an instance of the class before invoking it. This would introduce unnecessary object creation and memory allocation, even though no object is required to start program execution.
6) Which memory areas does instance and static variables use ?
Instance variables stored in heap and static variables are stored in method area.
7) Can we serialize static variables ?
No, Only object and it's members are serialized. Static variables are shared variables and doesn't correspond to a specific object.
8) What is a static import ?
Static imports allow us to import all static fields and methods of the class, you can access them without class name reference.
9) Can we execute a program without main() method?
Yes, its possible in previous versions of java not in 1.7 using static block.
public class StaticBlockEx {
static {
System.out.println("Static block invoked");
System.exit(0);
}
}
Output :-- Static block invoked
Related Post:--
1) String Interview Questions and Answers
2) Factory Design Pattern in Java
3) Singleton Design Pattern in java with example
4) Difference between Loose Coupling and Tight Coupling in Java With Examples.
5) Internal implementation of ArrayList in Java
6) Java Vertual Machine(JVM) Architecture in Java