return statement:
return is a control transfer statement.
It is used to return maximum one data from called method to calling method.
Note:
- It is mandatory to specify what type of data the method is returning is known as the return type of a method.
- ex. void, int, char, boolean, String, etc.
void:
- void is a return type.
- If the method is having void as a return type which means the method is not returning any data.
Note:
- Any method is having void as a return type then it is not mandatory to write return statement.
- If the method is having other than void as a return type then it is mandatory to write return statement.
Write a java program consist of add method to perform addition of two numbers using return statement.
- class Addition
- {
- public static int add(int a, int b)
- {
- int c =a+b;
- return c;
- }
- public static void main(String [] args)
- {
- System.out.println("MB");
- System.out.println(add(10,20));
- System.out.println("ME");
- }
- }
Output:
MB
30
30
ME
\
Tracing
Write a java program consist of add method to perform addition of two numbers using return statement with storing data.
- class Addition
- {
- public static int add(int a, int b)
- {
- int c =a+b;
- return c;
- }
- public static void main(String [] args)
- {
- System.out.println("MB");
- int res = add(1,2);
- System.out.println(res);
- System.out.println("ME");
- }
- }
Output:
MB
3
3
ME
---------------xxxxxxxxxxx-----------------xxxxxxxxxxx--------------xxxxxxxxxxx--------------
Method overloading:
The class having more than one method with same name but different formal arguments either differing length OR differing data type is known as method overloading.
Create a class with multiple methods to perform addition of
(a) 2 numbers (b) 3 numbers (c) 4 numbers
return data from each method then store and print
- class Addition
- {
- public static int add(int a, int b)
- {
- int c =a+b;
- return c;
- }
- public static int add(int a, int b, int c)
- {
- int d =a+b+c;
- return d;
- }
- public static int add(int a, int b, int c, int d)
- {
- int e =a+b+c+d;
- return e;
- }
- public static void main(String [] args)
- {
- int res1 = add(1,2);
- int res2 = add(1,2,3);
- int res3 = add(1,2,3,4);
- System.out.println(res1);
- System.out.println(res2);
- System.out.println(res3);
- }
- }
Output:
3
6
6
10
0 Comments