165
Table of Contents
In this tutorial, you’ll learn about What is method in Java, Why Use Methods, Basic Structure of a Method along with examples.
What is method in Java
- A method in Java is a block of code that performs a specific task.
- Methods are used to execute a sequence of statements, and they can be called or invoked from other parts of your program.
- Think of methods as functions or procedures in other programming languages.(If you don’t know functions in any other programming language then don’t worry. We will explain you method in java in detail here. )
- They are the building blocks of Java programs, helping to organize and reuse code efficiently.
Why Use Methods?
- Reusability: Write a method once and use it multiple times.
- Organization: Break down complex problems into smaller, manageable pieces.
- Maintainability: Easier to update and manage your code.
- Readability: Makes your code easier to read and understand.
Basic Structure of a Method
A method in Java consists of several parts:
- Modifier: Defines the access level (e.g., public, private).
- Return Type: The type of value the method returns (e.g., int, void).
- Method Name: A unique name identifying the method.
- Parameter List: A set of parameters (optional) the method can accept.
- Method Body: The block of code to be executed.
Example of a Method
Let’s look at a simple example to understand what a method is and how it works:
public class MyProgram {
// This is a method named sayHelloWorld
public static void sayHelloWorld() {
System.out.println("Hello, World Impactmillions!");
}
public static void main(String[] args) {
// Call the sayHelloWorld method directly
sayHelloWorld();
}
}
In this example:
- public: This keyword means that the method can be called from anywhere in your program.
- static: This keyword means you can call this method without creating an object of the class. For now, just understand that it makes it simpler to use the method.
- void: This means that the method does not return any value.
- sayHelloWorld: This is the name of the method. You can call it anything you like, but it’s a good idea to name it something that describes what the method does.
- (): These parentheses show that the method does not take any inputs. Methods can take inputs, but this one doesn’t.
Inside the method, we have:
- System.out.println(“Hello, World!”);: This line of code will print “Hello, World!” to the console when the method is called.
How the Program Works:
- Starting Point: The main method is where the program starts running.
- Calling the Method: Inside the main method, we call the sayHelloWorld method by simply writing sayHelloWorld();.
- Executing the Method: When sayHelloWorld(); is called, the program jumps to the sayHelloWorld method and runs the code inside it, which prints “Hello, World!” to the console.