- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Importance of return type in Java?
A return statement causes the program control to transfer back to the caller of a method. Every method in Java is declared with a return type and it is mandatory for all java methods. A return type may be a primitive type like i nt, float, double, a reference type or void type(returns nothing).
There are a few important things to understand about returning the values.
The type of data returned by a method must be compatible with the return type specified by the method. For instance, if the return type of some method is boolean, we can not return an integer.
The variable receiving the value returned by a method must also be compatible with the return type specified for the method.
The parameters can be passed in a sequence and they must be accepted by the method in the same sequence.
Example 1
public class ReturnTypeTest1 { public int add() { // without arguments int x = 30; int y = 70; int z = x+y; return z; } public static void main(String args[]) { ReturnTypeTest1 test = new ReturnTypeTest1(); int add = test.add(); System.out.println("The sum of x and y is: " + add); } }
Output
The sum of x and y is: 100
Example 2
public class ReturnTypeTest2 { public int add(int x, int y) { // with arguments int z = x+y; return z; } public static void main(String args[]) { ReturnTypeTest2 test = new ReturnTypeTest2(); int add = test.add(10, 20); System.out.println("The sum of x and y is: " + add); } }
Output
The sum of x and y is: 30