×

Why we use static in Java

Many reserved keywords in Java cannot be used as variable names or identifiers. Java uses static keywords frequently because of its effective memory management system. In most cases, you must first construct an instance or object of a class to access variables or methods within it. There may be instances, though, where you simply need to access a few of a class's methods or variables and don't want to make a new class instance specifically for that purpose. In this situation, Java's static keyword can be used.

The static keyword can be used in Java with methods, blocks, variables, and nested classes. Alternatively, if you use the static keyword with a variable or a method inside a class, these static members will remain the same for each instance of that class you create, and you won't be able to alter or edit them. To access these members for those classes, you don't even have to create an instance of an object, and simply using the class name will give you access to them. A Java class's main method frequently includes its static keyword.

If a class has any members marked as static, even before the class starts, all of the static members can be accessed and made active. In contrast, when an object disappears or leaves the scope, non-static members of the same class will also vanish.

Programs using static keywords:

StaticMethod.java

class StaticMethod
{
    // static variable declaration
    static int static_count = 5;
 
    // instance variable declaration 
   // we can't access the instance variable in the static method
   // you can understand it in this program 
    int inst_var = 10;
 
    // static method declaration 
    static void static demo()
    {
       static_count = 20;
       System.out.println("static method StaticDemo "+static_count);
 
       // inst_var = 20; // compilation error "error: non-static variable inst_var cannot be referenced from a static context"
 
        //instMethod ();  // compilation error "non-static method instMethod () cannot be referenced from a static context"
 
        //System.out.println (super.static_count); // compiler error "non-static variable super cannot be referenced from a static context"
     }
 
    // instance method declaration 
    void instMethod ()
    {     
           System.out.println ("instance method instance Method");
    }
 
    public static void main (String [] args)
    {
         staticDemo ();  
    }
}

You can see that there are two methods in the above program. While instMethod is an instance method, StaticDemo is a static method. Additionally, there are two variables: inst_var is an instance variable, and static_count is a static variable.

Instance variables, calling non-static methods, and referring to super in a static context all result in compilation errors when the program with the above lines is executed. These represent the static method's drawbacks.

The program above only runs smoothly and generates the output shown below when we comment on the three lines.

Output:

Why we use static in Java

Important Points about Static:

  • The static variables are initialized using the static block. When a class is loaded into memory, this block is executed. Multiple Static blocks may exist in a class, and they will all run in the same order.
  • When we declare not-static members as global in a class, we are unable to access the static block. Instead of declaring non-static variables, we must create static variables if we want to access a static block.
  • Static variables are shared by all instances (or objects) of the class because they are class-level variables. Class Variables are another name for static variables.
  • Static methods provide you with direct access to static variables.
  • Static variables are shared by each class instance.
  • Static variables are set before a class is loaded before any objects are generated from that class, and before any static methods are called from that class.
  • Constants are final static variables. Final variables must always be initialized; failure to do so will result in a compilation error.
  • However, the only way to access non-static variables and methods is through objects. Class variables can be accessed by static methods without using a class instance (static variables).
  • Static methods can be directly accessed by both static and non-static methods.
  • The main static method doesn't use an object to access static variables.
  • Both static and non-static methods can directly access a static method because they cannot be overridden.

Related Topics

MessageDigest in Java

The compression of mathematical numbers is accomplished using hash functions. In almost every data security application, hash functions are employed. The hashing, often called has values, returns a value called...

3 minutes read.

Java Integer toString() method

The toString() method of Java Integer class returns a String object which represents this Integer’s value. The second syntax returns a String object which represents the specified integer. The third syntax returns...

2 minutes read.

Java String replaceFirst() method

This method replace the first substring with user specified String. Syntax: public String replaceFirst(String Regexp, String Replacement) Parameter: Regexp : Regular Expression Replacement : the String which would replace found expression Return: a string Java String replaceFirst()...

1 minute read.

How to Solve the Deprecated Error in Java?

Deprecated Java methods should not be used because they are deprecated (often, there are better, more modern alternatives). API update. Until now, Java has kept everything backward compatible and never...

3 minutes read.

Java Instanceof Keyword

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). The type of comparison in java differentiates the...

4 minutes read.

Why main method is static in Java

The method serves as the entry point for Java programmes or simply the point from which the programme begins to run. As a result, it is one of the most...

4 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

Traverse through HashMap in Java

In this tutorial, we will discuss traversing through HashMap in Java Introduction: HashMap<Key, Value> is a part of the java collection implemented from the java 1.2 version. HashMap is written as HashMap<K,...

4 minutes read.

Java String replaceAll() method

Java String replaceAll() method returns a String replacing all the sequence of characters matching regular expression i.e regex and replacement string. Syntax: public String replaceAll(String regex, String replacement) Parameters: regex : regular expression replacement :...

1 minute read.

How to run Java Program?

How to run Java Program In this section, we will learn how to write, compile and run a Java program in Command Promptusing notepad. In order to run a Java program, we...

2 minutes read.

Java Math acos() Method

The acos() method of Math class computes the trigonometric Arc Cosine (inverse of cosine ) of an angle. The value returned is between 0.0 to pi. Syntax: public static double acos(double a) Parameters: The...

1 minute read.

Java 9 Interface Private Method

Java 9 provides us the facility to include private methods inside the java interface. In java 8 and earlier versions, we are supposed to use only constant variables and abstract...

3 minutes read.

How to reverse a linked list in java

The process of reversing a linked list in Java will be covered in this section. One of the most common questions in interviews is about reversing a linked list. If...

11 minutes read.

Interface in Java

  Interface in Java In Java, the interface is just like a class that has only static constants and abstract methods. It is used to achieve polymorphism so that it can also...

6 minutes read.

Exception Handling Program in Java

Exception Handling Program in Java Exception means something that is abnormal. In Java, an exception is treated as a problem that disrupts the normal flow of the program. An exception leads...

7 minutes read.

Constructor Chaining and Constructor Overloading in Java

Constructor Chaining Constructor chaining and constructor overloading are two confusing terms. Let's first understand constructor chaining.Constructor chaining is the process of calling one constructor from another constructor using the same object....

2 minutes read.

Kotlin Vs Java

Kotlin Vs Java There are many languages available for Android development. Java is the official language for android development but Kotlin is becoming popular nowadays. This article discusses both of these...

4 minutes read.

Hamming Code in Java

In a computer network, hamming code is a unique set of error-correction codes. It is mostly utilised in computer graphics for mistake detection and correction during data transmission from sender...

8 minutes read.

Java Static Keyword

It can be either said that static declares the value to be the same, not only in the instance of a class but also as the whole. To declare a variable...

6 minutes read.

Creating a Custom Generic Class in Java

To indicate parameter types when creating generic classes, we utilize the <> symbol. The syntax used to generate objects of a generic class is as follows. // To create an instance...

4 minutes read.