What is a Return Type?
In Java, a return type means the type of value a method gives back after execution.
Syntax :
returnType methodName() {
// code
return value;
}
Types of Return
1. void (No return value)
Method does not return anything
class Demo {
void display() {
System.out.println("Hello");
}
}
Use: When you just want to print / perform action
2. Return with value (int, String, etc.)
Method returns a value
class Demo {
int add(int a, int b) {
return a + b;
}
}
Calling:
int result = add(10, 20);
System.out.println(result); // 30
3. String return type
class Demo {
String getName() {
return "Silambu";
}
}
4. Boolean return type
class Demo {
boolean isEven(int n) {
return n % 2 == 0;
}
}
Flow of Execution
Let’s understand step-by-step:
Example:
class Demo {
int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
Demo obj = new Demo();
int result = obj.add(5, 3);
System.out.println(result);
}
}
Flow:
- Program starts from
main() - Object is created →
Demo obj = new Demo(); - Method call happens →
obj.add(5, 3) - Control goes to
add()method - Calculation happens →
5 + 3 = 8 -
return 8→ value goes back tomain() - Stored in
result - Printed →
8
-
void→ no return - Other types (
int,String, etc.) → must usereturn - Return value goes back to caller method
- Execution always starts from
main()
Return type in Java defines what type of value a method returns after execution.
Top comments (0)