Methods in Java
Java methods are essential building blocks that specify how classes and objects behave. They act similarly to functions, procedures, or subroutines in other programming languages by encapsulating a series of instructions to carry out particular tasks. By allowing large problems to be divided into smaller, more manageable components, methods are essential for writing modular, legible, and reusable code.
Defining Methods
A Java class’s structure and functionality are specified when a method is defined. A method declaration typically consists of the following: modifiers, a return type, the method name, and a list of parameters, followed by the method body surrounded in curly braces:
modifier returnType nameOfMethod (Parameter List) {
// method body
}

- modifier: This controls the method’s access level (
public
,private
,protected
, or default), hence limiting the program’s access points. - returnType: The data type of the value that the method will return to the caller code is indicated by the returnType parameter. It could be any legitimate Java type, including object or primitive kinds.
- nameOfMethod: The method’s nameOfMethod is its selected identifier. Java convention recommends capitalising consecutive words (camel notation) after a lowercase letter at the beginning of method names.
- Parameter List: When the method is called, the type and name of variables that will receive input values (arguments) are specified in this comma-separated list. A method still needs an empty set of brackets () if it accepts no inputs.
- method body: The actual executable code statements that specify the function of the method are contained here.
Return Types and Void Methods
The returnType
of a method determines the kind of data that is generated as an output. A method must employ the return value;
statement if it is intended to provide a result. Value
is an expression whose type matches the returnType
that the method has declared. For instance, an int
or double
return type would normally be used in a method that determines the maximum of two values and returns the calculated maximum.
The reason void
return-type methods are unique is that they don’t return any value. These methods mostly carry out operations, including changing an object’s state or printing output. A void
method can cease execution in two ways: either by reaching its closing curly brace }
or by executing a return;
statement (without a value).
Here is a Java code example illustrating both types of methods:
public class MethodExample {
// Method with an 'int' return type: calculates and returns a sum.
public static int calculateSum(int a, int b) {
int sum = a + b;
return sum; // Returns the calculated sum.
}
// Method with a 'void' return type: prints a message without returning data.
public static void displayMessage(String message) {
System.out.println("Message: " + message);
// No return statement needed for void methods unless an early exit is required.
}
public static void main(String[] args) {
// Calling calculateSum() and using its returned value
int result = calculateSum(10, 5);
System.out.println("The result of the sum is: " + result); // Output: The result of the sum is: 15
// Calling displayMessage()
displayMessage("Hello Java Programmers!"); // Output: Message: Hello Java Programmers!
}
}
Output:
The result of the sum is: 15
Message: Hello Java Programmers!
While displayMessage
runs a print action with no value returned, the calculateSum
method does a calculation and returns the amount explicitly.
Calling Methods
A method must be invoked or called in order to be used. Control of the program shifts to the called method when a method call takes place. Control immediately after the method invocation returns to the point in the calling routine where the statements in the called method have been executed.
Instance methods, or methods linked to objects, are usually invoked by using the dot (.
) operator to an object reference (e.g., myObject.myMethod()
). ClassName.myMethod()
or myMethod()
are examples of class names that can be used to activate a method that is specified as static
(a class method) or that is being called from within the same class.
Parameters: Passing Arguments by Value
A method’s parameters are variables that are declared in the method’s definition and act as stand-ins for the values that are entered when the method is called. Arguments are the names given to these input values. Java passes parameters primarily using a process known as pass-by-value.
When a method receives arguments of primitive data types (such int
, double
, boolean
, or char
), Java copies the value of the argument and assigns it to the method’s parameter. This implies that any changes made to the parameter inside the method will only impact that local copy and won’t change the value of the original argument in the calling method.
Here’s an example illustrating this concept:
public class PassByValueDemo {
public static void changePrimitiveValue(int number) {
number = number + 20; // This changes the 'number' parameter (a copy)
System.out.println("Inside method: The modified number is " + number); // Output: Inside method: The modified number is 30
}
public static void main(String[] args) {
int originalNumber = 10;
System.out.println("Before method call: Original number is " + originalNumber); // Output: Before method call: Original number is 10
changePrimitiveValue(originalNumber); // Pass a copy of originalNumber
System.out.println("After method call: Original number is still " + originalNumber); // Output: After method call: Original number is still 10
}
}
Output:
Before method call: Original number is 10
Inside method: The modified number is 30
After method call: Original number is still 10
As demonstrated, originalNumber
retains its initial value of 10
even after the changePrimitiveValue
method is invoked.This attests to the fact that the technique worked with a different copy of the value. The behaviour that is frequently referred to as “effectively pass-by-reference” for non-primitive types results from the fact that, even though objects are also passed by value (more precisely, a copy of the object reference is passed), modifications made to the object’s internal state through this copied reference will impact the original object.
The Method
Java’s main
method, which serves as the gateway to all standalone applications, has a special and important function. In order to start the execution of a Java application, the Java Virtual Machine (JVM) expressly searches for and invokes this method. There must be at least one class defining this main
function in any Java executable application.
Its precise signature is public static void main(String[] args)
, with each keyword carrying specific meaning:
- public: The
main
function can be accessed from outside the class thanks to this access modifier, which allows the JVM to call it when the application launches. - static: By using the
static
keyword,main
can be called immediately without requiring the creation of a class instance (object). Becausemain
is the first method to be executed before any object instantiation this is crucial. - void:
Main
is avoid
method, meaning it gives the JVM no value. Java usesSystem.exit()
to handle exit codes and program termination, in contrast to several other languages. - main: This is the fixed, case-sensitive name that the JVM looks for when it wants to launch a program. Any alternative capitalisation, such as
Main
, may cause the JVM to fail to locate the entry method, resulting in a runtime error. - String[] args: This declares an array of
String
objects, usually calledargs
, as the sole parameter. When the program is launched, any command-line arguments are supplied to it and stored in this array. The arrayargs
is still formed even if no arguments are supplied, however it will be empty.
The main
method to start the application usually only needs to be in one class, even though a complicated application may have several classes. Notably, some Java program types like applets do not utilise a main
method because the environment (like a web browser) controls their execution in a different way.
Why is it called methods?
In Java, the executable parts of a class are referred to as methods. This terminology is deeply rooted in Java’s object-oriented programming (OOP) paradigm.
Here’s why they’re called methods:
- Association with Objects and Classes – In Java, code must reside inside a class. Methods are explicitly defined within a class and operate on the data (instance variables) of that class or its objects. They define how the data within a class can be used and are the primary means by which objects communicate with each other.
- Emphasis on Object-Oriented Principles – The term “method” is used to reflect the concept that these routines are part of an object’s behaviour. This aligns with encapsulation, where methods and data are wrapped together within an object, controlling access to its members.
- Distinction from Other Languages – While other programming languages, such as C/C++, might use terms like “functions,” “procedures,” or “subroutines” for similar executable code blocks, Java specifically uses “method” to underscore their role as members of a class or object.
- Technical Correctness – In Java documentation and professional contexts, “method” is considered the more technically correct term, although “function” is sometimes used interchangeably in general discussions.
Essentially, a method in Java is a subroutine that defines a set of actions to be performed, typically manipulating the internal state of an object.