×

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

Enterprise Java Beans

One of the many Java APIs for the common development of corporate software is Enterprise Java Beans (EJB). An EJB, a server-side software component, contains the business logic of an...

4 minutes read.

How to run java program in ubuntu

To run the java programming in ubuntu, we need to follow several steps: Let's see the process. Step1: Install the Java compiler or JDK to the system. To run the java program, we...

3 minutes read.

Converting Long to Date in Java

What Long and Date are in Java and how are they implemented in the Java programming language are the topics of this article. Additionally, we'll go into great detail on...

4 minutes read.

Java String join() method

Java String join() method returns a joined String with given delimiter Syntax: public static String join(CharSequence delimeter,charSequence...elements) public static String join(CharSequence delimeter,Iterable<?extens charSequence>elements) Parameters: delimiter: char value to be added with each element elements: char value...

1 minute read.

Davis Staircase Problem in Java

Davis has several stairs in his home and prefers to ascend one, two, or three steps at a time. As a highly clever youngster, he thinks about how many ways...

3 minutes read.

Java Buffered Writer

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Java Math tanh() Method

The tanh() method of Java Math class returns the hyperbolic tangent of the specified double value. Syntax: public static double tanh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic tangent is to...

2 minutes read.

User Defined Custom Exceptions in Java

In this tutorial, we will discuss user-defined custom exceptions with examples. Introduction In Java, we have proactively characterised, Exception classes, for example, ArithmeticException, NullPointerException, ArrayoutOfBound and so on. These built-in exceptions are...

3 minutes read.

How to convert double to String in Java

How to Convert double to String in Java It is used when we want to convert double primitive to String type. There are two methods to convert double to String. Using String.valueOf()...

2 minutes read.

Java String equalsIgnoreCase() method

equalsIgnoreCase() method compares two Strings based on the their content but ignore the case. Syntax public boolean equalsIgnoreCase(Objects anObject) Parameter anObject: Object to be compared with the current String without case consideration. Returns It returns true...

1 minute read.

What is advance Java?

The definition of advance inside the dictionary refers to a forward motion, development, or progress, and the definition of enhancing is something that improves things. To become experts in that...

3 minutes read.

Convert list to array Java

One of the popular collection interfaces for storing an ordered collection is the List. The List interface may contain repeating groups and preserves the insertion order of entries. This article will...

4 minutes read.

Collections in Java

Collection framework is one of Java's most powerful subsystems. It is a set of classes and interfaces that is all-the-rage technology for superintending objects and a group of objects. In...

6 minutes read.

this keyword in Java

The 'this' keyword is an essential notion in Java. We'll go through the 'this' keyword in depth and provide some examples of how it's used in Java. In Java, the term...

5 minutes read.

Java float vs double

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Java Integer max() method

The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max. Syntax public static int max(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Java Integer floatValue() method

The floatValue() method of Integer class returns a float value for this Integer after a widening primitive conversion. Syntax public float floatValue() Parameters NA Specified by This method is specified by floatValue in class Number Return Value This...

1 minute read.

IdentityHashMap in Java

The IdentityHashMap class is comparable to the HashMap class and is an AbstractMap implementation. However, when comparing the key, it uses reference equality rather than object equality (or values). Identity HashMap...

6 minutes read.

Java Stringjoiner Class

StringJoiner is a class which is used to construct a sequence of characters which are separated by a delimiter. Optionally, it starts with a provided prefix and ended with the...

5 minutes read.

Java Integer remainder Unsigned() method

The remainderUnsigned() method of Java Integer class returns the unsigned remainder by dividing the first and second argument. Syntax public static int remainderUnsigned(int dividend, int divisor)  Parameters The ‘dividend’ and ‘divisor’ represents the value...

1 minute read.