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.

public class Employee {	

	public static void main(String[] args) {
		addNum(3,4);   // calling method to add 3 and 4
		addNum(4,5);  // calling method to add 4 and 5

	}	
	
	//reusable method which is adding 2 numbers
	public static void addNum(int num1,int num2){   // method
		num1 = num1 + num2;
		System.out.println("Total sum : "+num1);
	}
}
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).

public class Employee {	

	public static void main(String[] args) {
		int sum = addNum(3,4);  
		System.out.println("Total sum is " +sum);    // take the returned value in a variable called sum

	}	
	
	//reusable method which is adding 2 numbers
	public static int addNum(int num1,int num2){   // method
		num1 = num1 + num2;
		return num1;           // return value 
	}
}
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.

 

Avatar photo

Shekhar Sharma

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

You may also like...