Methods and return value

Programming is considered good if it contains reusable components. By making reusable components, there will be less no. of line of code, code will look better, you don’t have to write the same functionality again and again, improves the readability of the program etc.

What does it mean by reusable components?

Consider one simple example , that there is requirement to create a template which will have 3 fields as Name, email id, phone number. We created the template. Now, this template is used in a bank to maintain the customer details, and the same template can be used by a librarian to store the student details who borrow the books. In this case we don’t need to write the template 2 times. Same template can be reused.

Look at the below example where a reusable method addNum is created. So, to add the 2 set of  numbers we have written a common method as you can see in the below example.

Output : Total sum : 7
Total sum : 9

Can a method return a value?

Yes, a method can return a value. You will observe in the above example, that a keyword void has been used. Void means that method returns no value. For returning a value , in place of void you have to use a particular data type which you want to return from the method.

In above example, we are calculating sum which is of int data type. So, we will write int instead of void. Look at the below code for better understanding.

One more important point to note that, we have to use the return keyword in the method and pass the value which needs to be returned.We can also capture the returned value in a variable of the same data type(in our example sum).

Output : Total sum is 7
Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.


Object and Classes
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *