May 15, 2022

static in Java With Examples

Static keyword in Java is used to create variables and methods that are associated with the class rather than with any object of the class.

Static in Java

Normally when we create a class it serves as a blueprint for the objects of the class. It’s only when you create an object of the class with new operator that the storage for fields and methods is actually made available and using the object you can call the methods. Each object of the class has its own copy of the instance variable.

But you may have a scenario where you want only a single copy of the variable no matter how many objects are created, for example when declaring constants. You may also need a method that is not associated with the objects and you should be able to call that method with out creating any object of the class. Both of these things can be done by using static keyword in Java.

If you mark a variable or a method as static in Java that variable or method is not associated with any object of the class but exists at the class level, you can access that variable or method without creating any object of the class. Example of having such requirement where you should be able to call a method without creating any object is static main method in Java.

The static keyword in Java can be used with-

  • variables
  • methods
  • static blocks
  • nested (inner) classes

static variables in Java

If you want to have variables that are common to all objects you can mark them as static.

As Example– static int x = 10;

Fields having static modifier are associated with the class rather than with any object and such fields are known as static fields or class variables. Static variables are accessed directly using the class name and no object of the class is needed.

ClassName.static_var;

Though You can also refer to static fields with an object reference like-

obj.static_var

but this is discouraged because it does not make it clear that they are class variables.

Since static variables are shared by all the instances of the class static variables are stored as fixed location in the memory which is the method area in JVM.

Static variables usage

A common use of static keyword in Java with fields, in combination with final keyword is to define constants. Marking field as static ensures that there is only one copy and marking it as final ensures that the value can’t be changed.

public static final String PATH = "/usr/bin";
public static final int DAYS_PAID = 22;

static methods in Java

static method is also associated with the class not with the instances of the class.

Static methods should be invoked with the class name without the need for creating an instance of the class. For example-

ClassName.static_method(args);

Though you can also refer to static methods with an object reference like given here-

obj.static_method(args)

but this is discouraged because it does not make it clear that they are class methods.

static method access restrictions

  1. Static methods can access static methods and static fields directly.
  2. Static methods can’t access instance variables or instance methods directly, object reference is required in such cases.
  3. static methods cannot use the this keyword as static methods are not associated with any instance.
  4. super keyword can’t be used in a static context.
public class Test {
  public static void main(String[] args) { 
    staticMethod(); // ok
    nonStaticMethod(); // not permitted
  }
  // static method
  static void staticMethod(){
    System.out.println("In static method.");
  }
  // non static method
  void nonStaticMethod(){
    System.out.println("In non-static method.");
  }
}

Static method usage

One of the common use of static methods is to create static utility methods. Since utility methods generally have the logic that is not core to the application like sorting, formatting, data wrapping so there is no need for these utility methods to be called by object.

Static block in Java

Static block is an enclosed group of statements with in a class that is executed only once when the class is loaded. Static block is executed even before the main method is executed.

Static block usage

Static block is generally used to initialize static variables and static blank final variables in Java.

Static block example

public class Test {
  // static blank final variable
  static final int x;
  static int y;
  static{
    System.out.println("In static block");
    y = staticMethod(2);
    x = 5;
  }
  public static void main(String[] args) { 
    System.out.println("In main method");
    System.out.println("x = " + x);
    System.out.println("y = " + y);
  }
	 
  static int staticMethod(int i){
    return i * 5;
  }
}
Output
In static block
In main method
x = 5
y = 10

You can see here that static block is executed before the main method.

Static inner class in Java

A nested (inner) class can also be marked as static, note that top level class can’t be static.

Static nested classes are accessed using the enclosing class name- Top_class.Nested_class

A static nested class cannot refer directly to instance variables or methods defined in its enclosing class, it can use them only through an object reference.

Static nested class Java example

public class Test {
  int num1 = 7;
  public static class NestedClass{
    Test obj = new Test();
    private int num2 = 5;
    void display(){
      System.out.println("Value is "+ obj.num1 * num2);
    }
  }
  public static void main(String[] args) {
    Test.NestedClass nestedObj = new Test.NestedClass();
    nestedObj.display();
  }
}
Output
Value is 35

That's all for the topic static in Java With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment