Quick Links
Methods define behavior. A Java Methods is a collection of statements that are grouped together to perform an operation. System.out.println() is an example of a method.
You can define your own methods to perform your desired tasks.
Let’s consider the following code:
class MyClass {
static void sayHello() {
System.out.println(“Hello World!”);
}
public static void main(String[ ] args) {
sayHello();
}
}
// Outputs “Hello World!”
Calling Methods:
You can call a method as many times as necessary.
When a method runs, the code jumps down to where the method is defined, executes the code inside of it, then goes back and proceeds to the next line.
Example :
class MyClass {
static void sayHello() {
System.out.println(“Hello World!”);
}
public static void main(String[ ] args) {
sayHello();
sayHello();
}
}
// Hello World!
// Hello World!
Java Method Parameters:
You can also create a method that takes some data, called parameters, along with it when you call it. Write parameters within the method’s parentheses.
Example :
class MyClass {
static void sayHello(String name) {
System.out.println(“Hello ” + name);
}
public static void main(String[ ] args) {
sayHello(“David”);
sayHello(“Amy”);
}
}
// Hello David
// Hello Amy
The Return Type:
The return keyword can be used in methods to return a value.
Example :
class MyClass {
static int sum(int val1, int val2) {
return val1 + val2;
}
public static void main(String[ ] args) {
int x = sum(2, 5);
System.out.println(x);
}
}
// Outputs “7”