Table of Contents
What is a Method in Java?
A method in Java is a block of code that performs a specific task. It is executed only when it is called from another part of the program. Methods allow developers to divide a large program into smaller, manageable sections, improving code readability and reducing duplication.For example, instead of writing the same logic to calculate the area of a rectangle multiple times, you can create a method that performs the calculation and call it whenever required.
Syntax:
Explanation:accessModifier returnType methodName(parameters) {
// Method body
}
- accessModifier: Determines where the method can be accessed from, such as public, private, or protected.
- returnType: Specifies the type of value returned by the method. Use void if the method does not return anything.
- methodName: The name used to call the method. It should be meaningful and follow Java naming conventions.
- parameters: Values passed to the method when it is called. Parameters are optional.
- method body: Contains the statements that perform the desired task.
// Java program to implement method
public class MethodExample {
public static void greet() {
System.out.println("Welcome to TutorialforGeeks!");
}
public static void main(String[] args) {
greet();
}
}
Output:
Explanation:Welcome to TutorialforGeeks!
- The method greet() is created using the void return type because it does not return any value.
- The public keyword makes the method accessible throughout the program.
- The static keyword allows the method to be called directly from the main() method without creating an object.
- Inside the main() method, the statement greet(); calls the method.
- When the method is executed, it prints "Welcome to Tutorials!" on the console.
Predefined Methods
Predefined methods, also called built-in methods, are methods that are already available in Java's standard libraries. These methods are created by Java developers and can be used directly without writing their implementation.
Some commonly used predefined methods include:
- Math.sqrt()
- Math.max()
- Math.min()
- String.length()
- System.currentTimeMillis()
These methods save time because you do not need to implement common functionalities from scratch.
Example:
// Java program to implement predefined methods
public class PredefinedMethodExample {
public static void main(String[] args) {
double number = 81;
double squareRoot = Math.sqrt(number);
System.out.println("Square Root = " + squareRoot);
}
}
Output:
Explanation:Square Root = 9.0
- A variable named number stores the value 81.
- The predefined method Math.sqrt() calculates the square root of the given number.
- The returned value is stored in the variable squareRoot.
- Finally, the result is displayed using System.out.println().
User-defined Methods
A user-defined method is a method created by the programmer to perform a specific task. Unlike predefined methods, these methods are written according to the requirements of the application.User-defined methods improve code reusability because the same logic can be called multiple times from different parts of the program.
Syntax:
Example:returnType methodName(parameters) {
// statements
}
// Java program to implement user-defined methods
public class UserDefinedMethodExample {
public static void displayMessage() {
System.out.println("Learning Java Methods is Easy!");
}
public static void main(String[] args) {
displayMessage();
displayMessage();
displayMessage();
}
}
Output:
Explanation:Learning Java Methods is Easy!
Learning Java Methods is Easy!
Learning Java Methods is Easy!
- The method displayMessage() is created by the programmer.
- The method contains a single statement that prints a message.
- The main() method calls displayMessage() three times.
- Instead of writing the System.out.println() statement three separate times, the method is reused.
Static Methods
A static method is a method that belongs to the class rather than an object of the class. Since it is associated with the class, you can call it directly using the class name without creating an object.Static methods are commonly used for utility operations that do not depend on object-specific data. For example, methods in the Math class, such as Math.max() and Math.sqrt(), are static methods.
Syntax:
Example:class ClassName {
static returnType methodName(parameters) {
// Method body
}
}
// Java program to implement static methods
public class StaticMethodExample {
static void displayCourse() {
System.out.println("Course: Java Programming");
}
public static void main(String[] args) {
StaticMethodExample.displayCourse();
}
}
Output:
Explanation:Course: Java Programming
- The displayCourse() method is declared using the static keyword.
- Since the method is static, it belongs to the class instead of an object.
- Inside the main() method, the method is called using the class name:
- StaticMethodExample.displayCourse();
- Java executes the method and prints the course name.
Instance Methods
An instance method is a method that belongs to an object of a class. Unlike static methods, an instance method can access both instance variables and other instance methods.Before calling an instance method, you must first create an object of the class.
Instance methods are widely used because most real-world applications work with objects and their data.
Syntax:
Example:class ClassName {
returnType methodName(parameters) {
// Method body
}
}
// Java program to implement instance method
public class InstanceMethodExample {
void showMessage() {
System.out.println("Welcome to Java Programming!");
}
public static void main(String[] args) {
InstanceMethodExample obj = new InstanceMethodExample();
obj.showMessage();
}
}
Output:
Explanation:Welcome to Java Programming!
- The method showMessage() is an instance method because it is not declared as static.
- An object named obj is created using the new keyword.
- The method is called using the object: obj.showMessage();
- When the method executes, it displays the welcome message.
Advantages of Using Methods
Methods make Java programs easier to write, understand, and maintain. Here are some of their major advantages.1. Promotes Code Reusability: Once a method is created, it can be called multiple times without rewriting the same code. This reduces duplication and makes programs shorter and more organized. For example, a calculateSalary() method can be reused whenever salary needs to be calculated.
2. Improves Code Readability: Breaking a large program into smaller methods makes it easier to understand. Instead of reading hundreds of lines of code together, developers can focus on one method at a time. Well-named methods also make the purpose of the code clear.
3. Simplifies Program Maintenance: When a change is required, you only need to update the method instead of modifying the same logic in multiple places. This reduces the chances of introducing errors. For example, if a tax calculation changes, updating one method automatically updates every place where it is used.
4. Makes Debugging Easier: Finding and fixing bugs becomes much simpler because each method performs a specific task. You can test methods individually to identify where a problem exists. This saves time during development and troubleshooting.
5. Encourages Modular Programming: Methods divide a large application into smaller independent modules. Each module performs a specific responsibility, making the program easier to develop and manage. Modular programs are also easier to test, improve, and extend in the future.
Common Mistakes While Using Methods in Java
Even though methods are simple to use, beginners often make a few common mistakes.1. Forgetting to Call the Method: Creating a method does not automatically execute it. The method must be called from another method, usually main().
Incorrect:
public class Demo {
static void greet() {
System.out.println("Hello");
}
public static void main(String[] args) {
}
}
Since greet() is never called, nothing is printed.2. Using the Wrong Return Type: The declared return type should match the value returned by the method.
Incorrect:
public static int getMessage() {
return "Hello";
}
The method is declared to return an int but returns a String, resulting in a compilation error.3. Calling an Instance Method Without an Object: Instance methods require an object. Trying to call them directly from a static context causes an error.
Incorrect:
public static void main(String[] args) {
showMessage();
}
The correct approach is to create an object first.4. Passing the Wrong Number of Arguments: The number and type of arguments passed must match the method definition.
Incorrect:
add(10);If the method expects two parameters, passing only one argument results in a compilation error.
5. Giving Methods Meaningless Names: Method names like abc(), xyz(), or method1() make programs difficult to understand. Instead, choose names that clearly describe the method's purpose.
Conclusion
Methods are a fundamental part of Java programming because they help organize code into smaller, reusable units. By understanding different types of methods, such as predefined, user-defined, static, and instance methods, you can write programs that are cleaner, easier to maintain, and more efficient. As you continue learning Java, mastering methods will make it easier to understand advanced concepts like method overloading, recursion, and object-oriented programming.Frequently Asked Questions
1. What is a method in Java?2. What are the different types of methods in Java?A method in Java is a block of code that performs a specific task. It executes only when it is called and helps organize code into reusable and manageable sections.
3. What is the difference between a static method and an instance method?The commonly used types of methods in Java are:
- Predefined methods
- User-defined methods
- Static methods
- Instance methods
Each type serves a different purpose depending on the requirements of the program.
4. Why are methods important in Java?A static method belongs to the class and can be called without creating an object. An instance method belongs to an object, so you must create an object of the class before calling it.
5. Can a Java program have multiple methods?Methods improve code reusability, readability, and maintainability. They also reduce code duplication, simplify debugging, and support modular programming by breaking large programs into smaller, manageable units.
Yes. A Java program can contain multiple methods, and one method can call another method. This helps divide complex tasks into smaller, logical units, making the program easier to understand and maintain.
2 Comments