Static Methods
Part of the Object Oriented Programming section of Coddy's Java journey — lesson 16 of 87.
Just like static variables belong to the class rather than instances, static methods also belong to the class itself. You can call them without creating an object.
Declare a static method by adding the static keyword:
public class MathHelper {
public static int add(int a, int b) {
return a + b;
}
public static int multiply(int a, int b) {
return a * b;
}
}
// Call without creating an object
int sum = MathHelper.add(5, 3); // 8
int product = MathHelper.multiply(4, 2); // 8Static methods have one important restriction: they cannot access instance variables or instance methods directly. Since static methods exist without an object, there's no this reference to work with.
public class Counter {
private int count; // Instance variable
private static int total; // Static variable
public static void incrementTotal() {
total++; // OK - accessing static variable
// count++; // Error! Cannot access instance variable
}
}Static methods are ideal for utility operations that don't depend on object state - think of methods like Math.sqrt() or Integer.parseInt(). They provide functionality that makes sense at the class level rather than for individual objects.
Challenge
EasyLet's build a StringUtils utility class that provides helpful string manipulation methods without needing to create any objects - perfect for demonstrating static methods!
You'll create two files to organize your code:
StringUtils.java: Create a utility class with static methods that perform common string operations:- A static method
countVowels(String text)that returns the number of vowels (a, e, i, o, u - both uppercase and lowercase) in the given string - A static method
reverse(String text)that returns the string reversed - A static method
isPalindrome(String text)that returnstrueif the string reads the same forwards and backwards (case-insensitive),falseotherwise
- A static method
Main.java: Use your utility class to process a string. You'll receive one input: a text string. Call each static method directly through the class name and print three lines:Vowels: [count]Reversed: [reversed string]Palindrome: trueorPalindrome: false
You will receive one input: a text string to analyze.
Remember that static methods are called using the class name (like StringUtils.countVowels(text)) rather than creating an instance first. This makes utility classes convenient for operations that don't need to maintain any state between calls.
Cheat sheet
Static methods belong to the class itself and can be called without creating an object. Declare them using the static keyword:
public class MathHelper {
public static int add(int a, int b) {
return a + b;
}
}
// Call without creating an object
int sum = MathHelper.add(5, 3); // 8Important restriction: Static methods cannot access instance variables or instance methods directly, since they exist without an object and have no this reference:
public class Counter {
private int count; // Instance variable
private static int total; // Static variable
public static void incrementTotal() {
total++; // OK - accessing static variable
// count++; // Error! Cannot access instance variable
}
}Static methods are ideal for utility operations that don't depend on object state, like Math.sqrt() or Integer.parseInt().
Try it yourself
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine();
// TODO: Use StringUtils static methods to analyze the text
// Call StringUtils.countVowels(text) to get vowel count
// Call StringUtils.reverse(text) to get reversed string
// Call StringUtils.isPalindrome(text) to check if palindrome
// TODO: Print the results in the format:
// Vowels: [count]
// Reversed: [reversed string]
// Palindrome: true/false
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsFields (Attributes)Constructor MethodConstructor OverloadingRecap - Simple Calculator4Inheritance
Basic Inheritance (extends)The super KeywordMethod Overriding (@Override)Constructor ChainingThe Object ClassSingle & Multilevel InheritWhy No Multi Class InheritRecap - Employee Hierarchy7Special Methods & Object Class
toString() Methodequals() and hashCode()clone() MethodcompareTo() and ComparableComparator InterfaceRecap - Custom Sorting2Access Modifiers & Encapsulate
Access Levels OverviewGetter and Setter MethodsInformation HidingThe final KeywordRecap - Bank Account Manager5Polymorphism
Method Overloading BasicsMethod Overriding (Run-Time)Upcasting and DowncastingThe instanceof OperatorAbstract Classes and MethodsRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceAggregation vs CompositionInner Nested & Anonymous ClassEnums and Enum MethodsRecords (Java 16+)Sealed Classes (Java 17+)3Class Props & Static Member
Instance vs Static VariablesStatic MethodsStatic BlocksConstants (static final)Recap - Counter & Utility6Interfaces & Abstract Classes
Introduction to InterfacesImplementing InterfacesMulti Interface ImplemenDefault & Static in InterfaceAbstract Classes vs InterfacesFunctional InterfacesRecap - Payment System