Methods Part-2 (Lesson-24)

In this lesson we will talk about methods which can get input and return output. Such methods are also called functions.They can take any number of inputs but return only one output. Input is given as parameters to the method and output is returned by the method itself.
Previously, you studied the format of a method that took no parameters and it looked like this:

public static void myMethod() {
}

You give parameters separated by commas in those round brackets like this:

public static void methodName(DataType variable1 , DataType variable2 , DataType variable3){
}

In this way, a method can receive any number of parameters.

Let's consider a method that takes two ints as parameters and displays their sum on the screen.

public static void add (int a, int b)
{
int sum=a+b;
System.out.println(sum);
}

While calling the method, you will "pass" parameters in round brackets separated by comma.

add(5,3);

You can also pass a variable of the same DataType as parameter. For example:

int n=32,m=36;
add(n,m);

Now let's see the code that implements the above method concept.

It should be noted that the parameters should be passed in the same order as they were written while defining the method.

Now let's see how to return some output from the method. You must know that which DataType the method will return. The method which returned nothing used the void data type. void means nothing. So a method returning something will use a particular DataType instead of void. Also there will be a return statement at the end of the method. A method ends when a return statement is encountered. It will look like this:

public static DataType methodName(parameters){
return someData;
}

For example, if we were to write a method which will get two numbers as parameters and return their sum, it'll be like:

public static int add(int a , int b)
{
int sum = a + b;
return sum;
}

When calling this method, you will get the output in a variable. It will go like this:

int result=add(23,65);

The implementation will be like:


Now let's do some practice.

A method that will get the name and email of a person and display it on the screen in a good manner.
*Why did we use void in the above example?
**What will happen if you pass the parameters wrong while calling the new method from the main? If you put the email first or pass some number instead of String? Go try it.

A method that will get an int array as a parameter and return the largest number. (Yes we can also pass whole arrays as the parameters for methods)


Practice Corner:

  • Write a method which gets two numbers as parameters and returns the largest.
  • Write a method to get 3 numbers as parameter and return the smallest.
  • Write a method to get an array as parameter and return the smallest number in the array.


Post a Comment

0 Comments