Java Methods With Examples

What is a method?

A method is a set of instructions dedicated to a specific purpose which is required frequently in our program. Writing a single block and using it many times helps to achieve reusability. The number of lines of codes is relatively less and it makes the code modular and readable. The section of code is always available, but inaction only when invoked.

Format of Method

The below-mentioned points are the content of the method

  • Access Specifiers
  • Return Data Type
  • Name
  • List of input parameters
  • Body

Let us see an example and discuss all the mentioned contents in detail

public int countVowels(String myString){
   int numOfVowels = 0;
   for(int i=0;i<myString.length();i++){
	   if(myString.charAt(i) == 'a' || myString.charAt(i) == 'e' ||myString.charAt(i) == 'i' || myString.charAt(i) == 'o' || myString.charAt(i) == 'u'){
	       numOfVowels++;
	   }
    }
    return numOfVowels;
}

Access Specifiers:

Here, the keyword public is an access specifier in the above example. It specifies wherefrom will this method be accessible. There are 4 different types of access modes. We will discuss access specifiers in detail in upcoming lectures.

Example: public, private, protected, default

Return Data Type:

As per the definition, a method has a dedicated purpose and yield some desired output. The return data type defines the data type of the output. It can be any primitive data type or even reference data type. In case the method has nothing to return, we mention void in its place. Our example method has return type int.

Example:  int, float, double, void

Name:  

Every method is to be assigned with a meaningful name aligning to its purpose. It starts with a lowercase alphabet. In case there are multiple words in the name, they are concatenated without space. For readability, the words except the first are initiated with uppercase.

Example:  login(),countVowels()

List of input parameters:

The methods work on a set of inputs. These inputs are specified as a comma-separated pair of dataType variableName inside (). In case, no parameter is required, we keep it blank. Our example takes in String myString as an input.

Example:  (int myInt) , (int[] array, int valToFind) , ()

Body:

This is the real part. The code enclosed by the {} is the body of the method. It contains the set of local variables, a set of instructions that serve a specific purpose.  In case the return type is not void, the body ends with return in the last statement. In the above example, our method counts the number of vowels in the input string.

Type of Method

On the basis of whether a method is provided by the Java Standard Library, or defined by the coder as per requirement, there are 2 types of method:

  • Standard Library methods
  • User-defined methods

Standard Library methods

Java Class Libraries comprises pre-defined methods that are ready for use and provides the base for complex tasks that simply require invoking of these methods. Such methods are Standard Libraries. In our previous lectures like Java Characters, Java Math, Java Arrays, etc we have seen a series of methods and their examples that are pre-defined and are the optimized version ready to use.  

Example: 

toUpperCase() is a static method of class Character which is used to convert the character to its upper case equivalent.
toLowerCase() is a static method of class Character which is used to convert the character to its lower case equivalent.
public class MyCharacter{
     public static void main(String []args){
        System.out.println("Upper case of e is "+Character.toUpperCase('e'));
        System.out.println("Lower case of H is "+Character.toLowerCase('H'));
     }
}

Output:

Upper case of e is E
Lower case of H is h

User-defined method

The method written as per our requirement is called the User-defined method.

Define a method

The method defined above is made a member of class myVowelsCount.

class myVowelsCount{
    public int countVowels(String myString){
        int numOfVowels = 0;
        for(int i=0;i<myString.length();i++){
             if(myString.charAt(i) == 'a' || myString.charAt(i) == 'e' ||myString.charAt(i) == 'i' || myString.charAt(i) == 'o' || myString.charAt(i) == 'u'){

                numOfVowels++;
             }
        }
        return numOfVowels;
    }
}

Invoke a method

The method so defined is a part of class myVowelsCount. The method countVowels can be invoked using the (.) operator. We need to create an instance of our class and access the method the way, members are accessed.

public class MyCharacter{
     public static void main(String []args){
         myVowelsCount myObject = new myVowelsCount();
        System.out.println("Number of Vowels in education is "+myObject.countVowels("education"));
        System.out.println("Number of Vowels in rythm is "+myObject.countVowels("rythm"));
     }
}

Output:

Number of Vowels in education is 5
Number of Vowels in rythm is 0

Note that the methods discussed here are instance methods. There is another type of method which is a member of class instead of an object. Such methods are static methods. We will discuss it in detail in our upcoming lectures.

This was an overview of methods. In the next Lecture, we are going to discuss Constructors.