Java Methods
Java methods are an important concept in Java programming that help to organize code into reusable blocks. A method contains a group of statements that performs a specific task when it is called.
Methods improve code readability, reduce code repetition, and make Java programs easier to maintain. In this tutorial, you will learn Java methods, syntax, types of methods, parameters, and return values with examples.
What is a Method in Java?
A method in Java is a block of code that performs a particular operation. A method executes only when it is called. Java methods can accept values as parameters and can return results after execution.
Java Method Syntax
access_modifier return_type methodName(parameters)
{
// method body
}
Example of Java Method
Let us take a simple example to understand how to create and call a method in Java.
public class Main{
static void display() {
System.out.println("Hello Java Methods");
}
public static void main(String[] args) {
display();
}
}
Types of Methods in Java
Java methods are mainly divided into two types:
Predefined Methods
These methods are already created by Java and are available through Java libraries.
User-defined Methods
These methods are created by programmers according to their requirements.
User-defined Method Example
public class Main{
static void add() {
int a = 10;
int b = 20;
System.out.println(a + b);
}
public static void main(String[] args) {
add();
}
}
Java Method Parameters
Parameters are values passed to a method when it is called. They allow methods to work with different input values.
static void message(String name) {
System.out.println("Hello " + name);
}
Advantages of Java Methods
- Methods improve code reusability.
- They reduce code duplication.
- Methods make programs easier to understand.
- They improve code organization.
- They make debugging easier.
Conclusion
Java methods are used to divide programs into smaller reusable blocks. They help developers create clean, organized, and maintainable Java applications. Understanding methods is an important step toward learning advanced Java concepts.