Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
Understanding Staic Keyword in Java

Understanding Staic Keyword in Java

10 Sep 2024
Beginner
65 Views
10 min read
Learn with an interactive course and practical hands-on labs

Free Java Course With Certificate

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.

Become a high-demand developer with our Java Full Stack Developer Training—get certified now!

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)

        Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

        Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
        Accept cookies & close this