Menu
Coddy logo textTech

Instance vs Static Variables

Part of the Object Oriented Programming section of Coddy's Java journey — lesson 15 of 87.

So far, every field we've created belongs to a specific object. Each BankAccount has its own balance, and each Product has its own name. These are instance variables - they exist separately for each instance of a class.

But what if you need data that's shared across all objects? That's where static variables (also called class variables) come in. A static variable belongs to the class itself, not to any particular object.

public class Student {
    private String name;           // Instance variable - unique per student
    private static int totalCount; // Static variable - shared by all students
    
    public Student(String name) {
        this.name = name;
        totalCount++;  // Increments the shared counter
    }
    
    public static int getTotalCount() {
        return totalCount;
    }
}

When you create multiple students, each has their own name, but they all share the same totalCount:

Student s1 = new Student("Alice");
Student s2 = new Student("Bob");
System.out.println(Student.getTotalCount());  // Output: 2

Notice how we access the static variable through the class name (Student.getTotalCount()) rather than through an object. This emphasizes that static members belong to the class, not to instances.

Use instance variables for data that varies between objects (like a student's name). Use static variables for data that should be shared (like counting how many objects exist).

challenge icon

Challenge

Easy

Let's build a Book inventory system that tracks both individual book details and the total number of books across your entire collection using instance and static variables.

You'll create two files to organize your code:

  • Book.java: Create a Book class that tracks individual book information while also keeping count of all books ever created:
    • An instance variable title (String) - unique to each book
    • An instance variable price (double) - unique to each book
    • A static variable totalBooks (int) - shared across all Book objects, tracking how many books have been created
    • A constructor that takes the title and price, and increments the total book count
    • A getter getTitle() for the title
    • A getter getPrice() for the price
    • A static method getTotalBooks() that returns the total number of books created
  • Main.java: Create multiple Book objects and demonstrate how the static counter tracks all instances. You'll receive three book titles and three prices as inputs. After creating all three books, print four lines:
    • The title and price of each book in the format: [title]: $[price] (price formatted to 2 decimal places)
    • The total number of books using the static method: Total books: [count]

You will receive six inputs in order: title1, price1, title2, price2, title3, price3.

Remember to access the static method through the class name (Book.getTotalBooks()) rather than through an object instance. For formatting prices, use String.format("%.2f", price).

Cheat sheet

A static variable (also called a class variable) belongs to the class itself and is shared across all instances of that class, unlike instance variables which are unique to each object.

Declare a static variable using the static keyword:

public class Student {
    private String name;           // Instance variable - unique per student
    private static int totalCount; // Static variable - shared by all students
    
    public Student(String name) {
        this.name = name;
        totalCount++;  // Increments the shared counter
    }
    
    public static int getTotalCount() {
        return totalCount;
    }
}

Access static variables and methods through the class name rather than through an object instance:

Student s1 = new Student("Alice");
Student s2 = new Student("Bob");
System.out.println(Student.getTotalCount());  // Output: 2

Use instance variables for data that varies between objects. Use static variables for data that should be shared across all instances.

Try it yourself

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Read inputs for three books
        String title1 = scanner.nextLine();
        double price1 = Double.parseDouble(scanner.nextLine());
        String title2 = scanner.nextLine();
        double price2 = Double.parseDouble(scanner.nextLine());
        String title3 = scanner.nextLine();
        double price3 = Double.parseDouble(scanner.nextLine());
        
        // TODO: Create three Book objects using the inputs above
        
        // TODO: Print each book's title and price in format: [title]: $[price]
        // Use String.format("%.2f", price) for formatting the price to 2 decimal places
        
        // TODO: Print the total number of books using the static method
        // Format: Total books: [count]
        // Remember to access static method through class name: Book.getTotalBooks()
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming