Static Keyword in Java

  • By chetna malagi
  • December 26, 2023
  • JAVA
Static Keyword in Java

Static Keyword in Java

The static keyword in Java is used to define members (variables and methods) that belong to a class rather than instances of the class. Unlock the full potential of Java programming with SevenMentor’s Java Course in Pune. Here are the key significances of the static keyword:

 

  • Static Variables (Class Variables):

 

When a variable is declared as static, it becomes a class variable, also known as a static variable. These variables are shared among all instances of the class.

They are initialized only once when the class is loaded into memory and are common to all instances of the class.

 

Example:

 

public class MyClass

{

        static int count=0;//static variable

}

 

Here’s an example of a Java program that demonstrates the use of a static variable:

 

public class StaticVariableExample {

    // Static variable

    static int instanceCount = 0;

 

    // Constructor to increment the instance count each time an object is created

    public StaticVariableExample() {

        instanceCount++;

    }

 

    public static void main(String[] args) {

        // Creating instances of the class

        StaticVariableExample obj1 = new StaticVariableExample();

        StaticVariableExample obj2 = new StaticVariableExample();

        StaticVariableExample obj3 = new StaticVariableExample();

 

        // Accessing the static variable

        System.out.println(“Number of instances created: ” + StaticVariableExample.instanceCount);

    }

}

 

In this example:

 

  • The class StaticVariableExample has a static variable named instanceCount, which is initialized to 0.
  • Each time an object of this class is created (in the constructor), the instanceCount is incremented.
  • In the main method, three objects (obj1, obj2, and obj3) are created, and the instanceCount is printed to the console.
  • When you run this program, you’ll see the output indicating the number of instances created:

 

Output:

Number of instances created: 3

 

For Free, Demo classes Call: 020-71173125

Registration Link: Click Here!

 

  • Static Methods:

 

Similarly, when a method is declared as static, it becomes a class method. These methods belong to the class rather than any specific instance.

They can be called using the class name, without creating an instance of the class.

 

Example:

 

public class Mathutils

{

       public static int add(int a,int b)

        {

                   return a+b;

        }

}

 

Here’s an example of a Java program that demonstrates the use of static methods:

 

public class StaticMethodExample {

    // Static method to calculate the square of a number

    static int calculateSquare(int number) {

        return number * number;

    }

 

    // Another static method to calculate the cube of a number

    static int calculateCube(int number) {

        return number * number * number;

    }

 

    public static void main(String[] args) {

        // Calling static methods without creating an instance of the class

        int squareResult = calculateSquare(5);

        int cubeResult = calculateCube(3);

 

        // Displaying the results

        System.out.println(“Square of 5: ” + squareResult);

        System.out.println(“Cube of 3: ” + cubeResult);

    }

}

 

In this example:

 

  • The class StaticMethodExample has two static methods: calculateSquare and calculateCube.
  • These static methods can be called directly without creating an instance of the class.
  • In the main method, we call the static methods to calculate the square and cube of numbers and then print the results to the console.

 

When you run this program, you’ll see the output:

 

         Square of 5: 25

         Cube of 3: 27

 

  • Static Block:

A static block is a block of code enclosed in curly braces {} and preceded by the static keyword. It is executed when the class is loaded into memory.

It is often used for static initialization, setting up static resources, or performing any one-time activities for the class.

 

Example:

 

public class MyClass

{

         static{

                          //code to be executed when class is loaded

                             System.out.println(“Class is being loaded”);

                    }

}

 

Here’s an example of a Java program that includes a static block:

 

public class StaticBlockExample {

    // Static variable

    static int staticVariable;

 

    // Static block

    static {

        System.out.println(“This is a static block.”);

        staticVariable = 42; // Initializing the static variable in the static block

    }

 

    // Main method

    public static void main(String[] args) {

        System.out.println(“Static variable value: ” + staticVariable);

 

        // You can also access the static variable without creating an instance of the class

        System.out.println(“Static variable value (direct access): ” + StaticBlockExample.staticVariable);

    }

}

 

For Free, Demo classes Call: 020-71173125

Registration Link: Java Training in Pune!

 

  • Static Nested Classes:

 

A static nested class is a class that is declared as static. It is associated with its outer class and does not have access to instance-specific members of the outer class.

It can be instantiated without creating an instance of the outer class.

 

Example:

 

public class OuterClass 

{

    static class StaticNestedClass

   {

        // Code for the static nested class

    }

}

 

Here’s an example of a Java program that includes a static nested classes:

 

// Outer class

class OuterClass {

    private static String outerMessage = “Hello from OuterClass”;

 

    // Static nested class

    static class StaticNestedClass {

        void displayMessage() {

            // Accessing the static member of the outer class

            System.out.println(“Message from StaticNestedClass: ” + outerMessage);

        }

    }

}

 

public class Main {

    public static void main(String[] args) {

        // Creating an instance of the static nested class

        OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

 

        // Calling the method of the static nested class

        nestedObject.displayMessage();

    }

}

 

In this example:

 

  • OuterClass is the outer class, and it has a private static member outerMessage.
  • StaticNestedClass is a static nested class inside OuterClass.
  • In the main method of the Main class, an instance of the StaticNestedClass is created, and its displayMessage method is called to access the static member of the outer class.

 

  • Static Import:

 

The static keyword is also used in the context of static imports. It allows you to import the static members of a class directly, so you can use them without qualifying with the class name.

 

Example:

 

import static java.lang.Math.PI;

 

public class Circle {

    double calculateArea(double radius) {

        return PI * radius * radius;

    }

}

 

Here’s a simple example demonstrating the use of static imports:

 

// MathOperations.java

public class MathOperations {

    public static int add(int a, int b) {

        return a + b;

    }

 

    public static int subtract(int a, int b) {

        return a – b;

    }

}

 

// Main.java

import static java.lang.System.out; // Static import for System.out.println

import static java.lang.Math.*; // Static import for all static members of Math class

import static MathOperations.*; // Static import for static members of MathOperations class

 

public class Main {

    public static void main(String[] args) {

        // Using static import for System.out.println

        out.println(“Using static import for System.out.println”);

 

        // Using static import for Math class

        double result1 = sqrt(25);

        out.println(“Square root of 25: ” + result1);

 

        // Using static import for MathOperations class

        int result2 = add(10, 5);

        int result3 = subtract(20, 8);

 

        out.println(“Result of addition: ” + result2);

        out.println(“Result of subtraction: ” + result3);

    }

}

 

In this example:

 

  • MathOperations is a class with two static methods (add and subtract).
  • In the Main class, static imports are used for System.out.println, all static members of java.lang.Math, and the static members of the MathOperations class.
  • With static imports, you can directly use out for System.out.println, and sqrt, add, and subtract without explicitly mentioning the class names.

 

Do watch the video on Java: Click Here 

 

Please note that while static imports can make code more concise, they should be used judiciously to avoid confusion and maintain code readability.

 

Author:-

chetna malagi

Call the Trainer and Book your free demo Class for Java

Call now!!! | SevenMentor Pvt Ltd.

© Copyright 2021 | SevenMentor Pvt Ltd.

Submit Comment

Your email address will not be published. Required fields are marked *

*
*