Page 209 - ComputerScience_Class_11
P. 209
• return: In Java, when a method is called, the control is transferred to the method and it must return back to the
caller module after the execution of the method. This is done by the return statement. If the method does not
return any value, we must use the keyword “void” else we can use the datatype of the returned value.
Syntax:
return function_name(arguments)
{
Statements;
return statement;
}
For example:
Program 12 Write a Java program to calculate the sum of digits of a given number.
1 import java.util.*;
2 class SumOfDigits {
3 int sod(int n) {
4 int s = 0;
5 for (; n > 0; n = n / 10) {
6 s = s + n % 10;
7 }
8 return s;
9 }
10
11 public static void main(String[] args) {
12 Scanner sc = new Scanner(System.in);
13 int num, sum;
14 System.out.println("Enter a number: ");
15 num = sc.nextInt();
16 SumOfDigits obj = new SumOfDigits();
17 sum = obj.sod(num);
18 System.out.println("Sum of digits: " + sum);
19 sc.close();
20 }
21 }
The output of the preceding program is as follows:
BlueJ: Terminal Window - Java
Options
Enter a number:
45
Sum of digits: 9
Statements and Scope 207

