Sunday, 30 April 2023

What is Static Keyword in Java? with example.




In Java, the static keyword is used to define a variable, method, or block that belongs to the class itself, rather than an instance of the class. Here's an example of how the static keyword can be used in Java:


```

public class MyClass {

    static int numInstances = 0; // static variable


    public MyClass() {

        numInstances++; // increment static variable

    }


    static void printNumInstances() { // static method

        System.out.println("Number of instances created: " + numInstances);

    }

}


public class Main {

    public static void main(String[] args) {

        MyClass obj1 = new MyClass();

        MyClass obj2 = new MyClass();

        MyClass obj3 = new MyClass();


        MyClass.printNumInstances(); // call static method

    }

}

```


In This Example, We Have A Class Called `Myclass` That Has A Static Variable Called `Numinstances` And A Static Method Called `Printnuminstances()`. When A New Instance Of `MyClass` Is Created, The Constructor Is Called, And The `numinstances` Variable Is Incremented. The `printnuminstances()` Method Prints The Value Of The `numinstances` Variable.


In The `Main()` Method Of The `Main` Class, We Create Three Instances Of `MyClass` And Then Call The `Printnuminstances()` Method Using The Class Name `MyClass`. Since `Numinstances` Is A Static Variable, Its Value Is Shared Among All Instances Of `MyClass`, So The Output Of The Program Will Be:


```

Number of instances created: 3

```

The Static Keyword Is Useful When You Want To Define A Variable Or Method That Is Shared By All Instances Of A Class. Static Methods Can Be Called Without Creating An Instance Of The Class, Which Can Save Memory And Improve Performance. However, Overuse Of Static Variables And Methods Can Make Your Code Harder To Read And Maintain, So It's Important To Use Them Judiciously.

No comments:

Post a Comment

What is Java Permutation and Combination Program?

Here's A Java Program That Calculates Permutations And Combinations: ```Java Import Java.Util.Scanner; Public Class Permutationcombinati...