In the previous article, we have explained How to compare Strings in Java but if you have just started programming in Java or you have intermediate knowledge in it, you may come across this question in your mind, what are the static members in java? How are they different from public members and when to use them?

So, in this post, I am going to answer these above questions or you can say, will try to give the best answer and I hope to give all the answers to your questions related to static members.

What are Static members in Java?

The class level members which have static keyword in their definition are called static members.

In Java, a static member is a member of a class that isn’t associated with an instance of a class. Instead, the member belongs to the class itself. As a result, you can access the static member without first creating a class instance.

Let me explain this with an example, suppose here is the class with non-static members

class Item {
    public int size() { // An instance method.
        return 10;
    }
}

now to call the Above size() method, we need to create a Item Class object to access it like below

Item item = new Item();
int value = item.size();
System.out.println(value);

But, in Static methods, we don't need to create any instance of class

Let's take a look at example of Static method

public class StaticMemberProgram{

    static int StaticTotallength(String a, String b) {
        // Add up lengths of two strings.
        return a.length() + b.length();
    }

    static int StaticAverageLength(String a, String b) {
        // Divide total length by 2.
        return StaticTotallength(a, b) / 2;
    }

    public static void main(String[] args) {

        // Call methods.
        int total = StaticTotallength("Golden", "Bowl");
        int average = StaticAverageLength("Golden", "Bowl");

        System.out.println(total);
        System.out.println(average);
    }
}

Now as You can see in the above example to call methods StaticTotallength & StaticAverageLength , we didn't create any class object.

The output of the above program will be

10
5

static-members-in-java-min.png

Few important points of the static keyword in Java

  • All static members are identified and get memory location at the time of class loading by default by JVM in Method area.
  • Only static variables get memory location, methods will not have separate memory location like variables.
  • Static Methods are just identified and can be accessed directly without object creation.

The two types of static members are static fields and static methods:

  1. Static field: A field that’s declared with the static keyword, like this
    private static int StaticCount;
    static private int StaticCount;

    Both of the above formats works

    1. You can use the keyword static in front of a field or method declaration.
    2. The static keyword may come before or after the access modifier.
      Example:
      class DemoofStatic{
       
      static int a=10;
      static int b=20;
       
      }
    3. The value of a static field is the same across all instances of the class. In other words, if a class has a static field named AverageTime, all objects created from the class will have the same value for AverageTime.
    4. We can not declare local variables as static it leads to compile-time error "illegal start of expression".
          class DemoOfStatic{
           
          static int a=10;
          static int b=20;
           public static void main(String [] args){
           
             //local variables cannot be static
      
           static int a=10;// compile time error: illegal start of expression
      
          }
    5. Static fields are created and initialized when the class is first loaded. That happens when a static member of the class is referred to or when an instance of the class is created, whichever comes first. All static variables are executed by JVM in the order of they defined from top to bottom.
    6. Lifetime and Scope: Static variable gets life as soon as class is loaded into JVM and is available till class is removed from JVM or JVM is shutdown. And its scope is class scope means it is accessible throughout the class.
  2. Static method: A method declared with the static keyword. Like static fields, static methods are associated with the class itself, not with any particular object created from the class. As a result, you don’t have to create an object from a class before you can use static methods defined by the class.

    Define a static member in MathUtil class

    public class MathUtil {
        public static int add(int a, int b) {
            return a + b;
        }
    }?

    One of the best-known static method is main, which is called by the Java runtime to start an application. The main method must be static, which means that applications run in a static context by default.

    Also, you can’t access a nonstatic method or field from a static method because the static method doesn’t have an instance of the class to use to reference instance methods or fields.

    public class Counter{
    
    private int count;
    
    public static void main(String args[]){
       System.out.println(count); //compile time error
    }
    
    }

    Another important point about static method is that, you can not override static method in Java. If you declare same method in sub class i.e. static method with same name and method signature.
    It will only hide super class method, instead of overriding it. This is also known as method hiding in Java. What this means is, if you call a static method, which is declared in both super class and sub class, method is always resolved at compile time by using Type of reference variable.
    Example:

    class Van{
         public static void  kmToMiles(int km){
              System.out.println("Inside Parent class static method");
         } 
    }
    
    class MainCar extends Van{
         public static void  kmToMiles(int km){
              System.out.println("Inside Child class static method");
         } 
    }
    
    public class Demo{
       
       public static void main(String args[]){
          MainCar v = new MainCar();
           v.kmToMiles(10);
      }
    }
    
    
    //Output Will be
    //Inside Parent class static method

    demo-java-class-static-method-example.png


I hope this explanation makes all the static member-related questions in java clear to you, if not feel free to ask a question in the comments or in questions section.

You may also like to read:

Leap year program in Java (multiple ways)

Fibonacci series program in Java (With and without recursion)

Palindrome program in java (String & number example)