Methods
a method is a structured block of code designed to perform a specific task, which executes only when explicitly called. Methods act as functions that live inside a class, allowing programmers to reuse code, enforce modularity, and maintain clean applications without repeating logic.
In Java, a method is a structured block of code designed to perform a specific task, which only executes when it is explicitly called. Methods are essential for code reusability (writing code once and using it multiple times) and for breaking complex programs into smaller, manageable pieces
A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println() method, for example, the system actually executes several statements in order to display a message on the console.
A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions
Java Methods are blocks of code that perform a specific task. A method allows us to reuse code, improving both efficiency and organization. All methods in Java must belong to a class. Methods are similar to functions and expose the behavior of objects.
A method allows to write a piece of logic once and reuse it wherever needed in the program.
This helps keep your code clean, organized, easier to understand and manage.
- Performs a specific task,Improves Readability,Allows code reuse
- Can take Parameters and Return a value
- Can be Static or Instance
- Supports Method Overloading
Definition: Two of the components of a method declaration comprise the method signature—the method's name and the parameter types.
The signature of the method declared above is:
calculateAnswer(double, int, double, double)
Naming a Method
Although a method name can be any legal identifier, code conventions restrict method names. By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, etc. In multi-word names, the first letter of each of the second and following words should be capitalized. Here are some examples:
run
runFast
getBackground
getFinalData
compareTo
setX
isEmpty
Typically, a method has a unique name within its class. However, a method might have the same name as other methods due to method overloading.
Overloading Methods
The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists
public class DataArtist {
...
public void draw(String s) {
...
}
public void draw(int i) {
...
}
public void draw(double f) {
...
}
public void draw(int i, double f) {
...
}
}
Overloaded methods are differentiated by the number and the type of the arguments passed into the method. In the code sample, draw(String s) and draw(int i) are distinct and unique methods because they require different argument types.
You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart.
The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.
Basic Syntax
accessModifier returnType methodName(parameterType parameterName) {
// Method Body: Execution logic
return value; // Required if return type is not void
}
Access Modifier: Defines where the method can be accessed (e.g., public, private, protected, or default). It defines the access type of the method.
Return Type: Specifies the data type of the value returned by the method. Use void if the method does not return anything.Method may return a value.
Method Name: The descriptive identifier used to call the method. It follows camel-Case naming conventions and typically starts with a verb.This is the method name. The method signature consists of the method name and the parameter list.
Parameter List: A comma-separated list of input values passed into the method, enclosed in parentheses. It remains empty if no inputs are required.The list of parameters, it is the type, order, and number of parameters of a method. These are optional, method may contain zero parameters.
Method Body: The actual set of executable statements enclosed within curly braces {}.
Contains the logic or statements to be executed.
The method body defines what the method does with the statements.
method declarations have six components, in order:
Modifiers—such as public, private.
The return type—the data type of the value returned by the method, or void if the method does not return a value.
The method name—the rules for field names apply to method names as well, but the convention is a little different.
The parameter list in parenthesis—a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses.
An exception list
The method body, enclosed between braces—the method's code, including the declaration of local variables,
Method Call Stack in Java
Java is an object-oriented and stack-based programming language where methods play a key role in controlling the program's execution flow. When a method is called, Java uses an internal structure known as the call stack to manage execution, variables, and return addresses.
Call Stack
The call stack is a data structure used by the program during runtime to manage method calls and local variables. It operates in a Last-In-First-Out (LIFO) manner, meaning the last method called is the first one to complete and exit.
Methods Execution
When a method is called:
A new stack frame is added to the call stack to store method details.
The method runs its code.
After execution, the stack frame is removed, and control goes back to the calling method.
Java automatically manages the call stack using the Java Virtual Machine (JVM).
Let's use an image to understand how the method call stack works
Why Use Methods?
Breaking code into separate methods helps improve readability, reusability, and maintainability.
Code Reusability: Write once, use multiple times without repeating code so that code reusability increase.
Modularity: Dividing a program into separate methods allows each method to handle a specific task, making the code more organized and easier to manage.
Readability: Smaller, named methods make the code easier to read and understand.
Maintainability: It’s easier to fix bugs or update code when it's organized into methods.
Create a Method
- A method declared inside a class.
- Defined with name of the method ,followed by the parentheses()
A method must be declared within a class. It is defined with the name of the method, followed by parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can also create your own methods to perform certain actions:
Example
Create a method inside Main:
public class Main {
static void myMethod() {
// code to be executed
}
}
Example Explained
myMethod() is the name of the method
static means that the method belongs to the Main class and not an object of the Main class.
void means that this method does not have a return value.
Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a semicolon;
For using a method, it should be called. There are two ways in which a method is called i.e., method returns a value or returning nothing (no return value).
The process of method calling is simple. When a program invokes a method, the program control gets transferred to the called method. This called method then returns control to the caller in two conditions, when −
the return statement is executed.
it reaches the method ending closing brace.
In the following example, myMethod() is used to print a text (the action), when it is called:
Example
Inside main, call the myMethod() method:
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
}
}
public class Main{
static void myMethod(){
//code to be executed
}
}
Explanation
myMethod() => name of the method
void => does not return a value
static => method belongs to main class ,but not object of the main class
Passing Parameters by Value in Java Methods
While working under calling process, arguments is to be passed. These should be in the same order as their respective parameters in the method specification. Parameters can be passed by value or by reference.
Passing Parameters by Value means calling a method with a parameter. Through this, the argument value is passed to the parameter.
Call a Method
write method's name followed by parentheses() and semicolon;
Example
public class Main{
static void myMethod{
system.out.println("working as software developer")
}
public static void main(String[]args){
myMethod();
}
}
A method can be called multiple times
public class Main{
static void myMethod{
system.out.println("working as software developer")
}
public static void main(String[]args){
myMethod();
myMethod();
}
}
Types of Methods in Java
1. Predefined Methods vs User-defined Methods
Predefined Methods
Predefined methods are the method that is already defined in the Java class libraries. It is also known as the standard library method or built-in method.
Built-in methods provided by the Java Standard Library. Examples include System.out.println(), Math.max(), and String.length().
For example, random() method which is present in the Math class and we can call it using the ClassName.methodName() as shown in the below example.
Math.random() // returns random value
Math.PI //returns the value of π as a constant. it is a Constant not a Method
These are already available in Java libraries.
Example of Predefined Methods
System.out.println()
Standard library functions built directly into Java, such as System.out.println() or Math.max().
Program Example:
System.out.println("Hello");
Here, println() is a predefined method.
Standard Library Methods: These are built-in methods in Java that are available to use.
User-defined Methods
Methods created by the programmer.
Custom methods created by developers to handle specific logical workflows
The method written by the user or programmer is known as a user-defined method. These methods are modified according to the requirement.
Example:
sayHello // user define method created above in the article
Greet()
setName()
Example:
int add(int a, int b) {
return a + b;
}
Calling Different Types of Methods in Java
Method calling in Java means invoking a method to execute the code it contains. It transfers control to the process, runs its logic, and then returns to the calling point after execution.
Calling a User-Defined Method
User-defined methods are blocks of code written by the programmer. To execute a user-defined method, we first create an object of the class (if the method is non-static) and then call the method using that object.
Example
class Geeks {
void hello() {
System.out.println("This is a user-defined method.");
}
public static void main(String[] args) {
Geeks obj = new Geeks(); // Create object
obj.hello(); // Call method
}
}
Calling an Abstract Method
Abstract methods have no body and must be overridden in a subclass. They are called using an object of the subclass.
Example 2: Calling Methods in Different Ways
abstract class GeeksHelp {
abstract void check(String name); // Abstract method
}
public class Geeks extends GeeksHelp {
@Override
void check(String name) {
System.out.println(name);
}
public static void main(String[] args) {
Geeks obj = new Geeks(); // Subclass object
obj.check("GeeksforGeeks");
}
}
Output
GeeksforGeeks
Explanation: In the above code an abstract class GeeksHelp with an abstract method check(), which is implemented in the subclass Geeks. In the main() method, an object of Geeks is created to call the implemented check() method.
Calling the Predefined Methods
Java provides many built-in methods via the Java Standard Library, like hashCode().
public class Geeks {
public static void main(String[] args) {
Geeks obj = new Geeks();
System.out.println(obj.hashCode()); // Predefined method
}
}
Output
1510467688
Explanation: In the above code an object of the Geeks class and calls the predefined hashCode() method.
hashCode() returns an integer hash code for the object. This value is used in hash-based collections like HashMap and HashSet. It is not guaranteed to be unique or represent the memory address
Calling a Static Method
Static methods belong to the class, not the object. They can be called without creating an object.
class Test {
static void hello() {
System.out.println("Hello");
}
}
public class Geeks {
public static void main(String[] args) {
Test.hello(); // Call static method directly
}
}
Output
Hello
Explanation: we call a static method hello() from the test class without creating an instance of the class. The method prints "Hello" when invoked from the main method.
-
Static vs. Instance
Static Methods: Declared using the static keyword. They belong directly to the class rather than an object instance, meaning you can call them without creating an object first.
Access the static data using class name. Declared inside class with static keyword.
static - If we use the static keyword, it can be accessed without creating objects.For example, the sqrt() method of standard Math class is static. Hence, we can directly call Math.sqrt() without creating an instance of Math class.
Example:
modifier static returnType nameOfMethod (parameter1, parameter2, ...) {
// method body
}
// Static Method
static void method_name() {
// static method body
}
Instance Methods: Default methods declared without the static keyword. They belong to an object instance and require creating a class object using the new keyword to invoke them.
Access the instance data using the object name. Declared inside a class.
Methods belonging to an object instance. They can access instance variables and require the object initialization using the new keyword before invocation.
Example:
// Instance Method
void method_name() {
// instance method body
}
public class MethodDemo {
// 1. Static method: Calculates and returns an integer value
public static int addNumbers(int num1, int num2) {
return num1 + num2;
}
// 2. Instance method: Executes an action without returning a value
public void printGreeting(String name) {
System.out.println("Hello, " + name + "!");
}
public static void main(String[] args) {
// Calling the static method directly via class logic
int sum = addNumbers(5, 10);
System.out.println("The sum is: " + sum);
// Calling the instance method by creating an object instance
MethodDemo demoObject = new MethodDemo();
demoObject.printGreeting("Alex");
}
}
- Method Parameters
Methods can accept input values.
void add(int a, int b) {
System.out.println(a + b);
}
Explanation
a and b are parameters
- Return Type
A method can return a value using return
Example:
int add(int a, int b) {
return a + b;
}
Usage:
int result = add(5,3);
System.out.println(result);
Output
8
3.Method Without Return Value (void)
If a method does not return anything, we use void.
Example:
void message() {
System.out.println("Welcome");
}
4.Static Methods
Belong to the class,not to the object
Static Method in Java With Examples
In Java, the static keyword is used to create methods that belongs to the class rather than any specific instance of the class. Any method that uses the static keyword is referred to as a static method.
A static method in Java is associated with the class, not with any object or instance.
It can be accessed by all instances of the class, but it does not rely on any specific instance.
Static methods can access static variables directly without the need for an object.
They cannot access non-static variables (instance) or methods directly.
Static methods can be accessed directly in both static and non-static contexts.
Declare Syntax
access_modifier static return_type methodName() {
// method body
}
The name of the class can be used to invoke or access static methods.
Syntax to Call a Static Method
ClassName.methodName();
Example 1: Static Method Cannot Access Instance Variables
The JVM executes the static method first, even before creating class objects. So, static methods cannot access instance variables, as no object exists at that point.
Example 2: Static Methods Accessed from Both Static and Non-Static Methods
Why Use Static Methods?
To access or modify static variables or perform actions not tied to any instance.
Useful for utility or helper classes like Collections, Math, etc.
Restrictions on Static Methods
Non-static data members or non-static methods cannot be used by static methods, and static methods cannot call non-static methods directly.
In a static environment, this and super are not allowed to be used.
Why is the main Method Static in Java?
The main method must be static because the JVM does not create an object of the class before invoking it. If it were a non-static method, JVM would first build an object before calling the main() method, resulting in an extra memory allocation difficulty.
Static Method Vs Instance Method
Instance Methods
Requires an object of the class
Can access both instance and static variables Can access only static variables directly
Called using object reference (obj.methodName()) Called using class name (ClassName.methodName())
Can call both static and instance methods Can call only static methods directly
Associated with object (instance level) Associated with class (class level)
Can use this and super keywords Cannot use this and super
Used for object-specific behavior Used for common/shared behavior
Java uses pass-by-value Java uses pass-by-value
Static Methods
Does not require an object
class Test {
static void show() {
System.out.println("Static Method");
}
public static void main(String[] args) {
show();
}
}
Hence no object is required
5.Instance Methods
Requires an object to call them
class Test {
void display() {
System.out.println("Instance Method");
}
public static void main(String[] args) {
Test t = new Test();
t.display();
}
}
6.Method Overloading
Allows multiple methods with the same name but different parameters.
int add(int a, int b){
return a+b;
}
int add(int a, int b, int c){
return a+b+c;
}
7.Method can call other methods
void greet(){
System.out.println("Hello");
}
void welcome(){
greet();
System.out.println("Welcome");
}
Parameters and Arguments
Information can be passed to methods as a parameter. Parameters act as variables inside the method.
Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma
When a parameter is passed to the method, it is called an argument.
Multiple Parameters
the method call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order.
A Method with If...Else
It is common to use if...else statements inside methods.
Return Values
we used the void keyword in all examples (like static void myMethod(int x)), which indicates that the method should not return a value.
If you want the method to return a value, you can use a primitive data type (such as int, char, etc.) instead of void, and use the return keyword inside the method.
public class Main {
static int myMethod(int x) {
return 5 + x;
}
public static void main(String[] args) {
System.out.println(myMethod(3));
}
}
Method Signature
It consists of the method name and a parameter list.
Number of parameters
Type of the parameters
Order of the parameters
Note: The return type and exceptions are not considered as part of it.
Method Signature of the above function:
max(int x, int y) Number of parameters is 2, Type of parameter is int.
Naming a Method
In Java language method name is typically a single word that should be a verb in lowercase or a multi-word, that begins with a verb in lowercase followed by an adjective, noun. After the first word, the first letter of each word should be capitalized.
Rules to Name a Method:
Method names must start with a verb in lowercase.
Multi-word names should follow camelCase format.
Method names should be unique within a class unless method overloading is allowed in Java.
The this Keyword inside Java Methods
this is a keyword in Java which is used as a reference to the object of the current class, with in an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables and methods.
Note − The keyword this is used only within instance methods or constructors
This
In general, the keyword this is used to −
Differentiate the instance variables from local variables if they have same names, within a constructor or a method.
class Student {
int age;
Student(int age) {
this.age = age;
}
}
Call one type of constructor (parametrized constructor or default) from other in a class. It is known as explicit constructor invocation.
class Student {
int age
Student() {
this(20);
}
Student(int age) {
this.age = age;
}
}
Java Methods Variables Arguments (var-args)
pass a variable number of arguments of the same type to a method. The parameter in the method is declared as follows −
typeName... parameterName
In the method declaration, you specify the type followed by an ellipsis (...). Only one variable-length parameter may be specified in a method, and this parameter must be the last parameter. Any regular parameters must precede it.
Example: Use of Variables Arguments (var-args)
public class VarargsDemo {
public static void main(String args[]) {
// Call method with variable args
printMax(34, 3, 3, 2, 56.5);
printMax(new double[]{1, 2, 3});
}
public static void printMax( double... numbers) {
if (numbers.length == 0) {
System.out.println("No argument passed");
return;
}
double result = numbers[0];
for (int i = 1; i < numbers.length; i++)
if (numbers[i] > result)
result = numbers[i];
System.out.println("The max value is " + result);
}
}
Output
The max value is 56.5
The max value is 3.0
The finalize( ) Method
It is possible to define a method that will be called just before an object's final destruction by the garbage collector. This method is called finalize( ), and it can be used to ensure that an object terminates cleanly.
For example, you might use finalize( ) to make sure that an open file owned by that object is closed.
To add a finalizer to a class, you simply define the finalize( ) method. The Java runtime calls that method whenever it is about to recycle an object of that class.
Inside the finalize( ) method, you will specify those actions that must be performed before an object is destroyed.
The finalize( ) method has this general form −
protected void finalize( ) {
// finalization code here
}
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class.
This means that you cannot know when or even if finalize( ) will be executed. For example, if your program ends before garbage collection occurs, finalize( ) will not execute.
Standard Library Methods
The standard library methods are built-in methods in Java that are readily available for use. These standard libraries come along with the Java Class Library (JCL) in a Java archive (*.jar) file with JVM and JRE.
For example,
print() is a method of java.io.PrintSteam. The print("...") method prints the string inside quotation marks.
sqrt() is a method of Math class. It returns the square root of a number.
Here's a working example:
Example 4: Java Standard Library Method
public class Main {
public static void main(String[] args) {
// using the sqrt() method
System.out.print("Square root of 4 is: " + Math.sqrt(4));
}
}
Output:
Square root of 4 is: 2.0
What are the advantages of using methods?
- The main advantage is code reusability. We can write a method once, and use it multiple times. We do not have to rewrite the entire code each time. Think of it as, "write once, reuse multiple times".
Example 5: Java Method for Code Reusability
public class Main {
// method defined
private static int getSquare(int x){
return x * x;
}
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
// method call
int result = getSquare(i);
System.out.println("Square of " + i + " is: " + result);
}
}
}
Output:
Square of 1 is: 1
Square of 2 is: 4
Square of 3 is: 9
Square of 4 is: 16
Square of 5 is: 25
In the above program, we have created the method named getSquare() to calculate the square of a number. Here, the method is used to calculate the square of numbers less than 6.
Hence, the same method is used again and again.
- Methods make code more readable and easier to debug. Here, the getSquare() method keeps the code to compute the square in a block. Hence, makes it more readable.
Top comments (0)