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
}
Types of Methods in Java
1. Predefined Methods
These are already available in Java libraries.
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");
}
Types Of Methods
1. Method with No Parameter and No Return Value
No input,does not return anything
class Demo {
void greet() {
System.out.println("Hello Priya");
}
public static void main(String[] args) {
Demo d = new Demo();
d.greet();
}
}
Output
Hello Priya
Explanation
No Parameter inside ()
No Return Statement
Uses Void
2.Method with Parameter and No Return Value
takes input,does not return anything
class Demo {
void add(int a, int b) {
System.out.println(a + b);
}
public static void main(String[] args) {
Demo d = new Demo();
d.add(5, 3);
}
}
Output
8
Explanation
Takes parameter a and b
Prints result directly
Uses Void
3.Method with Parameter and Return Value
Takes input and return a value
class Demo {
int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
Demo d = new Demo();
int result = d.add(5, 3);
System.out.println(result);
}
}
Output
8
Explanation
Takes parameter
Returns result using return
4.Method with No Parameter but Return Value
Takes no input , return value
class Demo {
int number() {
return 10;
}
public static void main(String[] args) {
Demo d = new Demo();
int value = d.number();
System.out.println(value);
}
}
Output
10
Top comments (0)