Java Methods
In this tutorial, we will learn how to implement methods (or functions) in Java.
1. What is a Method in Java?
In Java, a method is a collection of statements designed to perform specific tasks and, optionally, return a result to the caller. A Java method can also execute a task without returning any value. Methods enable code reuse by eliminating the need to rewrite code. Importantly, in Java, every method must belong to a class.
2. Types of Methods in Java
User-defined Methods: Custom methods created by the programmer based on specific requirements.Standard Library Methods: Built-in methods provided by Java, ready for immediate use.
What is the return type of a method that does not return any value?
3. Declaring a Java Method
The basic syntax for a method declaration is:
returnType methodName() {
// method body
}- returnType: Specifies the type of value returned by the method. If it doesn’t return a value, the return type is
void. - methodName: The identifier used to call the method.
- method body: Code inside
{ }that defines the task to be performed.
Tip 💡: void means "I'm doing work, but I'm not giving you anything back." Like a volunteer!
Example 1:
int addNumbers() {
// code
}In this example, addNumbers() is the method name, and its return type is int.
For a more detailed declaration:
modifier static returnType methodName(parameter1, parameter2, ...) {
// method body
}- modifier: Defines access type (e.g., public, private).
- static: If included, the method can be called without creating an object.
- parameter1, parameter2, ...parameterN: Values passed to the method.
Example 2:
The sqrt() method in the Math class is static, so it can be accessed as Math.sqrt() without creating an instance of Math.
4. Calling a Method in Java
To use a method, call it by name followed by parentheses.
Java Method Call Example
class Main {
public int addNumbers(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int num1 = 25, num2 = 15;
Main obj = new Main(); // Create object of Main class
int result = obj.addNumbers(num1, num2);
System.out.println("Sum is: " + result);
}
}Output:
Sum is: 40Here, the addNumbers() method takes two parameters and returns their sum. Since it is not static, it requires an object to be called.
5. Method Return Types
A method may or may not return a value. The return statement is used to return a value.
Example 1: Method returns integer value
public static int square(int num) {
return num * num;
}Example 2: Method does not return any value
// void keyword is used as function does not return any value
public void printSquare(int num) {
System.out.println(num * num);
}6. Method Parameters
Methods can accept parameters, which are values passed to the method.
Examples
- With Parameters:
int addNumbers(int a, int b) - Without Parameters:
int addNumbers()
When calling a method with parameters, you must provide values for each parameter.
Example of Method Parameters
class Main {
public void display1() {
System.out.println("Method without parameter");
}
public void display2(int a) {
System.out.println("Method with a single parameter: " + a);
}
public static void main(String[] args) {
Main obj = new Main();
obj.display1(); // No parameters
obj.display2(24); // Single parameter
}
}Output:
Method without parameter
Method with a single parameter: 24Note: Java requires that argument types match the parameter types.
What must match when calling a method with parameters?
7. Recursion
Recursion occurs when a method calls itself. This is useful for solving problems that can be broken down into smaller, similar problems (like factorial or Fibonacci).
public class Main {
public static void main(String[] args) {
int result = sum(10);
System.out.println(result);
}
public static int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
}Output:
558. Standard Library Methods
Java includes built-in methods available in the Java Class Library (JCL), which comes with the JVM and JRE.
Example
public class Main {
public static void main(String[] args) {
System.out.println("Square root of 4 is: " + Math.sqrt(4));
}
}Output:
Square root of 4 is: 2.09. Advantages of Using Methods
1. Code Reusability
Define once, use multiple times.
private static int getSquare(int x) {
return x * x;
}
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Square of " + i + " is: " + getSquare(i));
}
}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: 252. Improved Readability
Grouping code into methods makes it easier to read and debug.
Challenge
Complete this chapter to unlock the next one.
Challenge
Task:
Create a method 'multiply' that takes two integers, returns their product, and call it with 5 and 3.Key Takeaways
- Reusability: Write code once, use it everywhere.
- Parameters: Inputs to the method.
- Return Type: The data type the method gives back (
voidif nothing).
Common Pitfalls
[!WARNING] Missing Return: If your method isn't
void, you MUST return a value on all paths.Parameter Mismatch: You can't pass a
Stringto a method expecting anint. Java is strict!
What's Next?
How do we set up an object right when we create it? Learn Constructors →
