Methods in Java
What is a method in Java?
A method in Java is a group of statements that performs a particular task.
For example, if we want to print a welcome message many times in a program, instead of writing the same print statement again and again, we can create a method.
public void welcomeMessage() {
System.out.println("Welcome to Core Java Course");
}
Here is a method. When this method is called, it prints the message.
Why Do We Use Methods in Java?
Methods are used to divide a program into smaller parts. This makes the program easier to read, manage, test, and debug.
Methods are useful because:
- They improve code reusability.
- They reduce code repetition.
- They make programs more organized.
- They make large programs easier to understand.
- They help in debugging and testing.
- They are important for object-oriented programming.
Syntax of a Method in Java
The basic syntax of a method is:
returnType methodName(parameters) {
// statements
}
Example:
public void displayMessage() {
System.out.println("Hello Java");
}
In this example:
publicis the access modifier.voidis the return type.displayMessageis the method name.{ }contains the method body.
Simple Example of Method in Java
public class MethodExample {
public void showMessage() {
System.out.println("Welcome to Java Programming");
}
public static void main(String[] args) {
MethodExample obj = new MethodExample();
obj.showMessage();
}
}
Output
Welcome to Java Programming
This programshowMessage() is a method. We created an object of the class and called the method using that object.
Method Declaration in Java
Method declaration means defining a method inside a class.
Example:
public void greet() {
System.out.println("Good Morning");
}
This method does not take any input and does not return any value.
Method Calling in Java
Method calling means executing a method.
Example:
obj.greet();
A method runs only when it is called. If we create a method but do not call it, the method will not execute.
Types of Methods in Java
Methods in Java can be divided into different types based on parameters and return values.
1. Method Without Parameters and Without Return Value
This type of method does not accept any input and does not return any value.
public class Example {
public void display() {
System.out.println("Learning Java Methods");
}
public static void main(String[] args) {
Example obj = new Example();
obj.display();
}
}
Output
Learning Java Methods
This type of method is useful when we only want to perform a simple task.
2. Method With Parameters and Without Return Value
This type of method accepts input values but does not return any result.
public class Example {
public void add(int a, int b) {
int sum = a + b;
System.out.println("Sum: " + sum);
}
public static void main(String[] args) {
Example obj = new Example();
obj.add(10, 20);
}
}
Output
Sum: 30
Here, a and b are parameters. The values 10 are passed when the method is called.
3. Method Without Parameters and With Return Value
This type of method does not accept input but returns a value.
public class Example {
public int getNumber() {
return 100;
}
public static void main(String[] args) {
Example obj = new Example();
int result = obj.getNumber();
System.out.println("Number: " + result);
}
}
Output
Number: 100
Here, the method returns an integer value.
4. Method With Parameters and With Return Value
This type of method accepts input values and returns a result.
public class Example {
public int multiply(int a, int b) {
return a * b;
}
public static void main(String[] args) {
Example obj = new Example();
int result = obj.multiply(5, 4);
System.out.println("Multiplication: " + result);
}
}
Output
Multiplication: 20
This is one of the most commonly used method types in Java programming.
Return Type in Java Methods
The return type defines what type of value a method will return.
Common return types are:
voidintdoublefloatcharbooleanString
Example of void Return Type
public void show() {
System.out.println("This method returns nothing");
}
The void keyword means the method does not return any value.
Example of int Return Type
public int square(int number) {
return number * number;
}
This method returns an integer value.
Example of String Return Type
public String getCourseName() {
return "Core Java";
}
This method returns a string value.
Parameters and Arguments in Java
Parameters are variables written inside the method declaration. Arguments are actual values passed during method calling.
Example:
public void studentDetails(String name, int age) {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
Method calling:
studentDetails("Rahul", 20);
Here:
String nameandint ageare parameters."Rahul"and20are arguments.
Static Method in Java
A static method belongs to the class, not to an object. We can call a static method directly using the class name or from the main() method.
Example:
public class StaticMethodExample {
public static void showMessage() {
System.out.println("This is a static method");
}
public static void main(String[] args) {
showMessage();
}
}
Output
This is a static method
Static methods are useful when we do not need object-specific data.
Non-Static Method in Java
A non-static method belongs to an object. To call a non-static method, we need to create an object of the class.
Example:
public class NonStaticMethodExample {
public void display() {
System.out.println("This is a non-static method");
}
public static void main(String[] args) {
NonStaticMethodExample obj = new NonStaticMethodExample();
obj.display();
}
}
Output
This is a non-static method
Difference Between Static and Non-Static Methods
| Static Method | Non-Static Method |
|---|---|
| Belongs to the class | Belongs to the object |
| Can be called without object | Requires object for calling |
| Uses static data directly | Can use instance data directly |
| Commonly used for utility tasks | Commonly used for object behavior |
Method Overloading in Java
Method overloading means creating multiple methods with the same name but different parameters in the same class.
Example:
public class MethodOverloadingExample {
public void add(int a, int b) {
System.out.println(a + b);
}
public void add(int a, int b, int c) {
System.out.println(a + b + c);
}
public void add(double a, double b) {
System.out.println(a + b);
}
public static void main(String[] args) {
MethodOverloadingExample obj = new MethodOverloadingExample();
obj.add(10, 20);
obj.add(10, 20, 30);
obj.add(5.5, 4.5);
}
}
Output
30
60
10.0
Method overloading is an example of compile-time polymorphism.
How Methods Work in Java
When a method is called, Java transfers control to that method. The statements inside the method body are executed. After the method finishes execution, control returns to the place where the method was called.
Example:
public class WorkingMethodExample {
public void message() {
System.out.println("Inside method");
}
public static void main(String[] args) {
WorkingMethodExample obj = new WorkingMethodExample();
System.out.println("Before method call");
obj.message();
System.out.println("After method call");
}
}
Output
Before method call
Inside method
After method call
This shows that the method runs only when it is called.
Real-Life Example of Method
Suppose we are creating a student result program. We can create separate methods for calculating total marks, percentage, and grade.
public class StudentResult {
public int calculateTotal(int m1, int m2, int m3) {
return m1 + m2 + m3;
}
public double calculatePercentage(int total) {
return total / 3.0;
}
public void displayResult(String name, int total, double percentage) {
System.out.println("Student Name: " + name);
System.out.println("Total Marks: " + total);
System.out.println("Percentage: " + percentage);
}
public static void main(String[] args) {
StudentResult obj = new StudentResult();
int total = obj.calculateTotal(80, 85, 90);
double percentage = obj.calculatePercentage(total);
obj.displayResult("Rahul Sharma", total, percentage);
}
}
Output
Student Name: Rahul Sharma
Total Marks: 255
Percentage: 85.0
This example shows how methods help divide a program into smaller and meaningful parts.
Important Points About Methods in Java
- A method is a block of code used to perform a specific task.
- Methods improve code reusability.
- Methods reduce code repetition.
- A method must be declared inside a class.
- A method runs only when it is called.
- A method can have parameters.
- A method can return a value.
voidmeans the method does not return any value.- Static methods can be called without creating an object.
- Non-static methods require an object for calling.
- Method overloading allows multiple methods with the same name but different parameters.
Advantages of Methods in Java
Methods are very useful in Java programming because they make code clean and reusable. They help divide large programs into smaller parts. This makes the code easier to understand and maintain.
Methods also help reduce errors because the same logic can be written once and used many times.
Practice Programs for Students
Students should practice the following programs after learning methods:
- Create a method to print a welcome message.
- Create a method to add two numbers.
- Create a method to find the square of a number.
- Create a method to check whether a number is even or odd.
- Create a method to find the largest of two numbers.
- Create a method to calculate student percentage.
- Create a method to calculate simple interest.
- Create a method to reverse a number.
- Create a method to check whether a number is prime.
- Create overloaded methods for addition.
Conclusion
Methods in Java are used to perform specific tasks and make programs more organized. They help in code reusability, reduce repetition, and improve program structure.
In this lesson, students learned what methods are, why methods are used, how to declare and call methods, how parameters and return types work, the difference between static and non-static methods, and how method overloading works.
After completing this lesson, students can move to the next topic, Class and Object in Java, where they will learn the foundation of object-oriented programming.
