Java Method

Filed Under: Java

Java is an Object Oriented Programming language. Java Methods are defined in the class and they are the backbone of its programming.

Java Method

Java Method is a collection of statements to process some specific task and return the response to the caller. Methods allow us to write reusable code and dividing our program into several small units of work. Java Method promotes clean and more readable code.

Java Method Components

Let’s look at the various components of a java method.

  1. Access Modifiers: Java Method access modifiers defines who can call the method. It’s used to restrict the scope of the method. There are four access modifiers in java – private, protected, public and default. Apart from access modifiers, we can also specify a method to be static, in that case, we don’t need to create an object to call the method. We can directly call a static method through class. Static methods are useful for creating utility methods.
  2. Return Type: Java Methods must specify the return type. They can be any primitive type or an object. If the method is not returning anything, then we must use void as return type.
  3. Method Name: Every method in Java must have a name. It’s used to identify the method. We should provide descriptive names for our method to give some idea about the task performed by the method. If you have written any Java program, I am sure you would have seen java main method.
  4. Method Parameters: We can pass parameters to a method, they are defined in the parenthesis after the method name. Usually, method statements work on these parameters to achieve their tasks.
  5. Exceptions List: Sometimes a java method can throw exceptions. We can define them using throws keyword. If there are multiple exceptions that can be thrown, then we can separate them using comma.
  6. Method Body: This is where all the method operations take place. Method body contains statements to be executed by the method and they are inside the curly brackets.

Below image shows the different components of a java main method.

Java Method

Java Method Signature

Java Method Signature consists of its name and parameter types in the declared order. In a class, there can be multiple methods but each of them should have a different signature otherwise it won’t compile. Java Method signature is used by JRE to identify the exact method to be called when invoked in our program.


public void print(String s) {}
private static int print(String s) {}

If we have above methods in a class, it won’t compile because both the methods have same signature.


public void print(String s, int i) {}
private static void print(int i, String s) {}

Above methods are different because the parameters order are not the same.

Calling a Java Method

Let’s see an example where we will create a main method and call some other method.


package com.journaldev.util;

public class MathUtils {

	public int add (int x, int y) {
		return x + y;
	}
	
	public static void main(String args[]) throws Exception {
		MathUtils mu = new MathUtils();
		System.out.println(mu.add(5, 2));
		MathUtils.print("Static Method");
	}
	
	public static void print(String s) {}
	
}

When we will run above program, java main method will execute and it will call MathUtils methods. Notice that if the method is not static, we need an object to call it. However, if the method is static then we can simply call it using the class name.

Also, notice that println() method is defined in the System.out object. It’s a standard java library method where as add() and print() methods in MathUtils class are called as user defined method.

Java Method Examples

Let’s look at some java method examples.

  • Overloaded Methods: If a class have multiple methods with the same name, they are called as overloaded methods.
    
    public void print(String s) {
    	System.out.println(s);
    }
    public void print(String s, int times) {
    	for (int i=0; i< times; i++) {
    		System.out.println(s);
    	}
    }
    
  • Method Throwing Exception: Let's look at an example where we will throw exception.
    
    public int divide(int x, int y) throws IllegalArgumentException {
    	if(y==0) throw new IllegalArgumentException("Can't divide by 0");
    	return x/y;
    }
    
  • Recursive Method: When a method calls itself, it's called as a recursive method. We should be very careful in defining recursive method because it can go into infinite look if there is no terminal condition. Let's look at a method that returns factorial of a number using recursion.
    
    public static long factorial(long n) {
    	if (n == 1)
    		return 1;
    	else
    		return (n * factorial(n - 1));
    }
    
  • Method Calling Another Method: We can call another method from a method, let's redefine the above overloaded methods by reusing the print(String s) method.
    
    public void print(String s) {
    	System.out.println(s);
    }
    public void print(String s, int times) {
    	for (int i=0; i< times; i++) {
    		print(s);
    	}
    }
    
  • Java Interface Static Method: Java interfaces can have static method from Java 8 onwards. Here is a small example of the interface static method.
    
    public interface MyData {
    
    static boolean isNull(String str) {
    	System.out.println("Interface Null Check");
    
    	return str == null ? true : "".equals(str) ? true : false;
      }
    }
    
  • Java Interface Default Method: From Java 8 onwards, interfaces can have default method implementations.
    
    public interface MyData {
    
    	default void print(String str) {
    		if (!isNull(str))
    			System.out.println("MyData Print::" + str);
    	}
    }
    

    Read more at Java 8 Interface Changes.

  • Java Getter Setter Methods: Java Getter Setter Methods are conventional methods to access and update an object properties. These methods create abstraction and we can restrict access to different properties. Most of the IDEs support easy creation of getter-setter methods of a property.
    
    private String name;
    
    public String getName() {
    	return name;
    }
    
    public void setName(String name) {
    	this.name = name;
    }
    
  • Java Abstract Methods: Java abstract class and interface can declare methods without its body. The class extending or implementing them have the responsibility to provide method definition. These methods are declared using abstract keyword in abstract class. Java interface methods are explicity abstract.
    
    public abstract class Person {
    	public abstract void work();
    }
    
    public interface Shape {
    	//interface methods are implicitly abstract and public
    	void draw();
    	
    	double getArea();
    }
    

That's all for methods in java.

Comments

  1. Nagamani says:

    sir,there is a mistake in this blog.In java abstract method concept you wrote java interface methods are explicitly abstract.
    where in code comment you wrote interface methods are implicitly abstract and public.

  2. Daniela says:

    You are such a great teacher!!! Your blog is extremely useful for beginners like me 🙂

  3. ANIL says:

    Sir,please explain Getter setter methods more elaborately with another example

  4. rakshit malhotra says:

    Thanks! It was a very nice blog. And the way you have explained Java method signature it was very helpful to me.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages