Methods in Java
Methods
Methods are the block of code that performs a specific task. To declare a method, you must go outside the main method.
Things To Remember
- Methods are also known as functions.
- Method only runs when it is called.
- We can create multiple methods and call multiple times.
Advantages
- We can reuse our code.
- We can create different methods for different purposes.
- It will reduce code duplication.
- We can divide complex problems into multiple chunks.
How To Create A Method
We must create a method inside the class. We already have pre-build methods, and we can also create and use our methods. We will learn it later.
Syntax
returnType myMethod() {
// method body here
}
- returnType Specifies the return type of the method. It can be void, int, float, boolean, or any other type. For example, if a method has a String return type, it returns a String value. If the method does not return a value, its return type is void.
- myMethod() is the name of the method.
- {} is starting and ending block of the method.
Example Of Method
public class Main {
public static void main(String[] args) {
printName();
}
static void printName() {
System.out.println("Hi I am Rahul!");
}
}
- printName() is the name of the method.
- static means that the method belongs to the Main class and not an object of the Main class. We will learn class and object later.
- void means it does not have a return value. This method does not return a value, so its return type is void.
- printName();. The main method is used to call a method. Method couldn’t run if we don’t call it.
Info
Note: We can call methods multiple times.