SILAMBARASAN AWhat is a Return Type? In Java, a return type means the type of value a method gives back...
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
Method does not return anything
class Demo {
void display() {
System.out.println("Hello");
}
}
Use: When you just want to print / perform action
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
class Demo {
String getName() {
return "Silambu";
}
}
class Demo {
boolean isEven(int n) {
return n % 2 == 0;
}
}
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:
main()
Demo obj = new Demo();
obj.add(5, 3)
add() method5 + 3 = 8
return 8 → value goes back to main()
result
8
void → no returnint, String, etc.) → must use return
main()
Return type in Java defines what type of value a method returns after execution.