methods in java

Java Methods: Explained With Practical Examples

April 7th, 2026
4175
19:00 Minutes

Do you know what methods in Java are? Methods are useful functions that belong to a class, and understanding them is crucial for Java developers to develop robust applications. This guide includes a detailed explanation of everything one should know about these Java methods. It begins with a basic introduction and explains all aspects, including its features, types, key components, and syntax, as well as the process of creating and calling them.

Learning about Java methods can be a game-changer for anyone aiming to become a proficient Java developer. The programming language doesn't demand writing long, complex code for every task, saving valuable time that developers can spend on more critical challenges. Learning this concept not only boosts productivity but also opens doors to exciting career opportunities. In fact, skilled Java developers earn an impressive average salary of $91,000 per year, making it a smart investment in your future.

Introduction to Methods in Java

Methods in Java are blocks of code that perform specific tasks and can be called to execute when needed. A method, also known as a function, is designed to perform specific tasks, improve code reusability, and reduce redundancy. Developers just have to create one and then they can call it in different codes. Its reusability improves the performance and efficiency of the programmer.

Each of them belongs to a special class. It is also referred to as a function that exposes a particular behavior of objects. There are many features of methods in Java. Let's explore some of them.

Explore all Programming Courses by igmGuru to become a successful programmer. 

Features of Methods in Java

The use of methods in Java is one of the most contributing factors to its success. This gives many features to programmers. In fact, these are the foundations of Java programming. Let us dive into these features -

  • Code Reusability

Code reusability is one of the most important perks of using methods. Individuals can use them again and again in the same or different codes after creating one. This reduces the chances of errors in concise code. It is also easier to manage these types of programs. Here is an instance of code reusability that can calculate the square of any given number.

public class ReusableMethods {

public static int square(int numb) {

return numb * numb;

}

public static void main(String[] args) {

int res1 = square(5);

int res2 = square(10);

System.out.println("Square of 6: " + res1);

System.out.println("Square of 9: " + res2);

}

}

  • Code Organization

Code organization is another feature of these methods. It divides a long code into smaller sections that are easy to maintain and comprehend. It is also better for teamwork and readability. Here is an instance of this feature that separates the welcome and farewell messages.

public class CodeOrganization {

public static void displayWelcomeMessage() {

System.out.println("Welcome to Java's class");

}

public static void displayFarewellMessage() {

System.out.println("Thanks for training Java with us");

}

public static void main(String[] args) {

displayWelcomeMessage();

displayFarewellMessage();

}

}

  • Easy to Read & Maintain

It is easy to read and maintain the methods in Java programming. Individuals can encapsulate special functionalities within a method by assigning them meaningful names. This approach makes it easy to understand the function of the code. It is also possible to correct bugs without affecting any parts of a program with these. Here is an instance of these types of methods -

public class Readability {

public static double calculateRectangleArea(double len, double wid) {

return len * wid;

}

public static void main(String[] args) {

double len = 9.0;

double wid = 2.0;

double area = calculateRectangleArea(len, wid);

System.out.println("Rectangle area is: " + area);

}

}

Explore top Java Interview Questions to ace your interview.

Key Components of Methods in Java

There are many key components of methods in Java as shown below. Each of them is focused on declaring a particular element or performing a task in the code.

1. Access ModifierIt defines the access level of a method like private, public, protected or default.

2. Return Type - It decides the type of return value or gives void if no value is returned.

3. Method Name - It is the Java naming conventions that start with a lowercase and use camelcase for many words.

4. Method Parameters - It is a list of input values. These are only used when parameters are needed.

5. Exception List - These are the exceptions that the method might throw.

6. Method Header & Body - It contains the logic of the code that has to be executed.

Related Article - Golang vs Java: What Should You Choose?

Types of Methods in Java

Types of methods in Java are typically classified into two types including predefined and user-defined. Both of these are suitable to use in different instances.

  • Predefined Methods

The predefined methods are the ones that are already available in the Java library. These can be called when needed without needing to define them. There are many predefined methods, including sqrt(), max(), length() and print(). Each of them is available within their respective classes. Here is an instance of using these methods.

public class Example {

public static void main(String args[]) {

System.out.println("The Square root is: " + Math.sqrt(25)); // Added the missing quote

}

}

  • User-defined Methods

User-defined methods are defined by the user themselves. Users can modify and tweak them according to the situation and requirements. Below is an example of using this type of method.

public class Example {

// Creating a method

public int subNumbers(int x, int y) {

int subtract = x - y;

// Returning the value

return subtract;

}

public static void main(String[] args) {

int num1 = 57;

int num2 = 22;

// Creating an object of Example class

Example obj = new Example();

// Calling the method

int outcome = obj.subNumbers(num1, num2);

System.out.println("Outcome is: " + outcome);

}

}

Also Read: Java Projects

How to Create Methods in Java?

Learning how to create methods in Java requires understanding its syntax, defining processes, and calling methods. These are the steps of building a program. One should start by creating the method signature that includes the method name, return type, and parameters. Then comes the main task, which is writing the main body. The body contains the logic of the code. Let's understand it with some instances.

Creating a Method Signature

There are different syntaxes to create a method signature. We are using the following syntax -

public <return type> ()

We are using an abstract method in Java with this syntax that takes two parameters and returns a single integer -

abstract class MyClass {

public abstract int add(int a, int b); // Abstract method

public static void main(String args[]) {

// You can't directly instantiate an abstract class

// MyClass instance = new MyClass(); // This will cause a compile-time error

// You need to create a concrete subclass that implements the abstract method

MyClass instance = new MySubclass(); // Example: Using a subclass (see below)

int result = instance.add(12, 3);

System.out.println(result);

}

}

// Concrete subclass that implements the abstract method

class MySubclass extends MyClass {

@Override

public int add(int a, int b) {

int result = 0;

result = a + b;

return result;

}

}

Defining Methods in a Class

The above instance is the perfect one to understand how to define methods in a class. The first row on this program is in the method signature. The public keyword shows that we have called this method from outside of the class.

Then the return type is an int, which means it will return an integer value. Our method name is add, and the parameters are integer a and integer b. The logic of the body adds the two parameters and returns the result.

Calling Methods in Java

It is possible to call a method from anywhere in the program with the following syntax -

<object reference>.()

For instance, the code given below calls the add method with the parameters 12 and 3 -

int result = myClass.add(12, 3);

This will give the result as 15. It is also possible to use a method that will not return any value.

public void printMessage() {

System.out.println("Hello, world!");

}

This method will not return any value. This is why the void keyword is used in its method signature. It needs to use the following code to call this method. This code will return the Hello World as a result.

class MyClass {

public void printMessage() {

System.out.println("Hello, world!");

}

}

public class Main {

public static void main(String[] args) {

MyClass object = new MyClass();

object.printMessage(); // prints "Hello, world!" to the screen

}

}

Explore all top Back End Languages for complete learning.

Method Overloading & Method Overriding in Java

Method overloading is a polymorphism at the time of compilation. Many methods share the same name while using different signatures in method overloading. It always returns different result types. It is important to change the parameter to achieve method overloading. Here is an instance of this case -

// Java Program to Implement

// Method Overloading

import java.io.*;

class MethodOverloadingEx {

static int add(int a, int b) { return a + b; }

static int add(int a, int b, int c)

{

return a + b + c;

}

// Main Function

public static void main(String args[])

{

System.out.println("add() with 2 parameters");

// Calling function with 2 parameters

System.out.println(add(4, 6));

System.out.println("add() with 3 parameters");

// Calling function with 3 Parameters

System.out.println(add(4, 6, 7));

}

}

Method Overriding is a polymorphism at the time of execution. The derived class will have the same name, parameters and return type as its parent class in this case. The derived class gives a special implementation for the method which is already available in the parent class. Here is an instance of this case -

import java.io.*;

// Base Class

class Animal {

void eat() {

System.out.println("eat() method of base class");

System.out.println("Animal is eating.");

}

}

// Derived Class

class Dog extends Animal {

@Override

void eat() {

System.out.println("eat() method of derived class");

System.out.println("Dog is eating.");

}

// Method to call the base class method

void eatAsAnimal() {

super.eat();

}

}

// Driver Class

class MethodOverridingEx {

// Main Function

public static void main(String args[]) {

Dog d1 = new Dog();

Animal a1 = new Animal();

// Calls the eat() method of Dog class

d1.eat();

// Calls the eat() method of Animal class

a1.eat();

// Polymorphism: Animal reference pointing to Dog object

Animal animal = new Dog();

// Calls the eat() method of Dog class

animal.eat();

// To call the base class method, you need to use a Dog reference

((Dog) animal).eatAsAnimal();

}

}

Also Explore: Python Tutorial

Wrapping Up

Programming in Java can be very complicated when working on difficult tasks. The use of methods in Java promotes modularity, reusability and abstraction that ultimately simplify complicated tasks. Mastering methods is important for any Java developer who wants to seek proficiency and code excellence. It is the best solution to create codes with minimum errors and maximum efficiency.

FAQs For Methods in Java

Q1. What is the main method in Java?

The entry point for executing a Java program is considered the main method. It is the first method that is called when a Java class is executed. The syntax of this method is public static void main(String[] args).

Q2. Can Java have two main methods?

It is possible to use more than one main method in Java with different parameter lists. But it will only call the method that has the signature syntax when starting your program.

Q3. What is void in Java?

The void is a keyword in Java programming language. It specifies that the method can not return any value. It is also referred to as a return type that shows the method performs a task but does not give any result.

About the Author
Author Nehal Sharma
About the Author

Nehal Sharma is a skilled Data Analyst with expertise in Java, mobile development, and data analytics. She transforms complex data into actionable insights and has experience in business intelligence, data science, and Salesforce. She also simplifies technical concepts into clear, engaging content for learners and professionals.

Drop Us a Query
Fields marked * are mandatory
×

Your Shopping Cart


Your shopping cart is empty.