A static method is limited to interacting with static variables and is unable to access instance variables. This is due to the static method being associated with the class itself. To call or reference a static method, the required syntax is as follows: class name. the method name. If there is a need to utilize a non-static method within a static method, one must create an instance for the class first.
CARVIEW |
A Guide on Static Methods in Java With Examples
A static method in Java is associated with the class itself rather than individual instances or objects of the class. It operates at the class level and can be accessed and invoked without creating an instance of the class.
The function main
is an instant example of a static
method of any class in Java. It is automatically called at the start of the program when no object of that class is instantiated.
Let’s look at the static methods in Java in more detail.
We’ll cover:
Java for Programmers
Java is one of the most sought after and widely used programming languages in the tech industry, and will continue to be for the foreseeable future. It runs on everything from phones to game consoles to data centers. This path is perfect for you if you already have experience programming, but are new to Java. It’ll help you become an employable Java developer with incredibly valuable skills, ready to jump in and contribute to real-world projects.
Introduction to Static Methods in Java#
The keyword static
is used as a modifier with methods and attributes. The static methods in Java are considered class-level methods. They are not attached to a specific object of the class. They can be called using the class name or object name from anywhere in the program as per access permission. They can also be called from within the class without using any qualifiers (class/object names).
In Java, the keyword this
, used as a reference to the current class instance, is available in the class methods that are not defined as static
. It is used to access the generally used (non-static) data members of the calling object.
Particularly, when a local variable or method parameter has the same name as an instance variable, this
can help disambiguate between the local variable/parameter and the instance variable. Since static
methods are not tied to specific instances, they do not have the this
available to directly access the instance variables or invoke non-static (instance) methods. The keyword static
in the method declaration indicates its association with the class, rather than with any particular object of that class. Let’s have a look at an example of a static method.
class MyClass {private int myVariable;public void setMyVariable(int myVariable) {this.myVariable = myVariable; // Using "this" to refer to the instance variableSystem.out.println("In setMyVariable() method.");}public static void setStaticVariable() {// this.myVariable = 100; // No "this" in itSystem.out.println("In setStaticVariable() method.");}public static void main(String[] args) {System.out.println("In main() method.");MyClass.setStaticVariable();MyClass obj = new MyClass();obj.setMyVariable(5);}}
In the above example:
-
Line 5: In the
setMyVariable
method,this.myVariable
refers to the instance variablemyVariable
, whilemyVariable
alone refers to the method parameter. -
Line 16: To call a static method, we use the class name followed by the method name, like
MyClass.setStaticVariable()
, without the need to create an object of the class. However, the methodsetMyVariable()
can’t be called using the class name. -
Lines 17–18: There must be an instance (object),
obj
, of the class to invokeobj.setMyVariable(5)
. In this particular call tosetMyVariable()
, the keywordthis
refers toobj
, which is the calling object of the method.
This distinction from instance methods allows the static methods to be accessed conveniently. Having no attachment to the calling object makes the static methods suitable for defining utility functions, helper methods, factory methods, and other class-level operations.
Grokking Coding Interview Patterns in Java
With thousands of potential questions to account for, preparing for the coding interview can feel like an impossible challenge. Yet with a strategic approach, coding interview prep doesn’t have to take more than a few weeks. Stop drilling endless sets of practice problems, and prepare more efficiently by learning coding interview patterns. This course teaches you the underlying patterns behind common coding interview questions. By learning these essential patterns, you will be able to unpack and answer any problem the right way — just by assessing the problem statement. This approach was created by FAANG hiring managers to help you prepare for the typical rounds of interviews at major tech companies like Apple, Google, Meta, Microsoft, and Amazon. Before long, you will have the skills you need to unlock even the most challenging questions, grok the coding interview, and level up your career with confidence. This course is also available in JavaScript, Python, Go, and C++ — with more coming soon!
Uses of Static Methods#
Most of the time, we might have developed programs without frequently using the static methods, except for main()
being the entry point of every Java program. The following are the common uses of static methods.
Utility Function
This refers to a function that provides commonly used functionality or performs a specific task that is not tied to a specific object or instance. The examples are:
-
To encapsulate a specific functionality or operation frequently needed in various contexts.
-
To operate solely on the input parameters provided to them, independent of object state (making them stateless) to be called without the need to create an object.
-
To perform mathematical calculations, string manipulation, file handling, and various data transformations.
class Util {public static void printArray(int[] array) {for (int num : array) {System.out.print(num + " ");}System.out.println();}}class Main {public static void main(String[] args) {int[] numbers = { 3, 8, 1, 6, 4 };Util.printArray(numbers);}}
In this example, the printArray()
, defined on lines 2–7, is a utility method provided by the Util
class. It’s a general-purpose method that prints the elements of an array. Utility methods like this can be reused across different parts of our applications.
Qualifying it with the class or object name is mandatory when calling it from outside its class.
Zero to Hero in Java
Java is one of the most sought after, widely used, and in-demand programming languages in the global job market today because it is easy to learn, object-oriented, and modular. This path is perfect for you if you are new to programming. This path will teach you real-world problem-solving techniques and how to write step-by-step solutions in Java. You will start by covering Java's basic syntax and functionality to create basic programs. In the latter half, you will get a detailed overview of object-oriented programming to create clean, scalable, and modular code. Finally, you will get hands-on experience practicing the implementations of commonly used data structures and classes in Java. By the end of this path, you will be able to write real-world programs in Java and start your career as a Java developer.
Helper Method#
This refers to a method that provides auxiliary or supportive functionality within a class. It is designed to assist other methods or operations by performing specific subtasks or providing common functionality in a modular and reusable manner. Helper methods enhance the overall structure of a program and improve its maintainability by encapsulating common functionality into reusable blocks of code. The examples are:
-
To validate data or the overall state of the system before changing the instance-level state to avoid inconsistency or anomaly.
-
To simplify complex operations by breaking them into smaller, more manageable steps, like recursion (using the parameters).
-
To promote code modularity and maintainability by providing a centralized location for commonly used functionality.
class MathHelper {public static int calculateSquare(int number) {return number * number;}public void fun() {int answer = this.calculateSquare(6);System.out.println("Square of 6: " + answer);}public static void main(String[] args) {int result = calculateSquare(5);System.out.println("Square of 5: " + result);}}
In this example, calculateSquare()
, defined on lines 2–4, is a helper method that computes the square of a number. It assists the main()
method by calculating and returning the square of an integer parameter.
The calculateSquare()
method can be called with or without using the class name from main()
of the same class. Similarly, it can be called with or without using the object name this
from the same class’s non-static method fun()
.
A Complete Guide to Java Programming
This course is your detailed guide to the fundamentals of the Java programming language. This course will get you on the fast track to becoming a proficient and modern Java developer. In this course, you will start by covering different programming paradigms like object-oriented and procedural programming. You will then cover the fundamentals of programming in Java such as: objects and data types, variables, arrays, and conditional statements. In the latter half of the course, you will cover iterative constructs, useful algorithms, and data structures. With over 100 problems, 11 quizzes, and 9 challenges, this course will get you prepared for a career in software development.
Factory Method#
The factory method is a design pattern. It outlines a procedure for generating objects of a class or subclasses. It is especially valuable when we want to encapsulate complex object creation logic. For example, when we want to restrict the object instantiation to a specific number like Singleton.
The Singleton pattern ensures that a class has only one instance and provides a global access point to that instance. This is typically achieved by controlling the instantiation process through static methods and private constructors.
When combining these patterns, we might have a factory method that returns a singleton instance of a specific class. The following is a simple example:
class Singleton {private static Singleton object;private Singleton() {// Private constructor to prevent direct instantiation}public static Singleton getInstance() {if (object == null) {object = new Singleton();}return object;}public void showMessage() {System.out.println("Hello from Singleton!");}public static void main(String[] args) {Singleton myObject = Singleton.getInstance();myObject.showMessage();}}
In this example, the Singleton
class directly manages the creation of the singleton instance through the getInstance()
method.
-
Line 2: A static attribute
object
is declared to keep hold of the instance of the class to be shared by all its users. -
Lines 4–6: An empty constructor is defined as
private
to control the instantiation. -
Lines 8–13: The
getInstance()
method is defined to return the previously or newly created object.- Line 9: The existence of the first instance is checked through the current value of
obj
. - Line 10: The object is created and stored to the static data member
object
for returning to its users. - Line 12: The instance stored in
object
is returned to thegetInstance()
caller.
- Line 9: The existence of the first instance is checked through the current value of
-
Lines 15–17: A non-static method
showMessage()
is defined to demonstrate the successful instantiation. The instance can’t be created here using the keywordnew
due to the constructor beingprivate
. -
Lines 19–22: The
main()
method is defined asstatic
so that it is used as the program’s entry point before the class instantiation.- Line 20: The class instance is obtained through a call to
getInstance()
and stored in the variablemyObject
. Using the class name for calling the method is not mandatory here becausemain()
is also part of the same class. - Line 21: The non-static method of the class is called through
myObject
because it can’t be called without the object from a static method.
- Line 20: The class instance is obtained through a call to
When the getInstance()
method is first called, it creates the instance if it doesn’t already exist. Subsequent calls to getInstance()
return the existing instance.
The getInstance()
method acts as a factory method responsible for creating and providing access to the single instance of the class. It encapsulates the logic for creating and maintaining the instance.
The concept of encapsulating the instantiation process and providing controlled access to instances aligns with the essence of a factory method.
Software Design Patterns: Best Practices for Software Developers
Being good at problem-solving is one thing but to take your career to the next level, one must know how complex software projects are architected. Software design patterns provide templates and tricks used to design and solve recurring software problems and tasks. Applying time-tested patterns result in extensible, maintainable and flexible high-quality code, exhibiting superior craftsmanship of a software engineer. Being well-versed in knowledge of design patterns allows one to spot brittle and immature code from miles away. The course goes to great lengths to lay bare the esoteric concepts of various design patterns before the reader and is replete with real-world examples and sample code. The readership for this course is expected to be familiar with some object orientated language. The course examples and snippets are written in the Java language but folks with experience in other OOP languages should easily be able to follow the discussion and code intent.
Keep In Mind#
Static methods are very useful when developing applications in Java. They can be used as helper and utility functions for other parts of the class/application. The following points are important to remember when using the static members in Java.
Instance Members#
Non-static members that are termed instance members are not directly accessible from static members. They are required to be qualified through an object. The static methods can be called without the object. The keyword this
is also not accessible from the static methods so attempting to qualify an instance member with this
will fail in those methods.
Polymorphism#
Polymorphism is a powerful feature of the object-oriented programming (OOP) paradigm. It provides the facility of calling the correct version of the method depending on the instance held by the base reference. It means we can call an overridden version of a base class method in its derived class using a derived instance through a base reference.
The static methods are class-level operations therefore they cannot be overridden. It’s not a weakness of Java; it’s the technically correct implementation. The static methods do not carry an implicit reference to the calling object (through this
) therefore they cannot implicitly trace the type of calling object.
Memory Matters#
Static members are class-level features. They are provided as shared facilities for all instances of the class. Their construction and destruction are not bound to the life of any object. They are allocated in the memory at the start of the execution of the program or at the time of loading of the class. They are not garbage collected; therefore, they stay in the memory till the end of the program. We need to be more cautious about memory leaks due to the same reason.
Wrapping up and Next Steps#
A static method can be accessed using the class name (without instantiating any object). Here are the pros and cons of static methods in Java.
-
The
static
method can be called from outside the class using the class or object name. However, using these qualifiers is optional when calling them from the methods of the same class. -
The
static
methods do not have thethis
keyword inside their definition because no object is tied to them. -
It is mandatory to use the object name when accessing the non-static methods or attributes from the
static
methods. -
The
static
method is a class-level operation; therefore, it can’t be overridden. -
The
static
members (including the data members) are created when loading the class into the memory and are not deleted from the memory like instance data members.
The static
methods are suitable for defining the class-level operations, e.g., utility functions, helper methods, and factory methods. They are not used to provide the public interface to deal with the individual objects of the class.
Keep exploring, keep coding, and happy learning!
To get started with learning these concepts and more, check out Educative’s Java for Programmers and Zero to Hero in Java paths.
Continue learning about the subject#
Frequently Asked Questions
How to call a static method in Java?
How to call a static method in Java?
Free Resources