Methods in Java are **blocks of code** that perform a specific task. They help in code reusability and make the program more modular.
Methods in Java
What are Methods in Java?
Methods in Java are **blocks of code** that perform a specific task. They help in code reusability and make the program more modular.
Types of Methods
There are two types of methods in Java:
- Predefined Methods (Built-in methods like
Math.sqrt()
,System.out.println()
) - User-defined Methods (Created by the programmer for specific tasks)
Defining a Method
A method is defined using the following syntax:
returnType methodName(parameters) {
// Method body
return value;
}
Example of a Simple Method
public class MethodExample {
public static void greet() {
System.out.println("Hello, Welcome to Java Methods!");
}
public static void main(String[] args) {
greet(); // Calling the method
}
}
Method with Parameters
Methods can accept parameters to process values.
public class ParameterExample {
public static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
public static void main(String[] args) {
greet("Mahendra"); // Output: Hello, Mahendra!
}
}
Method with Return Value
A method can return a value using the return
statement.
public class ReturnExample {
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int sum = add(5, 10);
System.out.println("Sum: " + sum);
}
}
Method Overloading
Java allows multiple methods with the same name but different parameters. This is called **method overloading**.
public class OverloadingExample {
public static int add(int a, int b) {
return a + b;
}
public static double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(add(5, 10)); // Calls int version
System.out.println(add(5.5, 10.5)); // Calls double version
}
}
Static vs Non-Static Methods
Static Method
Belongs to the class and can be called without creating an object.
public class StaticMethodExample {
public static void display() {
System.out.println("This is a static method.");
}
public static void main(String[] args) {
display(); // Direct call without an object
}
}
Non-Static Method
Requires an object to be called.
public class NonStaticMethodExample {
public void show() {
System.out.println("This is a non-static method.");
}
public static void main(String[] args) {
NonStaticMethodExample obj = new NonStaticMethodExample();
obj.show(); // Called using an object
}
}
Conclusion
Methods in Java are essential for writing clean, reusable, and maintainable code. They allow us to divide a program into smaller parts for better readability.
📌 Next Topic: Constructors in Java