Methods
- Performs a specific task,Improves Readability,Allows code reuse
- Can take Parameters and Return a value
- Can be Static or Instance
- Supports Method Overloading
Basic Syntax
returnType methodName(parameters) {
// method body
// code to execute
return value; // optional
}
Create a Method
- A method declared inside a class.
- Defined with name of the method ,followed by the parentheses()
public class Main{
static void myMethod(){
//code to be executed
}
}
Explanation
myMethod() => name of the method
void => does not return a value
static => method belongs to main class ,but not object of the main class
Call a Method
write method's name followed by parentheses() and semicolon;
Example
public class Main{
static void myMethod{
system.out.println("working as software developer")
}
public static void main(String[]args){
myMethod();
}
}
A method can be called multiple times
public class Main{
static void myMethod{
system.out.println("working as software developer")
}
public static void main(String[]args){
myMethod();
myMethod();
}
}
Types of Methods in Java
1. Predefined Methods
These are already available in Java libraries.
Example of Predefined Methods
System.out.println()
Program Example:
System.out.println("Hello");
Here, println() is a predefined method.
2. User-defined Methods
Methods created by the programmer.
Example:
int add(int a, int b) {
return a + b;
}
- Method Parameters
Methods can accept input values.
void add(int a, int b) {
System.out.println(a + b);
}
Explanation
a and b are parameters
- Return Type
A method can return a value using return
Example:
int add(int a, int b) {
return a + b;
}
Usage:
int result = add(5,3);
System.out.println(result);
Output
8
3.Method Without Return Value (void)
If a method does not return anything, we use void.
Example:
void message() {
System.out.println("Welcome");
}
4.Static Methods
Belong to the class,not to the object
class Test {
static void show() {
System.out.println("Static Method");
}
public static void main(String[] args) {
show();
}
}
Hence no object is required
5.Instance Methods
Requires an object to call them
class Test {
void display() {
System.out.println("Instance Method");
}
public static void main(String[] args) {
Test t = new Test();
t.display();
}
}
6.Method Overloading
Allows multiple methods with the same name but different parameters.
int add(int a, int b){
return a+b;
}
int add(int a, int b, int c){
return a+b+c;
}
7.Method can call other methods
void greet(){
System.out.println("Hello");
}
void welcome(){
greet();
System.out.println("Welcome");
}
Top comments (0)