Course contentsShow
← Java
Lesson 359 of 2,8709. Static Members and Utility ClassesFree lesson

Declaring static Fields

Syntax for declaring static fields and how they are shared across all instances of a class.

Declaring static Fields

What you'll learn: You'll learn the exact syntax for declaring static fields and how they are shared across all instances of a class.

The Syntax

Now that you understand what static means—that it belongs to the class rather than any single instance—let's see how to actually declare a static field.

The syntax is simple: place the static keyword between the access modifier and the type:

public class Counter {
    private static int count;  // static field
    private int instanceValue; // regular instance field
}

Notice the difference:

  • static int count is shared by all Counter objects
  • int instanceValue is unique to each Counter object

How Static Fields Are Shared

Think of a static field like a classroom whiteboard—there's only one board that all students share. Each student doesn't get their own whiteboard.

public class BankAccount {
    private static int totalAccounts = 0;
    private double balance;
}

In this example:

  • totalAccounts exists once, no matter how many BankAccount objects you create
  • Every BankAccount instance can see and modify the same totalAccounts value
  • Each BankAccount has its own separate balance

Where Static Fields Live

Static fields are stored in memory when the class is loaded, not when objects are created. They exist even if you never create a single instance of the class.

Key Takeaway: Declare a static field by placing the static keyword before the type; that field will be shared across all instances of the class, living at the class level rather than in each object.