Methods in Java

Methods are ways to group together a bunch of statements which work collectively to get a logical unit of work done. For example : a method to print something on the screen or a method to take user input from the keyword etc.

Java classes are made of  methods and variables. In simple terms methods are ways to manipulate the variables and do some meaningful calculations on them.


1. Syntax to declare a Method

Here is a simple method to add two integer variables:

Methods are quite versatile and they offer a lot more options than one shown above.


2. Method declaration

A method must be declared before it can be used. A method is always declared inside a class. The anatomy of any method declaration looks like:

Anatomy of a method in Java
Anatomy of a method in Java

Here is what each word means in short:

  • Access Modifier : It controls the visibility of a method. It can be one of public, private, protected or default access level.
  • Static Keyword : It is optional. If used, it means that the method belongs to the class and not any object instance.
  • Return Type : The data type of the value returned by the method. If method returns nothing then it should be void.
  • Method Name : As it says, the name of the method.
  • Paramter-list : The variables that are passed to the method by the user. It can be either empty or a comma separated list of data-type and variable-name tuples.
  • throws keyword : If the method may throw any exception then this keyword is used to denote the type of exception it may throw.
  • Exception Type : A list of exceptions that the method may throw.
  • Method Body :  Actual logic of the program.
  • Return keyword :  keyword used to return a value or an object from the method.

Note that you don’t have to use each one of them in a program. Some are compulory and some are depended on the need of the program.


3. Calling a Method

After a method has been declared, you can call the method to perform a task which it was declared for. A method can be called from two places:

  • From inside the same class : To call a method, you type the method name followed by a pair of parenthese.
  • From inside another class : To call a method from another class, you first have to instantiate an object of the class and call that method on that object.

Output :


4. Return value of a Method

A method can return any type of data, even the reference types. You can use the return statement to return a value or object from a method.


4.1 Example : Returning a primitive data type from a Method

Output :


4.2 Example : Returning an object from a Method

Output :


5. Advantages of using a Method

A program written using methods has a number of advantages.

  • Logical grouping : A method is a set of instructions written to get a logical unit of work done. Like a method to get the user input from keyboard.
  • Code Reuse : The code written inside a method is resuable i.e you don’t have to re-write the same bunch of statements again and again, you can simply call the method.
  • Easy to debug : You can test a method once and reuse this code again and again without worrying about its correctness.
  • Improves readability : A method is often given a descriptive name. By looking at the method name you can get a general idea of what a method does and why some statements have been written. It significantly reduces the program size as well.

6. Parameter vs Argument

People often tend to use these two words in place of each other but there is a difference between the two words:

  • Parameters are the variables used in the method signature. They are just the place holders.
  • Arguments are the actual values passed when calling the method.

Output :

Parameters are also called formal parameters.


7. Method Signature

The method signature consists of method name, number and type of arguments the method takes. It is used by the JRE to identify the method to be called at run time.

A class can have multiple methods. But the method signature of any of those methods must not match. If it does, the program won’t compile.

  • Following four methods have different method signatures.

  • Following methods don’t have different method signatures beacuse only thier return types differ. JRE cannot use return types to distinguish between two methods:

 


8. Access Control

There are four access levels, all of which can be used with methods with their usual meanings:

  • public : A public method can be called from anywhere, from any class inside any package.
  • private : A private method can be called only from the class where it is defined.
  • protected : This keyword is used in context of inheritance. A protected method can be called from any class inside its own package and the subclasses of its class in other packages.
  • default : Methods declared without any of the above three keywords have default access level. They can be called from any class in the package they are defined.

Let’s have an example to understand this concept:

Output :

Not that once a car is made, you cannot change anything. It happens so beacuse the data fields and methods that modify those fields are private. You can only access those data by using public method getType() and getMileage() but can’t change them.

You have already seen many examples on default access level and you will see the use of protected keyword when you learn about inheritance.


9. Setter and Getter Methods

You will often see people using these two words. In fact you have seen them many times uptil now, like in the last example.

  • Setter methods or Setters : They are used to set the data fields. They start with prefix set.
  • Getter methods or Getters :  They are used to get the value of data fields. They start with prefix get.

Let’s have another example:

Output :

 


10. Method calling another Method

It is very common to call one method from inside another method:

Output :


11. Static Methods

When you use the modifier static before a method, then that method can be called using the class name directly. You don’t have to instantiate an object in order to call them.

Output :

Static methods are often used to create libraries.

A static method comes with some restrictions as well:

  • A static method can call only other static methods
  • A static method can access only static data.
  • A static method cannot use this or super keyword inside its body.

12. More to Learn

You will learn following topics in next few lectures:

  • Method Overloading
  • Argument Passing: Call by value vs Call by reference
  • Recursion
  • Command Line Arguments
  • Variable Length Arguments or Varargs

Below are some topics related to methods but you need to learn some more Java concepts in order to understand them.

  • Method in Interfaces
  • final method
  • Abstract method
  • Methods and exceptions