Introduction to Methods
In this chapter, we're going to explore a powerful way to tidy up our code – using something called methods.
As our programs get more complex, the code can start to look messy and become a bit of a puzzle. That's where methods come to the rescue! They allow us to break our program into smaller, more manageable pieces, making it much easier to understand and use.
Imagine let's consider a scenario where you have a program for managing a simple shopping cart. Instead of tackling everything at once, methods let you create specific tools for each job:
- Method to Add Items to the Cart.
- Method to Calculate Total Cost.
- Method to Remove Items from the Cart.
This way, you can tackle one piece of the problem at a time, making your program much cleaner and more organised.
Method creation
Alright, let's talk about creating methods – a way to organise our code neatly. Don't worry, it's not as complicated as it sounds!
Understanding Method Syntax:
When we create a method, we follow a specific structure:
returnDataType methodName() {
// Your code goes here
}
- returnDataType: This represents the type of information the method gives back (like int - number, words - String, etc.).
- methodName(): This is the name of our method. It's like giving a nickname to a tool.
- {...}: The curly braces hold the instructions or the job the method does.
Let's go through a different example to help understand the concept of creating methods:
Consider a simple example where we create a program to repeatedly print a message. We'll use a method to handle this repetitive task:
// Method to print a message multiple times
void printMessage() {
for (int i = 0; i < 3; i++) {
System.out.println("Hello, How are you?.");
}
}
In this example:
- We've created a method named printMessage.
- We use void return type if the method doesn't return any value.
- Inside the method, it uses a loop to print the message "Hello, How are you?." three times.
When we run the program and call printMessage method, it prints the message three times. This illustrates how methods help us encapsulate a specific action, making our code more modular and readable.
How to call a Method in Java?
Let's use our earlier example with printMessage() method in a program -
class Main {
// Method to print a message multiple times
void printMessage() {
for (int i = 0; i < 3; i++) {
System.out.println("Hello, How are you?.");
}
}
public static void main(String[] args) {
// To see the greeting message, we need to call (invoke) the printMessage() method
}
}
Running the above code won't display any output because creating a method doesn't automatically execute the code within it.
The purpose of the code is to offer us a tool (the printMessage() method) that we can use when needed. To make the greeting message appear, we must call (invoke) the printMessage() method. The process of invoking the method is what triggers the execution of the code inside it.
In the main method, we have the opportunity to call the printMessage() method and witness the greeting in action. This calling or invoking step is essential to see the intended output.
Steps to call a Method in Java
In Java, calling a method involves using an object of the class. To do this, the initial step is to create an object of that class.
Main obj = new Main();
In this case, since our method is within the Main class, we've created an object named "obj" of that class.
Quick Note: We haven't delved into classes and objects extensively, so for simplicity, let's concentrate on the essential aspect of calling the method. We will learn more about classes and objects later.
Now, with this object, we can proceed to invoke the printMessage() method.
class Main {
// Method to print a message multiple times
void printMessage() {
for (int i = 0; i < 3; i++) {
System.out.println("Hello, How are you?.");
}
}
public static void main(String[] args) {
// Create an object to use our printMessage method
Main obj = new Main();
// Use the object to greet by calling the method
obj.printMessage();
}
}
Output
Hello, How are you?
Hello, How are you?
Hello, How are you?
Explanation
In the code, the line obj.printMessage(); is how we use our object (obj) to execute the printMessage() method. Think of it like giving instructions to our object to perform the greeting task.
Here's how it works:
- Using the Object and Dot Operator:
- We use the object (obj) along with the dot operator (.) to call the method (printMessage()). It's like telling our object to specifically call the method action.
- Working of the Code:
- When we call a method, the program's control jumps to the method definition.
- The statements inside the method are then executed.
- After executing all the statements in the method, the program's control jumps back to the next code after the method call.
- Important Note:
- The code to create the object and call the method is placed inside the
public static void main(String[] args)
method. This is because the execution of Java code begins from here.
- The code to create the object and call the method is placed inside the
This whole process is like using a object to perform a specific action, and understanding this helps us organize and structure our code effectively.