Functions and Methods in Java: A Beginner's Tutorial
Introduction to Functions and Methods
Functions and methods are reusable blocks of code that perform specific tasks in Java. They allow you to break
down your code into smaller, manageable parts and promote code reusability. Java supports both standalone functions
and methods within classes.
Creating a Function
In Java, a standalone function is created using the public static
keyword. Here's an example of a
simple function that adds two numbers:
public static int add(int num1, int num2) {
return num1 + num2;
}
Calling a Function
Functions are called by their name, followed by parentheses. You can pass arguments to the function within the
parentheses. Here's how you call the add
function:
int result = add(5, 3);
System.out.println("Result: " + result);
Creating a Method
Methods in Java are similar to functions but are defined within classes. Here's an example of a class with a
method to calculate the area of a rectangle:
public class Rectangle {
public static double calculateArea(double length, double width) {
return length * width;
}
}
Calling a Method
To call a method, you create an instance of the class (an object) and call the method on that object. Here's how
you calculate the area of a rectangle using the Rectangle
class:
Rectangle myRectangle = new Rectangle();
double area = myRectangle.calculateArea(5.0, 3.0);
System.out.println("Area: " + area);
Conclusion
Functions and methods are essential for organizing and structuring your code in Java. They promote code
reusability and make your programs more modular and readable. As a beginner, learning to create and use functions
and methods is a key step in becoming proficient in Java programming.