Skip to lesson

Static methods and why main is static

To find the larger of two marks, creating an object first feels pointless. Some work does not depend on any particular object.

A method that belongs to the class

A static method is a method declared with static. It belongs to the class, not to an object, so it is called with the class name, like Math.max(78, 91), and it cannot use instance fields or this directly.

Working out a percentage needs only the marks, not any one student's object. Make such a method static and call it with the class name, MarksUtil.percent(412, 500), just like Math.max(78, 91).

Example 1 · A utility class with static methods

MarksUtilDemo.javaJava
class MarksUtil {    static int percent(int got, int total) {        return got * 100 / total;    }
    static String grade(int percent) {        if (percent >= 75) {            return "Distinction";        } else if (percent >= 60) {            return "First class";        }        return "Pass";    }}
public class MarksUtilDemo {    public static void main(String[] args) {        int p = MarksUtil.percent(412, 500);        System.out.println("Percent: " + p);        System.out.println("Result: " + MarksUtil.grade(p));        System.out.println("Better: " + Math.max(78, 91));    }}
Output
Percent: 82
Result: Distinction
Better: 91

What this code does

  • percent and grade use only their parameters, so they are static and called with the class name.
  • Math.max works the same way: no object of Math or MarksUtil is ever created.

Helpers like these are utility methods, and a class that only holds them is a utility class. You have used static methods since Basics: Math.max, Math.sqrt, and every method you wrote next to main in Methods (opens in a new tab).

No object, so no instance fields and no this

Student.printResult() runs with no object, so when it says name, Java must ask: whose name? There is no answer, so javac stops with a static context error.

Example 2 · Mistake: a static method uses an instance field

StaticErrorDemo.javaJava
class Student {    String name;    int marks;
    static void printResult() {        System.out.println(name + ": " + marks);    }}
public class StaticErrorDemo {    public static void main(String[] args) {        Student.printResult();    }}
Sample compiler output
StaticErrorDemo.java:6: error: non-static variable name cannot be referenced from a static context
        System.out.println(name + ": " + marks);
                           ^
StaticErrorDemo.java:6: error: non-static variable marks cannot be referenced from a static context
        System.out.println(name + ": " + marks);
                                         ^
2 errors

What this code does

  • printResult() runs without an object, so name and marks belong to no one: javac reports both.
  • Fix it either way: remove static so it runs on one student, or pass the student in (next example).

A static context means code that runs without an object: a static method, a static block or a static field's starting value. Calling an instance method or using this there fails the same way; each case is a round below.

Fix the error

Fix the static context error

Read the error, then pick the line that fixes it.

Round 1 of 4

greet() should print one student's name.

class Student {
String name;
static void greet() {
System.out.println("Hi " + name);
}
}

Error

Student.java:4: error: non-static variable name cannot be referenced from a static context

Who can use what

A static topper() must compare two students' marks. The rule goes one way: instance code can use everything, but static code reaches instance members only through an object it is given or creates.

An instance method can use instance members and static members directly. A static method can use static members directly, but instance members only through an object it is given or creates, like a.getMarks().

Example 3 · A static method that takes objects

TopperDemo.javaJava
class Student {    private String name;    private int marks;
    Student(String name, int marks) {        this.name = name;        this.marks = marks;    }
    String getName() {        return name;    }
    int getMarks() {        return marks;    }
    static Student topper(Student a, Student b) {        if (a.getMarks() >= b.getMarks()) {            return a;        }        return b;    }}
public class TopperDemo {    public static void main(String[] args) {        Student s1 = new Student("Aarav", 88);        Student s2 = new Student("Priya", 94);        Student top = Student.topper(s1, s2);        System.out.println("Topper: " + top.getName());    }}
Output
Topper: Priya

What this code does

  • topper has no object of its own, but it gets two objects as parameters and reads them through a and b.
  • It compares two students, not one, so a static method fits: it is not about "this" student.

Example 4 · An instance method using static members

OrderBillDemo.javaJava
class Order {    private static int freeDeliveryAbove = 499;    private String item;    private int amount;
    Order(String item, int amount) {        this.item = item;        this.amount = amount;    }
    static int deliveryCharge(int amount) {        if (amount > freeDeliveryAbove) {            return 0;        }        return 40;    }
    void printBill() {        int total = amount + deliveryCharge(amount);        System.out.println(item + ": Rs. " + total);    }}
public class OrderBillDemo {    public static void main(String[] args) {        new Order("Notebook pack", 300).printBill();        new Order("Headphones", 1200).printBill();    }}
Output
Notebook pack: Rs. 340
Headphones: Rs. 1200

What this code does

  • The instance method printBill() uses its own fields and also calls the static deliveryCharge directly.
  • The static method reads only the static field and its parameter, so it never needs an object.

Why main is static

When you type java GreetDemo, no object exists yet. A static main is a starting point the JVM (the program that runs your code) can call directly, as GreetDemo.main(args), without building any object.

Example 5 · main is static: it needs an object for instance methods

GreetDemo.javaJava
public class GreetDemo {    String name = "Kavya";
    void greet() {        System.out.println("Hello, " + name);    }
    static void line() {        System.out.println("----------");    }
    public static void main(String[] args) {        line();        GreetDemo app = new GreetDemo();        app.greet();        line();    }}
Output
----------
Hello, Kavya
----------

What this code does

  • main is static, so it can call the static line() directly, with no object.
  • To call the instance method greet(), main first creates an object; writing just greet(); would be a compile error.

If main were an instance method, the JVM would first have to create a GreetDemo object and choose a constructor and its arguments. A static main avoids that question, which is also why main creates an object before it calls an instance method.

Java 25 added a shorter form of main for small programs, where the launcher creates the object for you. public static void main(String[] args) is still the standard form and works in every version.

Utility classes and a private constructor

A utility class is a class that holds only static helper methods, like Math. It has a private constructor, so no objects of it can be created.

Creating an object of GstUtil makes no sense: it holds only static methods. Give it a private constructor, private GstUtil() { }, and new GstUtil() outside the class becomes a compile error.

Example 6 · A private constructor blocks objects

GstUtilDemo.javaJava
class GstUtil {    private GstUtil() {    }
    static int withGst(int price) {        return price + price * 18 / 100;    }}
public class GstUtilDemo {    public static void main(String[] args) {        System.out.println(GstUtil.withGst(500));        GstUtil g = new GstUtil();    }}
Sample compiler output
GstUtilDemo.java:13: error: GstUtil() has private access in GstUtil
        GstUtil g = new GstUtil();
                    ^
1 error

What this code does

  • The private constructor means no class outside GstUtil can create an object of it.
  • Delete the last line and the program prints 590: the static method still works without any object.

Math itself is written this way. Java also lets you call a static method through an object, like u.withGst(500), but avoid it: it hides that no object is involved, and it even works when u is null.

Next step

Check your understanding

12 quick questions