Methods in Java

In this tutorial, we will learn about methods in Java programming. A method in Java is a block of code that performs a specific task. In other words, it is a group of statements that perform an operation. You can reuse methods throughout a program to avoid repetition.

When you call the method, statements inside the method will execute. If you don’t call it, then its code will not execute. In Java, methods help in organizing code, improving readability, and reducing redundancy. They are fundamental aspect of object-oriented programming (OOP), allowing you to define define the behavior of classes and objects.

Syntax of Methods in Java

The general syntax of methods in Java is as follows:

access_modifier return_type method_name(parameter_list) {
    // method body (code to be executed)
       return value; // (if return type is not void)
}

In the above syntax, there are the following components of a method. They are as:

  • Access Modifier: It defines the visibility of the method. In other words, this defines who can access the method. There are four types of access modifiers in Java:
    • public: Accessible from anywhere.
    • private: Accessible only within the same class.
    • protected: Accessible in the same package and by subclasses.
    • (default): If no modifier is specified, the method is accessible within the same package.
  • Return Type: This component of a method specifies the data type of the value returned by the method. For example, the data type int returns an integer, string returns a string, and void returns nothing. If it doesn’t return anything, use void.
  • Method Name: This represents a name of method (i.e. identifier) which is used to call the method. You must follow Java identifier rules to define a method name:
    • The name of method can contain letters, digits, _, and $.
    • It must not start with a digit
    • You cannot use Java reserved keywords as a method name.
    • You must follow camelCase naming convention. For example, calculateTotal, getResult, isEven.
  • Parameter List: This represents inputs passed to the method. However, this is an optional. A method can take zero or more parameters. Each parameter inside the method must have a data type and a name, followed by commas. If there are no parameters, just use empty parentheses.
  • Method Body: This is the block of code that runs when the method is called. It’s where the actual logic goes. The method body is enclosed in the curly braces { }.
  • Return Statement: This statement returns a value if the method has a non-void return type. If a method has a return type, it must return a value of that type.

Example of a Simple Method:

public int addNumbers(int a, int b) {
    int sum = a + b;
    return sum;
}

In this example, components of this method is as:

  • Access Modifier: public
  • Return Type: int
  • Method Name: addNumbers
  • Parameters: int a, int b
  • Return Statement: return sum

Types of Methods in Java

There are two types of methods in Java programming based on their behavior and usage. They are:

  • Predefined methods (Built-in Methods)
  • User-defined methods

Predefined Methods

Methods which are already defined in Java’s standard libraries are called predefined methods in Java. For example, java.lang, java.util, java.io, etc. are predefined methods which are also called built-in methods in Java. You can use them directly without writing their code from scratch. These methods are part of Java classes that are shipped with the Java Development Kit (JDK).

Why Use Predefined Methods in Java Program?

There are the following benefits of using predefined methods. They are:

  • Saves time: You do not need to write the code for common functionalities yourself.
  • Less error-prone: These methods are already tested by Java developers.
  • Boosts productivity: You can focus on business logic instead of low-level code.

Common Examples of Predefined Methods

1. System.out.println(): This statement prints the output on the console. For example:

public class Example1 {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
    }
}

In this example, println() is a predefined method in the PrintStream class, which is defined in java.io package. It prints the text and moves to a new line.

2. Math Class Methods: The Math class performs mathematical operations. Java provides many useful static methods in the Math class present in java.lang package. For example:

public class MathExample {
public static void main(String[] args) {
    System.out.println(Math.sqrt(16)); // Square root
    System.out.println(Math.pow(2, 3)); // Power
    System.out.println(Math.max(10, 20)); // Max of two
    System.out.println(Math.abs(-7));  // Absolute value
  }
}
Output:
      4.0
      8.0
      20
      7

3. String Class Methods: The String class provides tons of helpful methods. For example:

public class StringExample {
public static void main(String[] args) {
    String name = "Java Programming";
    System.out.println(name.length());        
    System.out.println(name.toUpperCase());
    System.out.println(name.substring(5));
    System.out.println(name.contains("Java"));
  }
}
Output:
       16
       JAVA PROGRAMMING
       Programming
       true

4. Arrays Class Methods: The java.util.Arrays class offers various utilities for array handling. For example:

import java.util.Arrays;
public class ArraysExample {
public static void main(String[] args) {
    int[] numbers = {4, 2, 7, 1};
    Arrays.sort(numbers); // Sort array
    System.out.println(Arrays.toString(numbers));
  }
}
Output:
       [1, 2, 4, 7]

5. Scanner Class Methods: Scanner class provides various method to read input from the user or keyboards. For example:

import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
 // Creating an object of Scanner class. 
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter your name: ");
    String name = sc.nextLine();          // Read a line of input
    System.out.println("Hello, " + name);
  }
}
Output:
      Enter your name: Deepak
      Hello, Deepak

Example of Predefine Methods:

public class PredefinedMethodExample {
public static void main(String[] args) {
  // Here, Math.max() is a predefined method.
     int maxNum = Math.max(10, 20);
     System.out.println("Maximum number: " + maxNum);

  // Here, String.length() is a predefined method
     String str = "Hello, Java!";
     int length = str.length();
     System.out.println("String length: " + length);
  }
}
Output:
      Maximum number: 20
      String length: 12

User-defined Methods in Java

Methods which are created or defined by the programmer to perform specific tasks are called user-defined methods in Java. Instead of writing the same block of code multiple times, you write it once in a method and just call that method whenever needed. They improve:

  • Code Reusability: Define once, use many times.
  • Modularity: Divide a big program into small blocks of code.
  • Readability: Easy to read and understand blocks of code.
  • Maintainability: Bugs can be located easily in a specific method.

User-defined methods are the heart of Java programming. By organizing logic into small reusable pieces, you can write cleaner, more efficient, and more maintainable code. Let’s take some examples on it.

Example 1: Method without Parameters and without Return Type

public class UserDefinedEx {
 // Declare user-define method.
    public static void greet() {
        System.out.println("Hello! Welcome to Java.");
    }
    public static void main(String[] args) {
        greet(); // Calling the method
    }
}
Output:
      Hello! Welcome to Java.

Example 2: Method with Parameters and without Return Type

public class UserDefinedEx2 {
 // Declare user-defined method with parameter list.
    public static void printSum(int a, int b) {
        int sum = a + b;
        System.out.println("Sum is: " + sum);
    }

    public static void main(String[] args) {
        printSum(10, 20); // Calling and passing arguments.
    }
}
Output:
      Sum is: 30

Example 3: Method with Parameters and with Return Type

public class UserDefinedEx3 {
    public static int multiply(int a, int b) {
        return a * b;
    }
    public static void main(String[] args) {
        int result = multiply(5, 4); // calling method.
        System.out.println("Multiplication result: " + result);
    }
}
Output:
      Multiplication result: 20

Example 4: Method without Parameters and with Return Type

public class UserDefinedEx4 {
    public static String getGreeting() {
        return "Good Morning!";
    }
    public static void main(String[] args) {
        String msg = getGreeting();
        System.out.println(msg);
    }
}
Output:
      Good Morning!

Example 5: Passing Objects to Methods

class Car {
    String model; // Instance variable.
// Declare a constructor with one parameter.
    Car(String model) {
        this.model = model;
    }
}
public class CarDemo {
    public static void printModel(Car car) {
        System.out.println("Car model: " + car.model);
    }
    public static void main(String[] args) {
    // Creating an object of class Car and pass argument to its constructor.
       Car car = new Car("Toyota");
       printModel(car);
    }
}
Output:
     Car model: Toyota

Example 6: Returning Objects from Methods

class Person {
    String name;
    Person(String name) {
        this.name = name;
    }
}
public class PersonDemo {
    public static Person getPerson() {
        return new Person("Alice");
    }
    public static void main(String[] args) {
        Person p = getPerson();
        System.out.println("Person name: " + p.name);
    }
}
Output:
     Person name: Alice

Best Practices for Writing Methods in Java

There are the following key points that you should remember when you define methods in Java. They are:

  • You should use meaningful names when you define a method in the program. This is because method names describe their purpose. For example, calculateTotal() is a good method name to calculate total instead of calc().
  • You follow a single responsibility principle. You define a method to perform only one task.
  • You should define parameters in limit. Always avoid too many parameters in the method.
  • Use proper access modifiers to restrict the access of method where necessary.
  • Use JavaDoc comments to explain method functionality.
  • Try to avoid long methods. You should break complex logic into smaller methods.

Method Inside Another Method

Java does not allow nested method definitions unlike some other programming languages.

// This is invalid
public void outerMethod() {
    void innerMethod() { } // ❌ not allowed
}

Conclusion:

Methods are fundamental building blocks in Java that allow you to write clean, modular, and reusable code. They encapsulate logic into manageable units, making programs easier to develop, test, and maintain. Java supports both predefined methods (from standard libraries) and user-defined methods, which provide programmers flexibility and power to organize their code effectively.

Whether you’re performing simple calculations or building large applications, methods help reduce redundancy, improve readability, and promote code reuse. I hope that you will have understood the basic syntax and concepts of methods in Java and practiced all example programs.

Please Share Your Love.

Leave a Reply

Your email address will not be published. Required fields are marked *