Subjects

Subjects

More

Static Variables and Methods

Learn with content from all year groups and subjects, created by the best students.

Static Variables and Methods: AP Computer Science A Study Guide



Introduction

Welcome to the magical world of static variables and methods, where things get a bit more... stable! Think of "static" like your bedhead: no matter how many times you try to smooth it out, it just won't change. In Java, static elements belong to the class itself, not to any individual instance. So, grab a snack, maybe some popcorn, and let's dive into the world of constants and class-level methods! 🍿📚



Introduction to Static Variables and Methods

Static variables and methods are marked by the keyword static, which means they are properties of the entire class instead of any specific object. Imagine a school cafeteria's rules: they apply to every student and cannot be altered by just one student. Similarly, a static variable or method is shared across all instances of the class. For example, the Math class that we’ve seen in earlier units is a perfect case: there aren't individual "math objects" wandering around; instead, there's a set of methods for all calculations.

It's crucial to remember a few specific details about static methods:

  • Static methods cannot access or modify instance variables (non-static variables).
  • Static methods do not have a this reference, meaning they cannot reference instance variables or call non-static methods.
  • Static methods can access and modify static variables of the class.


Adding Static Variables and Methods

Let's sprinkle some static magic on our Student class. We’ll add static variables for grade boundaries and the school name, as well as static methods to change the school name and get the letter grade for a student. Imagine these static variables as the universal rules of the school—unchangeable by individual whims just like school policies!

Here's how you might start with a snippet of static variables and static methods:

/** Represents an assignment that a student will complete */
public class Assignment {
  private boolean correctAnswer; // represents the answer to an assignment, either true or false

  /** Makes a new assignment with one True/False question and sets the correct answer */
  public Assignment(boolean answer) {
    correctAnswer = answer;
  }
  
  @Override
  public String toString() {
    return "This is an assignment with correct answer " + correctAnswer;
  }

  /** Grades an assignment; returns true if correct, false otherwise */
  public boolean gradeAssignment(boolean studentAnswer) {
    return studentAnswer == correctAnswer;
  }
}

/** Represents a high school student */
public class Student {
  private int gradeLevel; // a grade between 9-12
  private String name; // the student's name in "FirstName LastName" format
  private int age; // the student's age, must be positive
  private Assignment assignment; // the current assignment the student is working on
  private int assignmentsComplete; // number of assignments completed
  private int correctAssignments; // number of correct assignments

  // Static variables for grade boundaries and the school name
  private static final double A_BOUNDARY = 0.9;
  private static final double B_BOUNDARY = 0.8;
  private static final double C_BOUNDARY = 0.7;
  private static final double D_BOUNDARY = 0.6;
  private static String school = "The Fiveable School";

  /** Makes a new student with gradeLev, fullName, and age ageNum */
  public Student(int gradeLev, String fullName, int ageNum) {
    gradeLevel = gradeLev;
    name = fullName;
    age = ageNum;
    assignment = null; // There is no active assignment at the moment
    assignmentsComplete = 0; // no assignments completed yet
    correctAssignments = 0;
  }

  /** Returns the student's grade level */
  public int getGradeLevel() {
    return gradeLevel;
  }
  
  /** Returns the student's name */
  public String getName() {
    return name;
  }
  
  /** Returns the current assignment the student is working on */
  public Assignment returnCurrentAssignment() {
    return assignment;
  }

  @Override
  public String toString() {
    return name + ", a " + gradeLevel + "th grade high school student has an average grade of " + getGradeDecimal() + ".";
  }

  /** Changes the student's name */
  public void setName(String fullName) {
    name = fullName;
  }

  /** Changes the student's grade level */
  public void setGradeLevel(int gradeLev) {
    gradeLevel = gradeLev;
  }

  /** Submits an assignment */
  public void submitAssignment(boolean studentAnswer) {
    boolean grade = assignment.gradeAssignment(studentAnswer);
    assignmentsComplete++;
    if (grade) {
      correctAssignments++;
    }
  }  

  /** Calculates and returns the student's grade as a decimal value */
  public double getGradeDecimal() {
    return (double) correctAssignments / assignmentsComplete;
  }

  /** Changes the school that the students attend */
  public static void setSchool(String schoolName) {
    school = schoolName;
  }
}

This code provides a foundation where the boundaries for letter grades and the school name are class-level constants, applicable to all instances (students).



Using Static Methods and Variables

To harness these static marvels, you use the class name followed by the dot operator. Think of it as calling the school principal using an intercom, rather than whispering in just one classroom—the principal (our static variable) hears it all!

Suppose you want to create some student objects and then change the school name for all students. Here’s how you'd do it:

public class Main {
  public static void main(String[] args) {
    Student alice = new Student(11, "Alice", 17);
    Student bob = new Student(10, "Bob Smith", 16);

    // Change the school name for all students
    Student.setSchool("New School");
    
    // Printing a welcome message using a public static variable
    System.out.println("Welcome to " + Student.school);

    // Standard outputs showing their impact
    System.out.println(alice);
    System.out.println(bob);
  }
}

Note how the school name is changed using Student.setSchool() and not by calling methods on individual instances like alice or bob. This is the power of static: one command to rule them all! 🧙‍♂️

To make things even fancier, you can add a static variable like a welcome message. For instance:

public static String welcomeMessage = "Welcome to the School of Code!";
System.out.println(Student.welcomeMessage);

This setup lets you print the welcome message for all instances, thanks to the class-level scope. You won't need a getter method here because it’s already accessible, like a school announcement for everyone to hear.



Key Concepts to Know

Understanding these concepts will help you ace your exams and understand why static variables and methods are like the superheroes of a class, saving the day with their universal accessibility:

  • @Override: Used to indicate that a method in a subclass is meant to override a method in its superclass, helping to ensure accuracy in method signatures.
  • Boolean data type: Represents either true or false, used in conditions and decision-making.
  • Final Keyword: Marks something as final, making it a constant or preventing methods from being overridden.
  • GetGradeDecimal Method: A method that returns the grade as a decimal value, useful for calculations.
  • GetGradeLevel method: Retrieves the grade level of a student.
  • GradeAssignment method: Grades an assignment based on certain criteria.
  • Instance Variables: Variables that belong to an instance (object) of a class.
  • Keyword "static": Declares members that belong to the entire class.
  • Private Access Modifier: Restricts access so the variable or method can only be accessed within its own class.
  • Public Access Modifier: Allows the variable or method to be accessed from anywhere.
  • Static Methods: Belong to the class itself and can be called without creating an object.
  • Static Variables: Belong to the class itself and are shared by all instances.
  • SubmitAssignment method: Allows students to turn in their completed assignments.
  • This Reference: Refers to the current object within a method, useful for instance variables.
  • ToString method: Converts an object into a string representation.


Fun Fact

Did you know? The word "static" comes from the Greek 'statikos,' meaning causing to stand still. So, think of static variables and methods as those reliable friends who are always there and never change their minds, like ever. 😉

Conclusion

And there you have it! Static variables and methods are like the wise old sages who apply their knowledge universally across the land (or in this case, the class). They keep things stable, consistent, and incredibly useful. Keep these super static powers in your toolbox and remember: with great power comes great responsibility. Happy coding! 🚀

Knowunity is the # 1 ranked education app in five European countries

Knowunity was a featured story by Apple and has consistently topped the app store charts within the education category in Germany, Italy, Poland, Switzerland and United Kingdom. Join Knowunity today and help millions of students around the world.

Ranked #1 Education App

Download in

Google Play

Download in

App Store

Knowunity is the # 1 ranked education app in five European countries

4.9+

Average App Rating

15 M

Students use Knowunity

#1

In Education App Charts in 12 Countries

950 K+

Students uploaded study notes

Still not sure? Look at what your fellow peers are saying...

iOS User

I love this app so much [...] I recommend Knowunity to everyone!!! I went from a C to an A with it :D

Stefan S, iOS User

The application is very simple and well designed. So far I have found what I was looking for :D

SuSSan, iOS User

Love this App ❤️, I use it basically all the time whenever I'm studying

Can't find what you're looking for? Explore other subjects.