How do I use a method reference in Java?

A method reference lets you use an existing method as the implementation of a functional interface. It can make a lambda expression shorter when the lambda only calls that method.

In this example, you will use a method reference to print each language in a list.

Source code

Save the following code as MethodReferenceExample.java:

import java.util.List;

public class MethodReferenceExample {
    void main() {
        List<String> languages = List.of(
                "Java", "Python", "JavaScript");

        languages.forEach(IO::println);
    }
}

Explanation

The example creates a list containing three language names:

List<String> languages = List.of(
        "Java", "Python", "JavaScript");

The forEach() method performs an action for each element in the list:

languages.forEach(IO::println);

It accepts a Consumer, a functional interface whose abstract method takes one argument and returns no value.

Referring to an existing method

The expression IO::println is a reference to the static println() method in java.lang.IO.

The double colon (::) separates the class name from the method name. The method reference does not call the method immediately. It supplies the action that forEach() invokes for each element.

This method reference can replace the following lambda expression:

languages.forEach(language -> IO.println(language));

Both versions print each language on a separate line, in list order.

Matching the functional interface

For this list, forEach() needs an action that accepts a string and returns no value.

IO.println(Object) is compatible because it accepts a String as an Object and returns void.

You do not add parentheses after the method name in a method reference:

IO::println

Parentheses belong to a method call, such as:

IO.println("Java");

Run the example

Compile and run the file:

javac MethodReferenceExample.java
java MethodReferenceExample

Output

Java
Python
JavaScript

Use a method reference when an existing method already performs the required action. Keep a lambda expression when you need additional logic, such as adding a prefix before printing each value.

How do I write a lambda expression in Java?

A lambda expression provides a concise implementation of a functional interface. A functional interface has one abstract method.

In this example, you will use a lambda expression to greet someone by name.

Source code

Save the following code as LambdaExample.java:

public class LambdaExample {
    void main() {
        Greeting greeting = name -> "Hello, " + name + "!";

        IO.println(greeting.greet("Alice"));
        IO.println(greeting.greet("Bob"));
    }
}

@FunctionalInterface
interface Greeting {
    String greet(String name);
}

Explanation

The Greeting interface declares one abstract method:

@FunctionalInterface
interface Greeting {
    String greet(String name);
}

The method accepts a name and returns a greeting.

The @FunctionalInterface annotation lets the compiler check that the interface meets the requirements of a functional interface.

Creating the lambda expression

The following statement assigns a lambda expression to a Greeting variable:

Greeting greeting = name -> "Hello, " + name + "!";

Each part has a purpose:

Part Purpose
name Receives the method argument
-> Separates the parameter from the body
"Hello, " + name + "!" Produces the returned value

The compiler knows that name is a String because the greet() method declares a String parameter.

For a single parameter with an inferred type, parentheses are optional. You can also write:

Greeting greeting = (name) -> "Hello, " + name + "!";

Returning a value

This lambda has an expression body:

name -> "Hello, " + name + "!"

The expression’s result is returned automatically. You do not need braces or a return statement.

If you use a block body instead, you must return the value explicitly:

Greeting greeting = name -> {
    return "Hello, " + name + "!";
};

Both forms provide the same behavior.

Calling the implementation

Call the interface method through the variable:

greeting.greet("Alice")

This passes "Alice" to the lambda and returns "Hello, Alice!". The program then prints the returned string using IO.println().

Run the example

Compile and run the file:

javac LambdaExample.java
java LambdaExample

Output

Hello, Alice!
Hello, Bob!

A lambda expression needs a target functional interface, such as Greeting in this example. You can also use lambdas with standard functional interfaces from java.util.function, including Predicate, Function, and Consumer.

How do I create a generic method in Java?

A generic method uses a type parameter to work with different reference types. This lets you reuse the same method without writing a separate version for each type.

In this example, you will create a method that prints the elements of an array. The same method will handle arrays of strings and integers.

Source code

Save the following code as GenericMethodExample.java:

public class GenericMethodExample {
    void main() {
        String[] languages = {"Java", "Python", "JavaScript"};
        Integer[] numbers = {10, 20, 30};

        IO.println("Languages:");
        printElements(languages);

        IO.println();
        IO.println("Numbers:");
        printElements(numbers);
    }

    <T> void printElements(T[] elements) {
        for (T element : elements) {
            IO.println(element);
        }
    }
}

Explanation

The printElements() method declares a type parameter named T:

<T> void printElements(T[] elements) {
    for (T element : elements) {
        IO.println(element);
    }
}

The <T> declaration appears before the return type, void. It makes T available as a type within the method declaration and body.

Each part has a purpose:

Part Purpose
<T> Declares the type parameter
void Indicates that the method does not return a value
T[] elements Accepts an array whose element type is T
T element Holds each element during iteration

T is a conventional name. You can use a more descriptive name when it makes the code easier to understand.

Calling the method with different types

The first call passes an array of strings:

String[] languages = {"Java", "Python", "JavaScript"};
printElements(languages);

The compiler infers T as String for this call.

The second call passes an array of integers:

Integer[] numbers = {10, 20, 30};
printElements(numbers);

For this call, the compiler infers T as Integer.

You do not need to specify the type argument explicitly because the compiler can infer it from the array argument.

Using wrapper types

Java generic type arguments must be reference types. You cannot use a primitive type such as int as the type argument for T.

That is why this example uses Integer[] rather than int[]. Autoboxing converts the integer literals into Integer objects when the array is initialized.

Passing an int[] directly to this method would cause a compilation error.

Run the example

Compile and run the file:

javac GenericMethodExample.java
java GenericMethodExample

Output

Languages:
Java
Python
JavaScript

Numbers:
10
20
30

The type parameter belongs to the method, so the containing class does not need to be generic. Use a generic method when the same operation can work with multiple types while keeping compile-time type checking.

How do I create a custom exception in Java?

You can create a custom exception to describe a problem specific to your application. Give it a meaningful name so calling code can recognize and handle the problem.

In this example, you will create an InvalidAgeException and throw it when someone under 18 tries to register.

Source code

Save the following code as CustomExceptionExample.java:

public class CustomExceptionExample {
    void main() {
        try {
            register(16);
        } catch (InvalidAgeException exception) {
            IO.println("Registration failed: " + exception.getMessage());
        }

        IO.println("The program continues.");
    }

    void register(int age) throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException(
                    "You must be at least 18 years old.");
        }

        IO.println("Registration successful.");
    }
}

class InvalidAgeException extends Exception {
    InvalidAgeException(String message) {
        super(message);
    }
}

Explanation

The custom exception extends Exception:

class InvalidAgeException extends Exception {
    InvalidAgeException(String message) {
        super(message);
    }
}

This makes InvalidAgeException a checked exception. Code that calls a method declaring this exception must either catch it or declare that it can propagate it.

The constructor accepts a message and passes it to the superclass constructor:

super(message);

Calling code can retrieve that message using getMessage().

Declaring the exception

The register() method declares the exception using throws:

void register(int age) throws InvalidAgeException {

This declaration tells callers that the method may throw an InvalidAgeException.

Throwing the exception

The method checks whether the age meets the registration requirement:

if (age < 18) {
    throw new InvalidAgeException(
            "You must be at least 18 years old.");
}

The throw statement creates and throws the exception. Execution leaves the method immediately, so the success message is skipped.

Notice the difference between the two keywords:

Keyword Purpose
throw Throws a specific exception object
throws Declares exceptions that a method may propagate

Handling the exception

The calling code catches the custom exception:

try {
    register(16);
} catch (InvalidAgeException exception) {
    IO.println("Registration failed: " + exception.getMessage());
}

Since 16 is below the minimum age, the catch block prints the failure message.

Once the exception is handled, the program continues after the try-catch statement.

Run the example

Compile and run the file:

javac CustomExceptionExample.java
java CustomExceptionExample

Output

Registration failed: You must be at least 18 years old.
The program continues.

If you change the method call to register(20), the output becomes:

Registration successful.
The program continues.

Choosing an exception type

Extend Exception when you want callers to catch or declare the exception. Extend RuntimeException when you want an unchecked exception, which callers are not required to catch or declare.

Use a custom exception when its name gives callers useful information or lets them handle a specific failure separately. For a simple invalid argument, a standard exception such as IllegalArgumentException may be sufficient.

How do I handle an exception using try-catch in Java?

You can use a try-catch statement to handle an exception and provide a useful response when an operation fails.

In this example, you will try to convert text into an integer. If the text is not a valid integer, the program will display a message and continue running.

Source code

Save the following code as TryCatchExample.java:

public class TryCatchExample {
    void main() {
        String input = "twenty";

        try {
            int number = Integer.parseInt(input);
            IO.println("Parsed number: " + number);
        } catch (NumberFormatException exception) {
            IO.println("Cannot convert \"" + input + "\" to an integer.");
            IO.println("Please enter a whole number, such as 20.");
        }

        IO.println("The program continues.");
    }
}

Explanation

The variable input contains the text to convert:

String input = "twenty";

The try block contains the operation that may throw an exception:

try {
    int number = Integer.parseInt(input);
    IO.println("Parsed number: " + number);
}

Integer.parseInt() converts a valid integer string, such as "20", into an int.

If the text cannot be parsed as an int, the method throws a NumberFormatException. This also happens when the number is outside the range supported by int.

Catching the exception

The catch block handles NumberFormatException:

catch (NumberFormatException exception) {
    IO.println("Cannot convert \"" + input + "\" to an integer.");
    IO.println("Please enter a whole number, such as 20.");
}

Since "twenty" is not a valid integer string, execution moves from Integer.parseInt() to this block.

The remaining statement inside the try block is skipped, so "Parsed number: ..." is not printed.

The parameter exception refers to the exception object. This example provides its own message rather than displaying the exception’s technical details.

Continuing after the catch block

After the exception is handled, execution continues with the statement following the try-catch:

IO.println("The program continues.");

Catching an exception does not retry the failed operation automatically.

Run the example

Compile and run the file:

javac TryCatchExample.java
java TryCatchExample

Output

Cannot convert "twenty" to an integer.
Please enter a whole number, such as 20.
The program continues.

If you change input to "20":

String input = "20";

The conversion succeeds, the catch block is skipped, and the output becomes:

Parsed number: 20
The program continues.

Catch the specific exception you can handle. Here, NumberFormatException clearly identifies the expected conversion failure.