AI Hints
Home›Java Tutorial›The this Keyword, Instance Methods and static
Java · Lesson 69 of 120

static

Belongs to the class.

⏱ 2 min read▶ Video at 1:26:39🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Most fields belong to each object. But a static field belongs to the class itself, and is shared by every object. It's like a single noticeboard everyone can see.

  • Not one per object
  • One for the class
  • Shared by everyone

Ticket.java

Sold is static, so there's only one, shared by all tickets. Number is a normal field, so each ticket has its own. The constructor adds one to sold, and gives the ticket its number. Price with tax is a static method. It doesn't need any ticket, just a price.

Main.javajava
public class Ticket {
    static int sold = 0;
    int number;

    Ticket() {
        sold++;
        number = sold;
    }

    static double priceWithTax(double price) {
        return price * 1.2;
    }
}

Static in action

We make three tickets. Each one gets the next number. Static members are used with the class name, Ticket dot sold. Math dot sqrt is static too. That's why we never wrote new Math. Run it. Tickets one, two, three. Three sold, and the price with tax is twelve.

Main.javajava
public class Main {
    public static void main(String[] args) {
        Ticket a = new Ticket();
        Ticket b = new Ticket();
        Ticket c = new Ticket();
        System.out.println("Numbers: " + a.number + ", " + b.number + ", " + c.number);
        System.out.println("Sold in total: " + Ticket.sold);
        System.out.println("Price: " + Ticket.priceWithTax(10));
        System.out.println("Square root of 81: " + Math.sqrt(81));
    }
}
Output
Numbers: 1, 2, 3
Sold in total: 3
Price: 12.0
Square root of 81: 9.0
Also uses Ticket.java
public class Ticket {
    static int sold = 0;
    int number;

    Ticket() {
        sold++;
        number = sold;
    }

    static double priceWithTax(double price) {
        return price * 1.2;
    }
}

Static or not

Instance members belong to each object, and need an object to use them. Static members belong to the class, and are used with the class name. Main is static, so Java can run it without creating any object first.

Instance

  • One per objectobj.method()Uses the object's fields

static

  • One per classClass.method()No object needed

Summary

Static fields are shared by every object, and static methods need no object. Use them with the class name. Next, controlling who can see what, with access modifiers.

Key takeaways
  • static: shared
  • Class.member
  • Math.sqrt, main
Next up: Access Modifiers — public and private