Java Methods

Java methods:

Methods are like classes. Some programming languages make a distinction between them, while others do not. Methods are reusable pieces of code.

public class Main{

public static void sayHello(String name){

System.out.printf(“Hello, %s!\n”, name);

}

public static void main(String[] args){

sayHello(“Alan”);

}

}

Java lambda expressions:

Here is a lambda expression example from my open source 2D game engine with keyboard movement:

debugModeButton.setOnAction(e -> {

debugMode = true;

System.out.println(“enabled debug mode”);

});

When you click on the debug button object (an instance of the Button class) in my game engine’s JavaFX GUI, the lambda expression enables the debug mode by changing a Boolean to true, which is checked with if/else statements in many places throughout the game engine.

Think of it as a function with no name, with no need to be invoked. The lambda expression is being passed as an argument to the setOnAction() method of the Button object. In other words, I’m giving an anonymous function to an event-handling function. The Oracle API documentation says setOnAction() takes an EventHandler<ActionEvent> argument. There’s another way to do it, with generics instead of lambda expressions, but that’s not relevant to this explanation of lambdas in Java.

← Previous | Next →

Java Topic List

Main Topic List

Leave a Reply

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