Welcome to our comprehensive guide on the static keyword in Java! In this tutorial, we'll explore this essential concept, learn when and why to use it, and see it in action with practical examples. Let's dive right in! 💡
static keyword in Java?The static keyword in Java is used to declare variables, methods, or blocks of code that belong to the class rather than to individual objects of the class. These static elements are class-level entities and can be accessed directly from the class, without creating an instance of the class.
static Keyword?Efficiency: Since static elements belong to the class, not individual objects, they are shared among all the objects of the class, reducing memory usage.
Class-level Operations: Static members are used for class-level operations that do not involve any object of the class. For example, a counter to keep track of the number of objects created.
Initialization: Static variables are initialized only once, during the class loading, making them suitable for constants.
To declare a static variable, use the static keyword followed by the data type, variable name, and the semicolon (;).
public class MyClass {
public static int myStaticVariable = 10;
}To access a static variable, use the class name instead of an object.
public class Main {
public static void main(String[] args) {
System.out.println(MyClass.myStaticVariable); // Output: 10
}
}Static methods can only access and modify static variables and other static methods. To declare a static method, use the static keyword followed by the return type, method name, parameters, and the curly braces.
public class MyClass {
public static void myStaticMethod() {
System.out.println("Hello, World!");
}
}To call a static method, use the class name followed by the dot operator and the method name.
public class Main {
public static void main(String[] args) {
MyClass.myStaticMethod(); // Output: Hello, World!
}
}Static blocks are used to initialize static variables. They are executed only once, during the class loading.
public class MyClass {
public static int myStaticVariable = 10;
static {
System.out.println("Static block executed.");
myStaticVariable = 20;
}
}What is the output of the following code?