Understanding Staic Keyword in Java

Understanding Staic Keyword in Java

09 Sep 2024
Beginner
294 Views
10 min read

Static Keyword in Java

The static keyword in Java is a strong feature that allows you to efficiently manage memory and build class elements that may be shared by all instances. It alters variables, methods, blocks, and even classes so that they belong to the class rather than individual instances of the class. Understanding how to use the static keyword in Java is important for building clean, efficient, and scalable Java code.

Hence, In this Java tutorial, we will explore more about a static keyword in Java including What is a Static Keyword in Java?, Static Variables in Java, and Static Methods in Java. So grab a cup of tea and let's explore each and every concept one by one.

What is a Static Keyword in Java?

In Java, the static keyword indicates that a certain member (variable, function, or block) belongs to the class rather than a single instance. When a member is marked as static, it implies:

  • Static members are loaded into memory only once, at the time of class loading.
  • Access to static members can be done without creating an instance of the class.
    • In Java, the static keyword can be used for:

      What is a Static Keyword in Java?

    • Static variables
    • Static methods
    • Static blocks
    • Static nested classes
      • Static Variables in Java

        A static variable (sometimes called a class variable) is shared by all instances of a class. It is only initialized once, at the beginning of the program execution. All instances of the class can change the value of the static variable, and the changes are reflected across all objects.

        Example

         public class Counter {
            public static int count = 0;
        
            public Counter() {
                count++;
            }
        
            public static void main(String[] args) {
                Counter c1 = new Counter();
                Counter c2 = new Counter();
                Counter c3 = new Counter();
                System.out.println("Number of objects created: " + Counter.count);
            }
        }
        

        Output

         Number of objects created: 3
        

        Explanation

        The count variable is static and shared by all Counter class objects. Every time a new object is generated, the static count variable is increased. Regardless of how many instances are created, the count variable shows the total number of objects.

        Static Methods in Java

        In Java, static methods belong to the class rather than to its instances. Static methods can only retrieve static data and invoke other static methods; they cannot create a class object. They cannot have direct access to instance variables or non-static methods.

        Example

         public class MathUtils {
            // Static method to find the square of a number
            public static int square(int number) {
                return number * number;
            }
        
            public static void main(String[] args) {
                // Calling static method without creating an object
                int result = MathUtils.square(5);
                System.out.println("Square of 5 is: " + result);
            }
        }
        

        Output

         Square of 5 is: 25
        

        Explanation

        The square() function is static and can be used directly using the class name (MathUtils.square(5)) without requiring an instance of MathUtils.

        Static Blocks in Java

        To initialize static variables, use a static block (also known as a static initialization block). It is executed when the class is loaded into memory, even before the main function is called. Static blocks are especially useful for establishing initial settings for static variables.

        Example

         public class StaticBlockDemo {
            static int num;
            static String message;
        
            // Static block
            static {
                num = 100;
                message = "Hello, World!";
                System.out.println("Static block executed");
            }
        
            public static void main(String[] args) {
                System.out.println("Number: " + num);
                System.out.println("Message: " + message);
            }
        }
        

        Output

        Static block executed
        Number: 100
        Message: Hello, World!
        

        Explanation:

        The static block is executed once when the class is loaded, even before the main() method. It initializes the static variables num and message.

        Static and Nested Static Classes

        In Java, static classes are not permitted; however, you can designate a class as static when it is nested within another class. A nested static class does not require a reference to an instance of the parent class. Static nested classes can only access static members of their parent class.

        Example

        public class OuterClass {
            static int outerStaticVar = 10;
        
            // Nested static class
            public static class NestedStaticClass {
                public void display() {
                    System.out.println("Static variable from outer class: " + outerStaticVar);
                }
            }
        
            public static void main(String[] args) {
                // Creating an instance of the nested static class
                OuterClass.NestedStaticClass nested = new OuterClass.NestedStaticClass();
                nested.display();
            }
        }
        

        Output

        Static variable from outer class: 10
        

        Explanation

        The NestedStaticClass is a static class, meaning it can be created without an instance of OuterClass. It can directly access static members of the outer class, like outerStaticVar.

        When to Use the Static Keyword in Java

        The static keyword is useful in a variety of circumstances, particularly when you need to share common data or functionality among all instances of a class, or when you wish to access members without establishing an instance.
        Here are some typical circumstances when the static keyword is useful:
        1. Utility Classes: Static methods are suitable for classes that provide helper methods (for example, the Math class in Java), as they do not require any instance-specific data.
        Examples:
        Math.sqrt(), Math.pow().
        2. Constant Variables: Static variables allow you to define constants that are shared by all instances.

        Example

        public static final double PI = 3.14159;
        
      • Shared Data Across Instances: Static variables allow you to save common values for all instances of a class. For example, keeping track of the total number of items created globally.
      • Single Instance Method: Use static methods when the method does not rely on instance variables and solely operates with static data. Examples include utility methods such as Collections.sort(). 
      •  Static Initialization: Use static blocks to initialize static data before using the class. Setting up configurations and initializing static variables, for example, are both hard tasks. 
      •  Nested Static Classes: Use static nested classes to group related classes together but prevent the nested class from having a direct link with instances of the outer class.
      • Conclusion
        The static keyword in Java is a useful tool for writing memory-efficient, orderly, and tidy code. From static variables to static methods, blocks, and nested classes, it lets you to share data across all instances of a class and execute methods without having to create new objects. Proper usage of the static keyword improves the efficiency and structure of Java applications. Also, consider our Full Stack Java Certification Course for a better understanding of Java concepts.

        FAQs

         A static method means it can be called without creating an instance of the class.

        Static: Static members have a global scope and can be accessed from anywhere within the program, even without creating an instance of the class. Non-Static: Non-static members have a local scope and can be accessed only through an instance of the class. They are not accessible without creating an object

        The Java Virtual Machine can call it without having to create an instance of the class that contains it
        Share Article
        About Author
        Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

        Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
        Accept cookies & close this