Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Java Dictionary

  1. Home
  2. Java Dictionary
  3. main Method / static (Java)

main Method / static (Java)

This page explains the syntax of public static void main(String[] args), the entry point of a Java program, along with the meaning of each modifier. It also covers the difference between static methods and instance methods, how static fields are shared across all instances, and how to use static initializer blocks.

Syntax

// Entry point of a Java program.
public class ClassName {
    public static void main(String[] args) {
        // Execution starts here.
    }
}

// Static field (class variable) definition.
static type fieldName = initialValue;

// Static method definition.
static returnType methodName(args) {
    // Can be called without creating an instance.
}

// Static initializer block (runs once when the class is loaded by the JVM).
static {
    // Write complex initialization logic for static fields here.
}

Meaning of Each Modifier in the main Method

Modifier / ElementMeaning
publicAllows the JVM (Java Virtual Machine) to call this method from anywhere.
staticAllows the JVM to call the method directly without creating an instance.
voidIndicates no return value. The method does not need to return a result to the JVM.
mainA reserved method name that the JVM recognizes as the entry point.
String[] argsReceives command-line arguments as a string array. If no arguments are passed, it is an empty array.

Characteristics of static

Comparisonstatic MemberInstance Member
How to callClassName.methodName()instanceVariable.methodName()
Instance creationNot requiredRequired (new)
Field sharingShared across all instancesIndependent per instance
Use of thisNot allowed (no instance exists)Allowed
Common usesUtility methods, constants, countersObject state and behavior

Sample Code

MainBasic.java
// Demonstrates basic usage of the main method and how to receive command-line arguments.
public class MainBasic {
    public static void main(String[] args) {

        // Check the number of command-line arguments.
        System.out.println("Number of arguments: " + args.length);

        // Print all arguments.
        for (int i = 0; i < args.length; i++) {
            System.out.println("args[" + i + "] = " + args[i]);
        }

        // Default behavior when no arguments are given.
        if (args.length == 0) {
            System.out.println("Run without arguments.");
        }
    }
}
javac MainBasic.java
java MainBasic
Number of arguments: 0
Run without arguments.
java MainBasic 虎杖悠仁 伏黒恵
Number of arguments: 2
args[0] = 虎杖悠仁
args[1] = 伏黒恵
SorcererRegistry.java
// Demonstrates the difference between static fields, static methods, and instance methods.
// A registry class for Jujutsu Kaisen sorcerers.
public class SorcererRegistry {

    // --- Static field (class variable) ---
    // A counter shared across all instances.
    static int totalCount = 0;

    // Constants are defined as static and final (by convention in UPPER_SNAKE_CASE).
    static final String ORGANIZATION = "Tokyo Prefectural Jujutsu High School";

    // --- Instance fields (instance variables) ---
    // Each instance holds its own value.
    String name;
    int gradeLevel;

    // Constructor: increments totalCount each time an instance is created.
    SorcererRegistry(String name, int gradeLevel) {
        this.name = name;
        this.gradeLevel = gradeLevel;
        totalCount++; // Updates the counter shared by all instances.
    }

    // --- Static method ---
    // Can be called without creating an instance. Cannot use this.
    static void printOrganization() {
        System.out.println("Organization: " + ORGANIZATION);
        System.out.println("Registered sorcerers: " + totalCount);
    }

    // --- Instance method ---
    // Can access the instance's fields.
    void printProfile() {
        System.out.println("Name: " + name + " / Year: " + gradeLevel);
    }

    public static void main(String[] args) {

        // Static methods are called using the class name (no instance needed).
        SorcererRegistry.printOrganization();

        // totalCount increments each time an instance is created.
        SorcererRegistry yuji   = new SorcererRegistry("虎杖悠仁", 1);
        SorcererRegistry megumi = new SorcererRegistry("伏黒恵", 1);
        SorcererRegistry nobara = new SorcererRegistry("釘崎野薔薇", 1);

        // Instance methods are called via an instance variable.
        yuji.printProfile();
        megumi.printProfile();
        nobara.printProfile();

        // The static field is shared across all instances, so it equals 3.
        System.out.println("Registered sorcerers: " + SorcererRegistry.totalCount);
    }
}
javac SorcererRegistry.java
java SorcererRegistry
Organization: Tokyo Prefectural Jujutsu High School
Registered sorcerers: 0
Name: 虎杖悠仁 / Year: 1
Name: 伏黒恵 / Year: 1
Name: 釘崎野薔薇 / Year: 1
Registered sorcerers: 3
GradeConfig.java
// Demonstrates how to use a static initializer block.
// Initializes sorcerer grade settings when the class is loaded.
import java.util.HashMap;

public class GradeConfig {

    // Static field (HashMap cannot be easily initialized at declaration, so a static initializer is used).
    static HashMap<String, String> gradeMap;
    static String defaultGrade;

    // Static initializer block: runs exactly once when the class is loaded by the JVM.
    static {
        gradeMap = new HashMap<>();
        gradeMap.put("五条悟",   "Special Grade");
        gradeMap.put("乙骨憂太", "Special Grade");
        gradeMap.put("虎杖悠仁", "Grade 1");
        gradeMap.put("七海建人", "Grade 1");
        gradeMap.put("伏黒恵",   "Grade 2");
        gradeMap.put("釘崎野薔薇", "Grade 2");
        defaultGrade = "Not registered";
        System.out.println("GradeConfig has been initialized.");
    }

    // Static method: retrieves a grade.
    static String getGrade(String name) {
        return gradeMap.getOrDefault(name, defaultGrade);
    }

    public static void main(String[] args) {
        // The static initializer block runs the moment the class is first used.
        System.out.println("Grade of 五条悟: " + GradeConfig.getGrade("五条悟"));
        System.out.println("Grade of 虎杖悠仁: " + GradeConfig.getGrade("虎杖悠仁"));
        System.out.println("Grade of 釘崎野薔薇: " + GradeConfig.getGrade("釘崎野薔薇"));
        System.out.println("Grade of 東堂葵: " + GradeConfig.getGrade("東堂葵"));
    }
}
javac GradeConfig.java
java GradeConfig
GradeConfig has been initialized.
Grade of 五条悟: Special Grade
Grade of 虎杖悠仁: Grade 1
Grade of 釘崎野薔薇: Grade 2
Grade of 東堂葵: Not registered

Notes

public static void main(String[] args) is the method the JVM calls when starting a program. public makes it accessible from the JVM, static allows it to be called without an instance, void means no return value, and String[] args receives command-line arguments. If any of these four signature elements are missing, the JVM cannot recognize the entry point.

static members belong to the class, so they can be called as ClassName.methodName() without creating an instance. A static field exists exactly once per class, and all instances share the same value. It is convenient for managing state that is common across the entire class, such as instance counters or configuration values. The this keyword cannot be used inside a static method, because static methods can be called without an instance.

A static initializer block static { } runs exactly once when the class is loaded by the JVM. It is used for complex initialization that cannot be written on a single line at declaration, such as pre-populating a HashMap. When a simple value assignment suffices, initializing the field at declaration is simpler.

For access modifiers (public / private / protected), see public / private / protected / static / final. For the basics of classes and instances, see class / new / Constructor / this.

Common Mistake 1: Calling an instance method from a static context

A static method is called without an instance. Therefore, directly accessing an instance method or instance field from within it causes a compile error.

StaticCallNg.java
public class StaticCallNg {
    String name = "虎杖悠仁"; // Instance field.

    // Directly accessing an instance field from a static method causes an error.
    public static void main(String[] args) {
        System.out.println(name); // Compile error: non-static variable name cannot be referenced from a static context
    }
}
javac StaticCallNg.java
StaticCallNg.java:6: error: non-static variable name cannot be referenced from a static context
        System.out.println(name);
                           ^
1 error

To access instance members, create an instance. Alternatively, declaring the field static makes it directly accessible from a static context.

StaticCallOk.java
public class StaticCallOk {
    String name = "虎杖悠仁"; // Instance field.

    public static void main(String[] args) {
        // Create an instance first, then access the field.
        StaticCallOk obj = new StaticCallOk();
        System.out.println(obj.name); // 虎杖悠仁
    }
}
javac StaticCallOk.java
java StaticCallOk
虎杖悠仁

Common Mistake 2: Wrong main method signature

The signature public static void main(String[] args) is a strict format defined by the JVM. Even a single difference means the JVM cannot recognize the entry point and a runtime error occurs.

WrongMainNg.java
public class WrongMainNg {
    // The return type is int, so the JVM will not recognize this as the entry point.
    public static int main(String[] args) {
        System.out.println("伏黒恵");
        return 0;
    }
}
javac WrongMainNg.java
java WrongMainNg
Error: Main method not found in class WrongMainNg, please define the main method as:
   public static void main(String[] args)

The only entry point the JVM recognizes is public static void main(String[] args). The variable name args can be any valid name, but the type must be String[] and the modifiers public static void are required.

CorrectMainOk.java
public class CorrectMainOk {
    // Correct signature.
    public static void main(String[] args) {
        System.out.println("伏黒恵");
    }
}
javac CorrectMainOk.java
java CorrectMainOk
伏黒恵

Common Mistake 3: Using this in a static method

A static method does not belong to an instance, so the this keyword cannot be used. Since this refers to the current instance (itself) and no instance exists in a static context, using it causes a compile error.

StaticThisNg.java
public class StaticThisNg {
    String name;

    public static void printName() {
        System.out.println(this.name); // Compile error: cannot use this in a static context
    }

    public static void main(String[] args) {
        printName();
    }
}
javac StaticThisNg.java
StaticThisNg.java:5: error: non-static variable name cannot be referenced from a static context
        System.out.println(this.name);
                           ^
1 error

To use an instance's fields in a static method, receive an instance as a parameter, or change the method to an instance method.

StaticThisOk.java
public class StaticThisOk {
    String name;

    // Making it an instance method allows this to be used.
    public void printName() {
        System.out.println(this.name);
    }

    public static void main(String[] args) {
        StaticThisOk obj = new StaticThisOk();
        obj.name = "七海建人";
        obj.printName(); // 七海建人
    }
}
javac StaticThisOk.java
java StaticThisOk
七海建人

If you find any errors or copyright issues, please .