🌄 Check out these other AP Computer Science A Resources:

  • Attend AP CS A live streams every week with Fiveable+ 👉 Join here

The keyword "static" means that the variable or method belongs to the class. Let's see what this means by diving deeper.

Static Methods
If you've ever used methods from the Math class, you've used static methods. For example, when you call "Math.abs(-5)", you are calling the static method "abs" in the Math class. Since the method is static, you call it by doing "Math.abs(-5)", without first creating an object of the Math class.

Inside the Math class, this is what the static function "abs" looks like:

public class Math
   static int abs (int a)
      // Implementation not shown, but the method returns the absolute value
      // of the variable a

   // There may be instance variables, constructors, and other methods not
   // shown.

Static Variables 😮
Static variables belong to the class, so if you change them while creating one object, the value changes for all objects of that class.

public class Student
   public String name;
   public static int count = 0;

   public Student (String studentName)
      name = studentName;

   public void printName()

   public void printCount()

When you create objects of this class, each object can have a different name, but the count will be the same for both. 🔍

Student andy = new Student("Andy");

// If you call andy.printCount() here, you will get "1"

Student mary = new Student("Mary");

// If you call andy.printCount() here, you will get "2"

After executing both lines of code, you can still access the individual names of both students (objects of the Student class). By doing andy.printName(), the computer will print "Andy". By doing mary.printName(), the computer will print "Mary". 

However, regardless of whether you call andy.getCount() or mary.getCount(), you will get "2" because count is a static variable, so its value is shared by both students and its value increased by 1 each time a student was created.

Summary: 🎉✨😎

  • You can call static methods without creating an object of their class (like Math class functions)
  • Static variables are shared by all objects of a class, meaning any one of these objects can change the value of the variable for the other objects
Did this answer your question?