Table of Contents
What is a Method
Methods in Java or a function is a block of code that contains execution statements and operations. It mainly describes what your code can do. It is similar to the mathematical function like sqrt(square root) which finds the square root of a number. Similarly in Java, we can have functions or methods that describe a specific code behavior. We should always write methods only within a class.
Advantage of Methods in Java
- Reusability: Methods allow us to reuse the code by just calling the specific function. This prevents us from writing redundant code and enhances reusability.
- Readability: It makes the code more readable and understandable since we group the related actions together in a method.
- Maintainability: Methods help us to maintain the code easier and allow us to refactor it easily when changes are required.
Types of Methods in Java
Java supports two different types of class methods:
Standard Library Methods
These are pre-defined methods that are present in the Java library. We can use these methods without any changes. For example, we have the print() method of the System class that allows us to print a statement. We can invoke this method directly to print the statement as you can see in the below example.
public class StandardMethod { public static void main(String[] args) { System.out.println("This is a standard library method"); } }
This is a standard library method
User-defined Methods
When we create our own function or method, we call it a user-defined method. We can group similar actions together in a function. For example, add() is a method that adds numbers. Hence methods are used to define a task or functionality.
Next, let’s see how to create and invoke user-defined methods in Java.
Create a method
We must always create a method inside a class. A method contains a method name followed by parentheses().
Below is the syntax to create a method.
access_type return_type method_name(arguments) { //method body }
access_type: it specifies the access modifier like public, private, protected.
return_type: Specifies if the method returns any value. It may be void(no return type) or specify a type like String or int
method_name: Any valid name that suites the method behavior
arguments: If the method requires any parameters or arguments to perform an operation. It is optional.
method body: Functionality of the method
Below is an example of creating a user-defined method. Here we have created a method add which has void return type and public access type. Inside the method body, we have a print statement.
public class MethodExample { public void add() { System.out.println("Addition method"); } }
Naming convention of a method
- Method name always starts with a lowercase
- It should always be a verb. Eg: add()
- If the name contains more than two words, it should start with a verb followed by an adjective or noun. Eg: getName()
- If there are multiple words for a method name, the first letter of the words other than the first word should start with a capital letter. Eg: getAddressDetails()
Invoke a Java method
A method is usable only when we invoke a call a method. We can call a method using the method name followed by the arguments if any within the parentheses.
method_name(arguments);
Below is a simple example of invoking a method. Since the methods are defined within a class, we can invoke the method by only using the class instance. In this example, add is the method and m is the class object.
public class MethodExample { public void add() { System.out.println("Addition method"); } public static void main(String[] args) { MethodExample m = new MethodExample(); m.add(); } }
Addition method
Method with no parameter and no return type
Below is an example of a java method that does not have any arguments or return types. When the method does not return any value, we mention the void keyword as the return type. When the method has no arguments, we mention it with empty parentheses.
We initialize the integer variables x, y using constructor, and use this value directly inside the add method. This method does not have any parameters and no return type.
public class Addition { int x,y; Addition(int x, int y) { this.x = x; this.y = y; } public void add() { int sum = x + y; System.out.println("Sum is: " + sum); } public static void main(String[] args) { Addition a = new Addition(5,8); a.add(); } }
Sum is: 13
Method with parameters but no return type
The below example illustrates a method with parameters but does not return any value. The method difference accepts two parameters both of integer type. Hence when we call the method, we need to pass the values to the method which assigns to the parameter variables inside the method. Here, x and y parameters take the values 4 and 5 respectively.
public class Subtraction { public void difference(int x, int y) { int diff = x - y; System.out.println("Difference is: " + diff); } public static void main(String[] args) { Subtraction s = new Subtraction(); s.difference(10, 4); } }
Difference is: 6
The main difference between class variables and parameter variables is that class variables can be used in the entire class where as parameter variables can be used only within the method.
Method that has return type but no parameters
In the below example, the method product returns a value of integer type. Any method that has a return value should have the return statement with the value that needs to be returned. In this case, the variable product is the return value. Similarly, while invoking a method with the return type, we need to have a variable of the same type that receives the function output. Hence we use int prod = m.multiply().
public class Multiplication { int product,x, y; Multiplication(int x, int y) { this.x = x; this.y = y; } public int multiply() { product = x * y; return product; } public static void main(String[] args) { Multiplication m = new Multiplication(4,8); int prod = m.multiply(); System.out.println("Product is: " + prod); } }
Product is: 32
Method with parameter and return type
In this example, the method greaterNumber has both parameters and return value. Hence when calling the method, we should pass arguments as well as have a variable to assign the return value from the method. In this case, x and y values have 47 and 29 respectively and return the variable max from the method. While invoking the method, we have the variable value that receives the output of this method.
public class Compare { int max; public int greaterNumber(int x, int y) { if(x > y) max = x; else max = y; return max; } public static void main(String[] args) { Compare c = new Compare(); int value = c.greaterNumber(47, 29); System.out.println("Greater value is: " + value); } }
Greater value is: 47
Static Java Method
We have seen in the Java Static keyword tutorial, that we can use the static
keyword for the methods. In this case, we do not need any class object to invoke the static method and can call using the method name directly.
public class MethodExample { public static void add() { System.out.println("Addition method"); } public static void main(String[] args) { add(); } }
Addition method
Instance Methods
Methods which are non-static
and that belongs to a class is called an instance
method. These methods require an object or class instance to make a call to the function. This is in contrast to the static methods which do not require any object.
In this example, we can understand the difference in invoking an instance method and a static method. add is a static method and subtract is an instance method.
public class MethodExample { //Static method public static void add() { System.out.println("Addition method"); } //Instance method public void subtract() { System.out.println("Subtraction method"); } public static void main(String[] args) { MethodExample m = new MethodExample(); //Invoking a static method add(); //Invoking an instance method m.subtract(); } }
Types of instance methods
- Accessor method: We use this method to read the instance variables. Generally, these methods have a prefix get. Accessor methods can also be called as getters to read the values of private variables.
- Mutator method: We use this method to modify the instance variable value. They have a prefix set. These are also called as setters and are used to set the values of private variables.
These methods are used to read and update private variables from different classes.
Example:
public class InstanceMethodDemo { private String name; //Getter method public String getName() { return name; } //Setter method public void setName(String name) { this.name = name; } public static void main(String[] args) { } }
Abstract method
An abstract method has only a function declaration and no definition. This means, that it does not contain a method body. We use abstract methods to implement abstraction. Abstract class contains abstract methods. The class which extends the abstract class implements the functionality of the abstract method.
abstract class class_name { //abstract method abstract void method_name(); }