Static

Objects

Static

🙋 Need help? Ask an expert now!

A "static" object is unique; it belongs to the class rather than the instance of the class. In other words, a static variable is only allocated to the memory once: when the class loads. No matter how many instances you create from a class, the static variable is only allocated to the memory once, making your program memory efficient. When a program is running and there's only one instance of something, it is "static". Take a look at the program below for examples of static methods and variables, and how we can call them without the use of an object.

StaticFieldsExample.java
package exlcode;

public class StaticFieldsExample {

  public static void main(String[] args) {
    // static variables and methods can be accessed
    // without creating an object
    System.out.println(StaticFieldsTest.exampleVariableOne);
    StaticFieldsTest.print();
  }
}
StaticFieldsTest.java
package exlcode;

public class StaticFieldsTest {

  public static String exampleVariableOne = "Java";
  private static String exampleVariableTwo= "Hello World!";

  public static void print() {
    System.out.println(exampleVariableTwo);
  }
}

We don't need to create a new object to access "static" members of a class. We call the class name and use "dot notation" to specify the member we want to access. Static members are attached to a class rather than an object or an instance of the class.

As a programmer, it is important to note that since there is only one version of the "static" members, when the variable's value is changed, the value of that variable is changed for every object in the class.

Also, keep in mind that the main method of each class is static because there are no objects that exist for the class when the JVM calls the main method. Objects are usually created inside the main method, which is why the method itself has to be static.

Edit Me on GitHub!

Application Question

Which of the following statements is incorrect?