Java Top

The early-bird price of the new Learn Spring Security OAuth course packages will increase by $50 on Wednesday:

>> CHECK OUT THE COURSE

1. Introduction

In Java, methods are where we define the business logic of an application. They define the interactions among the data enclosed in an object.

In this tutorial, we'll go through the syntax of Java methods, the definition of the method signature, and how to call and overload methods.

2. Method Syntax

First, a method consists of six parts:

  • Access modifier: optionally we can specify from wherein the code one can access the method
  • Return type: the type of the value returned by the method, if any
  • Method identifier: the name we give to the method
  • Parameter list: an optional comma-separated list of inputs for the method
  • Exception list: an optional list of exceptions the method can throw
  • Body: definition of the logic (can be empty)

Let's see an example:

 

Let's take a closer look at each of these six parts of a Java method.

2.1. Access Modifier

The access modifier allows us to specify which objects can have access to the method. There are four possible access modifiers: public, protected, private, and default (also called package-private).

A method can also include the static keyword before or after the access modifier. This means that the method belongs to the class and not to the instances, and therefore, we can call the method without creating an instance of the class. Methods without the static keyword are known as instance methods and may only be invoked on an instance of the class.

Regarding performance, a static method will be loaded into memory just once – during class loading – and are thus more memory-efficient.

2.2. Return Type

Methods can return data to the code where they have been called from. A method can return a primitive value or an object reference, or it can return nothing if we use the void keyword as the return type.

Let's see an example of a void method:

public void printFullName(String firstName, String lastName) {
    System.out.println(firstName + " " + lastName);
}

If we declare a return type, then we have to specify a return statement in the method body. Once the return statement has been executed, the execution of the method body will be finished and if there are more statements, these won't be processed.

On the other hand, a void method doesn't return any value and, thus, does not have a return statement.

2.3. Method Identifier

The method identifier is the name we assign to a method specification. It is a good practice to use an informative and descriptive name. It's worth mentioning that a method identifier can have at most 65536 characters (a long name though).

2.4. Parameter List

We can specify input values for a method in its parameter list, which is enclosed in parentheses. A method can have anywhere from 0 to 255 parameters that are delimited by commas. A parameter can be an object, a primitive or an enumeration. We can use Java annotations at the method parameter level (for example the Spring annotation @RequestParam).

2.5. Exception List

We can specify which exceptions are thrown by a method by using the throws clause. In the case of a checked exception, either we must enclose the code in try-catch clause or we must provide a throws clause in the method signature.

So, let's take a look at a more complex variant of our previous method, which throws a checked exception:

public void writeName(String name) throws IOException {
    PrintWriter out = new PrintWriter(new FileWriter("OutFile.txt"));
    out.println("Name: " + name);
    out.close();
}

2.6. Method Body

The last part of a Java method is the method body, which contains the logic we want to execute. In the method body, we can write as many lines of code as we want — or none at all in the case of static methods. If our method declares a return type, then the method body must contain a return statement.

3. Method Signature

As per its definition, a method signature is comprised of only two components — the method's name and parameter list.

So, let's write a simple method:

public String getName(String firstName, String lastName) {
  return firstName + " " + middleName + " " + lastName;
}

The signature of this method is getName(String firstName, String lastName).

The method identifier can be any identifier. However, if we follow common Java coding conventions, the method identifier should be a verb in lowercase that can be followed by adjectives and/or nouns.

4. Calling a Method

Now, let's explore how to call a method in Java. Following the previous example, let's suppose that those methods are enclosed in a Java class called PersonName:

public class PersonName {
  public String getName(String firstName, String lastName) {
    return firstName + " " + middleName + " " + lastName;
  }
}

Since our getName method is an instance method and not a static method, in order to call the method getName, we need to create an instance of the class PersonName:

PersonName personName = new PersonName();
String fullName = personName.getName("Alan", "Turing");

As we can see, we use the created object to call the getName method.

Finally, let's take a look at how to call a static method. In the case of a static method, we don't need a class instance to make the call. Instead, we invoke the method with its name prefixed by the class name.

Let's demonstrate using a variant of the previous example:

public class PersonName {
  public static String getName(String firstName, String lastName) {
    return firstName + " " + middleName + " " + lastName;
  }
}

In this case, the method call is:

String fullName = PersonName.getName("Alan", "Turing");

5. Method Overloading

Java allows us to have two or more methods with the same identifier but different parameter list — different method signatures. In this case, we say that the method is overloaded. Let's go with an example:

public String getName(String firstName, String lastName) {
  return getName(firstName, "", lastName);
}

public String getName(String firstName, String middleName, String lastName) {
  if (!middleName.isEqualsTo("")) {
    return firstName + " " + lastName;
  }
  return firstName + " " + middleName + " " + lastName;
}

Method overloading is useful for cases like the one in the example, where we can have a method implementing a simplified version of the same functionality.

Finally, a good design habit is to ensure that overloaded methods behave in a similar manner. Otherwise, the code will be confusing if a method with the same identifier behaves in a different way.

6. Conclusion

In this tutorial, we've explored the parts of Java syntax involved when specifying a method in Java.

In particular, we went through the access modifier, the return type, the method identifier, the parameter list, the exception list, and the method body. Then we saw the definition of the method signature, how to call a method, and how to overload a method.

As usual, the code seen here is available over on GitHub.

Java bottom

The early-bird price of the new Learn Spring Security OAuth course packages will increase by $50 on Wednesday:

>> CHECK OUT THE COURSE
Comments are closed on this article!