1. What is Return Type in Java?
Return type in Java means what value a method gives back after execution.
Syntax:
returnType methodName(){
// code
return value;
}
Example:
int add(){
return 10;
}
Here:
int → return type
add() → method name
return 10 → returning value
So this method returns integer value.
2. Why Return Type is Used
1. To Send Result Back
class Demo {
static int add(){
return 5 + 3;
}
public static void main(String args[]){
int result = add();
System.out.println(result);
}
}
Output:
8
Here:
add() returns 8
main method receives it
prints result
Without return → you cannot send value back.
Example Without Return Type:
class Demo {
static void add(){
System.out.println(5 + 3);
}
public static void main(String args[]){
add();
}
}
Output:
8
Here:
void means no return value
Only prints
Can't store result
You cannot do this:
int result = add(); // ERROR
Because void returns nothing.
Top comments (0)