Java Static Keyword 🎯

beginner
16 min

Java Static Keyword 🎯

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! 💡

What is the 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.

Why Use the static Keyword?

  1. Efficiency: Since static elements belong to the class, not individual objects, they are shared among all the objects of the class, reducing memory usage.

  2. 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.

  3. Initialization: Static variables are initialized only once, during the class loading, making them suitable for constants.

Declaring Static Variables 📝

To declare a static variable, use the static keyword followed by the data type, variable name, and the semicolon (;).

java
public class MyClass { public static int myStaticVariable = 10; }

Accessing Static Variables ✅

To access a static variable, use the class name instead of an object.

java
public class Main { public static void main(String[] args) { System.out.println(MyClass.myStaticVariable); // Output: 10 } }

Static Methods 💡

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.

java
public class MyClass { public static void myStaticMethod() { System.out.println("Hello, World!"); } }

Calling a Static Method ✅

To call a static method, use the class name followed by the dot operator and the method name.

java
public class Main { public static void main(String[] args) { MyClass.myStaticMethod(); // Output: Hello, World! } }

Static Blocks 📝

Static blocks are used to initialize static variables. They are executed only once, during the class loading.

java
public class MyClass { public static int myStaticVariable = 10; static { System.out.println("Static block executed."); myStaticVariable = 20; } }

Quiz Time! 🎯

Quick Quiz
Question 1 of 1

What is the output of the following code?