Static methods and why main is static
32 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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)); }}Percent: 82 Result: Distinction Better: 91
What this code does
percentandgradeuse only their parameters, so they are static and called with the class name.Math.maxworks the same way: no object ofMathorMarksUtilis 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
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(); }}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 errorsWhat this code does
printResult()runs without an object, sonameandmarksbelong to no one: javac reports both.- Fix it either way: remove
staticso 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.
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.
Example 3 · A static method that takes objects
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()); }}Topper: Priya
What this code does
topperhas no object of its own, but it gets two objects as parameters and reads them throughaandb.- 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
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(); }}Notebook pack: Rs. 340 Headphones: Rs. 1200
What this code does
- The instance method
printBill()uses its own fields and also calls the staticdeliveryChargedirectly. - 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
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(); }}---------- Hello, Kavya ----------
What this code does
mainis static, so it can call the staticline()directly, with no object.- To call the instance method
greet(),mainfirst creates an object; writing justgreet();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.
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
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(); }}GstUtilDemo.java:13: error: GstUtil() has private access in GstUtil
GstUtil g = new GstUtil();
^
1 errorWhat this code does
- The private constructor means no class outside
GstUtilcan 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