Free for students · Ad-free · WCAG 2.1 AA Compliant · Accessibility

Calling Class Methods

Lesson ~10 min read 8 MCQs

In simple terms: In simple terms, class methods are like shared tools that belong to a whole category of things, not just one specific item. You use them by calling the category's name directly.

Why this matters

Think about your high school. Some things belong to you and you alone, like your student ID card or your specific locker combination. To use them, you need your specific card or your combo.

But other things are shared resources. The big clock in the main hallway, the school's official website, or the PA system for announcements—these belong to the school as a whole. Anyone can use them. You don't need your own personal school clock to check the time; you just look up at the one the school provides for everyone.

In programming, we have the same distinction. Some methods belong to individual objects (like your locker combo), while others are shared tools that belong to the entire class (like the school clock). Today, we're going to focus on those shared tools: class methods.

Comparing instance-specific vs. class-wide resources.

Concept overview

flowchart TD
    A[Start: Need to call a method] --> B{Is the method declared with `static`?};
    B -- Yes --> C[It's a Class Method];
    B -- No --> D[It's an Instance Method];
    C --> E{Am I calling from inside the same class?};
    E -- Yes --> F[Call with `methodName()`];
    E -- No --> G[Call with `ClassName.methodName()`];
    D --> H[Create an object first: `MyClass obj = new MyClass()`];
    H --> I[Call with `obj.methodName()`];
    F --> J[End];
    G --> J[End];
    I --> J[End];
This flowchart diagram illustrates the process of calling a method in Java. It starts by asking if the method is static, branching to 'Class Method' or 'Instance Method' accordingly, and then shows the correct syntax for each scenario.

Core explanation

So far in your Java journey, you've mostly seen methods that belong to objects. For example, if you have a Dog object named fido, you might call fido.bark(). That action is tied directly to that specific fido object.

Visualizing the difference: instance methods vs. class methods.

But what about actions or calculations that aren't tied to any one object? That's where class methods come in.

What Makes a Method a Class Method?

A class method is a method that belongs to the class itself—the blueprint—rather than any individual object created from that blueprint.

The key to identifying a class method is the static keyword.

static: A Java keyword that indicates a method or variable belongs to the class, not to any one instance (object). There is only one copy of a static member, shared by all objects of that class.

Let's look at a method header: public **static** void doSomething()

That static keyword is our big signal. It tells us doSomething() is a class method. If static is missing, it's a regular instance method that needs an object to be called.

The Ultimate Analogy: A Public Library

Imagine a public library system for a city like Seattle.

  • Instance Method
    myLibraryCard.checkoutBook(). This action is specific to your library card object. It affects your personal account, your due dates.
  • Class Method
    SeattlePublicLibrary.getTodaysHours(). This information is the same for everyone. It belongs to the library system as a whole, not your individual card. You don't need a library card in your hand to look up the hours online.

Class methods are the getTodaysHours() of the programming world. They are shared utilities.

How to Call a Class Method

Because class methods belong to the class, you call them using the class name, followed by a dot, followed by the method name.

The syntax is: ClassName.methodName(arguments);

The most famous example in all of Java is the Math class. The Math class is a collection of common mathematical functions. It wouldn't make sense to create a Math object. Math is universal!

// We don't create a Math object. We use the class directly.

// Find the absolute value of -15
double absValue = Math.abs(-15.0); // absValue is now 15.0

// Calculate 2 to the power of 5
double powerResult = Math.pow(2, 5); // powerResult is now 32.0

// Get a random number between 0.0 (inclusive) and 1.0 (exclusive)
double randomNumber = Math.random();

Notice the pattern: Math.abs(), Math.pow(), Math.random(). We're always using the class name, Math, to call these static methods.

Creating Your Own Class Methods

Let's create a simple utility class to see this in action. Imagine we're building an app and frequently need to convert temperatures.

public class TempConverter {

    // This is a class method. Notice the 'static' keyword.
    // It takes a temperature in Fahrenheit and returns it in Celsius.
    public static double fahrenheitToCelsius(double fahrenheit) {
        return (fahrenheit - 32) * 5.0 / 9.0;
    }

    // Another class method.
    public static double celsiusToFahrenheit(double celsius) {
        return (celsius * 9.0 / 5.0) + 32;
    }
}

Now, in another part of our program (like our main method), we can use these tools without ever creating a TempConverter object.

public class WeatherApp {
    public static void main(String[] args) {
        double tempInBostonF = 75.5;

        // Call the static method using the class name
        double tempInBostonC = TempConverter.fahrenheitToCelsius(tempInBostonF);

        System.out.println("The temperature in Boston is " + tempInBostonC + "°C.");
        // Output: The temperature in Boston is 24.166...°C.
    }
}

This is incredibly useful! We've created a reusable tool that any part of our code can access just by knowing the TempConverter class name.

The One Exception: Calling from Inside

There's one situation where you don't have to use the class name.

If you are calling a static method from within the same class where it is defined, the class name is optional.

Let's add another method to our TempConverter class:

public class TempConverter {

    public static double fahrenheitToCelsius(double fahrenheit) {
        return (fahrenheit - 32) * 5.0 / 9.0;
    }

    public static double celsiusToFahrenheit(double celsius) {
        return (celsius * 9.0 / 5.0) + 32;
    }

    // A new static method to display a conversion table
    public static void displayFahrenheitConversion(double f_temp) {
        // Calling another static method from WITHIN the same class.
        // Notice we don't need "TempConverter." here.
        double c_temp = fahrenheitToCelsius(f_temp); 
        System.out.println(f_temp + "°F is " + c_temp + "°C.");
    }
}

Inside displayFahrenheitConversion, we can just write fahrenheitToCelsius(f_temp) instead of TempConverter.fahrenheitToCelsius(f_temp). Java knows you mean the static method in the current class.

The `static` keyword is the key identifier for class methods.
Tracing `Math.pow(2, 5)`: a static method in action.

See it in action

python
Line 1
Output
Click Run to see the output.

        
Try these
    © Shrutam.ai

    Worked examples

    Let's walk through a couple of scenarios to make this crystal clear.

    Example 1

    The Pizzeria Calculator

    Problem: You're writing software for a pizzeria in Chicago. You need to calculate the area of a pizza to determine how much cheese is needed. The formula for a circle's area is πr². Write code to find the area of a 14-inch pizza.

    Solution Walkthrough:

    1. 1
      Identify the Tools
      The formula involves pi (π) and squaring a number (r²). These are universal mathematical concepts. This is a huge clue that the Math class, a library of static math methods, is the right tool.
    2. 2

      Find the Math Members: We need π and a power function.

      • The Math class has a static constant for pi: Math.PI.
      • The Math class has a static method for powers: Math.pow(base, exponent).
    3. 3
      Write the Code
      We'll define the radius and then use the Math class methods to perform the calculation. A 14-inch pizza has a radius of 7 inches.
      public class PizzeriaCalculator {
          public static void main(String[] args) {
              double diameter = 14.0;
              double radius = diameter / 2.0;
      
              // Call static members from the Math class
              // We use Math.PI for pi and Math.pow() for the exponent.
              double area = Math.PI * Math.pow(radius, 2);
      
              System.out.println("A " + diameter + "-inch pizza has an area of " + area + " square inches.");
          }
      }
    4. 4
      Why this works
      We didn't need to create a Math object because area calculation is a pure, universal function. The Math class provides these functions as shared utilities for any part of any program to use.
    Example 2

    A Username Validator

    Problem: You're creating a sign-up page. You need a helper method that checks if a proposed username is valid. For now, a valid username must simply be between 4 and 10 characters long. Since this check might be needed in multiple places, it should be a reusable utility.

    Solution Walkthrough:

    1. 1
      Design the Utility Class
      This is a perfect job for a static method. The check doesn't depend on any specific user's data, just the username string itself. Let's create a ValidationUtils class.
    2. 2
      Create the Static Method
      Inside ValidationUtils, we'll write a static method isUsernameValid. It will take a String as a parameter and return a boolean (true if valid, false otherwise).
      // File: ValidationUtils.java
      public class ValidationUtils {
          public static boolean isUsernameValid(String username) {
              int len = username.length();
              if (len >= 4 && len <= 10) {
                  return true;
              } else {
                  return false;
              }
              // A more concise way to write this is:
              // return username.length() >= 4 && username.length() <= 10;
          }
      }
    3. 3
      Use the Method
      Now, in another class that handles user sign-up, we can call our new utility method.
      // File: SignUpPage.java
      public class SignUpPage {
          public static void main(String[] args) {
              String user1 = "maya_p"; // Valid
              String user2 = "li";     // Too short
              String user3 = "carlos_santiago_the_third"; // Too long
      
              // Call the static method using ClassName.methodName()
              System.out.println("Is 'maya_p' valid? " + ValidationUtils.isUsernameValid(user1));
              System.out.println("Is 'li' valid? " + ValidationUtils.isUsernameValid(user2));
              System.out.println("Is 'carlos_santiago_the_third' valid? " + ValidationUtils.isUsernameValid(user3));
          }
      }
    4. 4
      Why this is good design
      We've separated the validation logic from the sign-up process. If we later want to add more rules (e.g., "no special characters"), we only have to change the isUsernameValid method in one place. Every part of our application that uses it will automatically get the update.
    Avoid trying to instantiate utility classes like `Math`.

    Try it yourself

    Ready to try it yourself? Here are a couple of challenges.

    1. 1
      Vowel Counter
      Create a new class named StringUtil. Inside this class, define a public static method called countVowels that accepts a String and returns an int representing the number of vowels (a, e, i, o, u, case-insensitive) in that string. In your main method, test it with a few different words.
    2. 2
      Game Night
      You're making a game that involves rolling two dice. Use the Math.random() method to simulate rolling a single six-sided die (a random integer from 1 to 6). Then, create a public static method in your main class called rollTwoDice that calls your single-die-roll logic twice and prints the result of each roll and their sum.
    Tracing `countVowels` for the word 'Hello'.