AP Computer Science A
Find gaps with guided practice
Guided practice grid visualization
Table of Contents

💻ap computer science a review

5.7 Static Variables and Methods

Verified for the 2025 AP Computer Science A examCitation:

In Java, not everything belongs to individual objects. Sometimes, we need data or behaviors that are shared across all instances of a class or that exist even without any instances at all. This is where the static keyword comes in. Static variables and methods belong to the class itself rather than to any specific object. They provide a way to define class-level properties and behaviors that can be accessed without creating an instance. In this section, we'll explore how static members work, when to use them, and how they differ from their non-static counterparts.

Static Variables: Class-Level Data

Static variables (also called class variables) are:

  • Declared with the static keyword
  • Associated with the class, not individual objects
  • Shared among all instances of a class
  • Accessed using the class name and dot operator
public class School {
    // Instance variable - each School object has its own name
    private String name;
    
    // Static variable - shared by all School objects
    private static int totalSchools = 0;
    
    public School(String name) {
        this.name = name;
        totalSchools++;  // Increment the shared counter
    }
    
    public static int getTotalSchools() {
        return totalSchools;
    }
}

Key Characteristics of Static Variables

  1. Single Copy: Only one copy of a static variable exists, regardless of how many objects are created.
  2. Shared Access: All instances of the class share the same static variables.
  3. Class Association: Static variables belong to the class, not to objects.
  4. Initialization: Static variables are initialized when the class is loaded, before any objects are created.

Public vs. Private Static Variables

Static variables can be designated as either public or private:

public class MathConstants {
    // Public static variable - accessible from any class
    public static final double PI = 3.14159265358979323846;
    
    // Private static variable - accessible only within this class
    private static int calculationCount = 0;
}

Best Practices for Static Variable Access:

  • Make static variables private to maintain encapsulation
  • If a static variable must be public, consider making it final (constant)
  • Provide public static methods to access or modify private static variables

Accessing Static Variables

Static variables are accessed using the class name and dot operator, since they are associated with a class, not objects:

// Accessing a public static variable
double circleArea = Math.PI * radius * radius;

// Accessing a static variable through a static method
int schoolCount = School.getTotalSchools();

Unlike instance variables, which require an object reference followed by the dot operator, static variables are used with the class name:

// CORRECT: Using class name to access static variable
int count = Counter.getCount();

// INCORRECT: Using an object to access static variable
// (This works but is discouraged as it's confusing)
Counter c = new Counter();
int count = c.getCount();

Static Methods: Class-Level Behavior

Static methods are:

  • Declared with the static keyword in the header
  • Associated with the class, not individual objects
  • Called using the class name, not an object reference
  • Unable to access instance variables or call non-static methods directly
  • Unable to use the this reference
public class MathHelper {
    // Static method - belongs to the class
    public static int square(int number) {
        return number * number;
    }
    
    // Static method with multiple parameters
    public static double average(double a, double b) {
        return (a + b) / 2;
    }
}

Using Static Methods

Static methods are called using the class name:

// Calling a static method
int squared = MathHelper.square(5);  // Returns 25

// Using multiple static methods together
double avg = MathHelper.average(3.5, 7.5);  // Returns 5.5

Limitations of Static Methods

Static methods cannot:

  • Access instance variables (non-static variables)
  • Call non-static methods
  • Use the this reference
public class Example {
    private int instanceValue = 10;
    private static int staticValue = 20;
    
    // This works - static method accessing static variable
    public static void staticMethod() {
        System.out.println(staticValue);
        
        // ERROR: Cannot access instance variable
        // System.out.println(instanceValue);
        
        // ERROR: Cannot use this reference
        // System.out.println(this.staticValue);
        
        // ERROR: Cannot call non-static method
        // nonStaticMethod();
    }
    
    public void nonStaticMethod() {
        // Non-static methods can access both static and instance members
        System.out.println(instanceValue);
        System.out.println(staticValue);
        staticMethod();  // Can call static methods
    }
}

Common Uses for Static Members

1. Utility Methods

Static methods are perfect for utility functions that don't require object state:

public class StringUtils {
    public static boolean isEmpty(String str) {
        return str == null || str.trim().length() == 0;
    }
    
    public static String reverse(String str) {
        if (str == null) return null;
        return new StringBuilder(str).reverse().toString();
    }
}

2. Counters and Statistics

Static variables are useful for tracking class-wide information:

public class User {
    private String username;
    private static int userCount = 0;
    
    public User(String username) {
        this.username = username;
        userCount++;
    }
    
    public static int getUserCount() {
        return userCount;
    }
}

3. Constants

Static final variables are ideal for constants:

public class GameSettings {
    public static final int MAX_PLAYERS = 4;
    public static final int STARTING_LIVES = 3;
    public static final double GRAVITY = 9.8;
}

4. Factory Methods

Static methods that create and return objects of the class:

public class Color {
    private int r, g, b;
    
    private Color(int r, int g, int b) {
        this.r = r;
        this.g = g;
        this.b = b;
    }
    
    // Factory methods
    public static Color red() {
        return new Color(255, 0, 0);
    }
    
    public static Color green() {
        return new Color(0, 255, 0);
    }
    
    public static Color blue() {
        return new Color(0, 0, 255);
    }
    
    public static Color custom(int r, int g, int b) {
        return new Color(r, g, b);
    }
}

Static Methods vs. Instance Methods

Static MethodsInstance Methods
Declared with static keywordNo static keyword
Belong to the classBelong to objects
Called using class nameCalled using object reference
Cannot access instance variablesCan access instance variables
Cannot use this referenceCan use this reference
Can only call other static methods directlyCan call both static and instance methods
Exist even without objectsRequire an object to be called

The main Method: A Special Static Method

The most well-known static method in Java is the main method:

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

The main method must be static because it's the entry point of the program and is called before any objects are created.

Complete Example: Using Static and Instance Members Together

Here's a complete example showing how static and instance members interact:

public class BankAccount {
    // Instance variables - unique to each account
    private String accountNumber;
    private double balance;
    
    // Static variables - shared across all accounts
    private static double interestRate = 0.02;  // 2%
    private static int accountsCreated = 0;
    
    // Constructor
    public BankAccount(String accountNumber, double initialBalance) {
        this.accountNumber = accountNumber;
        this.balance = initialBalance;
        accountsCreated++;
    }
    
    // Instance methods - operate on a specific account
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }
    
    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
        }
    }
    
    public void addInterest() {
        // Instance method using static variable
        balance += balance * interestRate;
    }
    
    public double getBalance() {
        return balance;
    }
    
    // Static methods - operate at the class level
    public static void setInterestRate(double newRate) {
        if (newRate >= 0) {
            interestRate = newRate;
        }
    }
    
    public static double getInterestRate() {
        return interestRate;
    }
    
    public static int getAccountsCreated() {
        return accountsCreated;
    }
}

Using the Example Class:

// Set class-wide interest rate
BankAccount.setInterestRate(0.03);  // 3%

// Create account instances
BankAccount account1 = new BankAccount("A001", 1000);
BankAccount account2 = new BankAccount("A002", 2000);

// Get information about the class
System.out.println("Accounts created: " + BankAccount.getAccountsCreated());  // 2
System.out.println("Current interest rate: " + BankAccount.getInterestRate());  // 0.03

// Operate on specific accounts
account1.deposit(500);
account1.addInterest();  // Uses the static interest rate
System.out.println("Account 1 balance: " + account1.getBalance());  // 1545.0

Key Points to Remember

  • Static variables belong to the class, with all objects sharing a single copy
  • Static variables can be designated as either public or private
  • Static variables are accessed using the class name and dot operator
  • Static methods are associated with the class, not individual objects
  • Static methods cannot access instance variables or call non-static methods directly
  • Static methods cannot use the this reference
  • The main method must be static because it runs before any objects are created
  • Static members are ideal for utilities, counters, constants, and factory methods

Key Terms to Review (15)

Boolean data type: The boolean data type in Java represents one of two possible values - true or false. It is commonly used for conditions and decision-making in programming.
Final Keyword: The final keyword is used in Java to declare constants, make methods unchangeable (cannot be overridden), and prevent inheritance (a final class cannot be extended). Once assigned or declared as final, their values or definitions cannot be changed.
GetGradeDecimal Method: The getGradeDecimal Method is a function that retrieves the grade for an assignment as a decimal value. It allows users to access and use grades numerically in calculations or comparisons.
GetGradeLevel method: The getGradeLevel method is a function in programming that retrieves the grade level of a student. It returns the grade level as an output.
GradeAssignment method: The gradeAssignment method is a function in programming that calculates and assigns a grade to a student's assignment based on certain criteria.
Instance Variables: Instance variables are variables declared within a class but outside any method. They hold unique values for each instance (object) of the class and define the state or characteristics of an object.
Keyword "static": The keyword "static" is used in Java to declare members (variables or methods) that belong to the entire class rather than any specific instance of the class.
@Override: The @Override annotation is used in Java to indicate that a method in a subclass is intended to override a method with the same name in its superclass. It helps ensure that the method signature and return type are correct.
Private Access Modifier: The private access modifier is used in object-oriented programming to restrict the visibility of a variable or method within a class. It means that the variable or method can only be accessed and modified from within the same class.
Public Access Modifier: The public access modifier is used in object-oriented programming to allow unrestricted visibility of a variable or method. It means that the variable or method can be accessed and modified from anywhere, including outside the class.
Static Variables: Static variables are variables that belong to the class itself, rather than an instance of the class. They are shared by all instances of the class and can be accessed without creating an object of the class.
Static Methods: Static methods are methods that belong to the class itself, rather than an instance of the class. They can be called directly using the class name without creating an object of the class.
SubmitAssignment method: The submitAssignment method is a function that allows students to turn in their completed assignments for grading. It typically takes the submitted content as input and updates the status of the assignment.
This Reference: The "this" reference is used in Java to refer to the current object on which a method is being called. It can be used to access instance variables, call other methods, or pass the current object as an argument.
ToString method: The toString method is a built-in method in Java that converts an object into a string representation. It returns a string that represents the value of the object.