Calling Class Methods
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.
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];
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.
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.
See it in action
Worked examples
Let's walk through a couple of scenarios to make this crystal clear.
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:
- 1Identify the ToolsThe formula involves pi (π) and squaring a number (r²). These are universal mathematical concepts. This is a huge clue that the
Mathclass, a library of static math methods, is the right tool. - 2
Find the
MathMembers: We need π and a power function.- The
Mathclass has astaticconstant for pi:Math.PI. - The
Mathclass has astaticmethod for powers:Math.pow(base, exponent).
- The
- 3Write the CodeWe'll define the radius and then use the
Mathclass 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."); } } - 4Why this worksWe didn't need to create a
Mathobject because area calculation is a pure, universal function. TheMathclass provides these functions as shared utilities for any part of any program to use.
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:
- 1Design the Utility ClassThis 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
ValidationUtilsclass. - 2Create the Static MethodInside
ValidationUtils, we'll write astaticmethodisUsernameValid. It will take aStringas a parameter and return aboolean(trueif valid,falseotherwise).// 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; } } - 3Use the MethodNow, 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)); } } - 4Why this is good designWe'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
isUsernameValidmethod in one place. Every part of our application that uses it will automatically get the update.
Try it yourself
Ready to try it yourself? Here are a couple of challenges.
- 1Vowel CounterCreate a new class named
StringUtil. Inside this class, define apublic staticmethod calledcountVowelsthat accepts aStringand returns anintrepresenting the number of vowels (a, e, i, o, u, case-insensitive) in that string. In yourmainmethod, test it with a few different words. - 2Game NightYou'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 apublic staticmethod in yourmainclass calledrollTwoDicethat calls your single-die-roll logic twice and prints the result of each roll and their sum.
Practice — 8 questions
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.
// 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();
- 1.10.A: Develop code to call class methods and determine the result of those calls.
- 1.10.A.1
- Class methods are associated with the class, not instances of the class. Class methods include the keyword static in the header before the method name.
- 1.10.A.2
- Class methods are typically called using the class name along with the dot operator. When the method call occurs in the defining class, the use of the class name is optional in the call.
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];
Read what Saavi narrates
Hello, AP scholars! I'm Saavi, and welcome to Shrutam.
Think about your high school for a second. Some things are yours and yours alone, like your student ID. But other things are shared, like the big clock in the hallway. You don't need your own personal clock to know the time; you just look up at the one the school provides for everyone.
In programming, class methods are like that school clock. They're shared tools that belong to a class as a whole, not to any one object. We use them for tasks that aren't tied to a specific object's data. You can spot them because they always have the keyword `static` in their definition.
Let's walk through an example. Imagine you're coding a program for a pizzeria in Chicago. You need to calculate the area of a pizza to figure out how much cheese to use. The formula is pi times the radius squared.
Now, pi and the power function are universal math concepts, right? They don't belong to any one pizza. So, we use Java's built-in `Math` class, which is full of static methods.
To find the area of a 14-inch pizza, which has a 7-inch radius, our code would look something like this. We'd create a variable called area, and set it equal to `Math.PI`... that's the static value for pi... times `Math.pow(radius, 2)`. Notice we're using the class name, `Math`, to call these tools. We don't need to, and can't, create a `Math` object. We just use the class itself.
Now, here's a spot where a lot of us can get tripped up. A common mistake is to try to call a static method on an object. For example, if you had a `TempConverter` class with a static method, you might be tempted to create a `TempConverter` object and call the method on that. But that's misleading. The method belongs to the class, so you should call it with the class name, like `TempConverter.fahrenheitToCelsius()`. It's clearer and the correct convention.
Class methods are a fundamental part of writing clean, organized code. You're learning how to create and use a shared toolkit that any part of your program can access. Keep practicing, and I'll see you in the next lesson.
While this might compile, it's misleading. It implies the method belongs to the `myConverter` object, but it actually belongs to the `TempConverter` class. It's like asking your personal librarian to tell you the hours for the entire city's library system—they can, but you should have just looked at the main website.
Use the class name. It's clearer and the standard convention.
double celsius = TempConverter.fahrenheitToCelsius(98.6); // Correct
The `Math` class is not designed to be instantiated. Its constructor is private, so this code won't even compile. The class exists only to hold static methods and constants.
Call the methods directly on the class.
double val = Math.abs(-10); // Correct
Without `static`, `add` is an instance method. It can't be called on the class name. You would need to create a `MyUtils` object first.
Add the `static` keyword to the method definition if you intend for it to be a class method.
public static int add(int a, int b) { ... } // Correct
A static method is shared by the whole class. It doesn't know which specific `Player` object's `name` you're talking about. `this` and instance variables don't exist in a static context.
Pass any required information as parameters to the static method, or make the method non-static if it truly needs to operate on an object's state.
public class Player {
private String name; // Instance variable
public Player(String name) {
this.name = name;
}
public static String getRules() {
// Trying to access 'name' from a static context
return "The rules are simple, " + this.name; // Error!
}
}