Function pointers in Java
java 8object oriented programmingprogramming
From Java 8 onwards, the lambda expression is introduced which acts as function pointers.
Lambda expressions are introduced in Java 8 and are touted to be the biggest feature of Java 8. Lambda expression facilitates functional programming and simplifies the development a lot.
语法
A lambda expression is characterized by the following syntax.
parameter -> expression body
Following are the important characteristics of a lambda expression.
- Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.
- Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
- Optional curly braces − No need to use curly braces in expression body if the body contains a single statement.
- Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value.
Lambda Expressions Example
Create the following Java program using any editor of your choice in, say, C:\> JAVA.
Java8Tester.java
public class Java8Tester { public static void main(String args[]) { Java8Tester tester = new Java8Tester(); //带有类型声明 MathOperation addition = (int a, int b) -> a + b; //不带有类型声明 MathOperation subtraction = (a, b) -> a - b; //带有 return 语句和花括号 MathOperation multiplication = (int a, int b) -> { return a * b; }; //不带有 return 语句和花括号 MathOperation division = (int a, int b) -> a / b; System.out.println("10 + 5 = " + tester.operate(10, 5, 加法)); System.out.println("10 - 5 = " + tester.operate(10, 5, 减法)); System.out.println("10 x 5 = " + tester.operate(10, 5, 乘法)); System.out.println("10 / 5 = " + tester.operate(10, 5, 除法)); //不带括号 GreetingServicegreetService1 = message -> System.out.println("Hello" + message); //带括号 GreetingServicegreetService2 = (message) ->; System.out.println("Hello " + message); greetService1.sayMessage("Mahesh"); greetService2.sayMessage("Suresh"); } interface MathOperation { int operation(int a, int b); } interface GreetingService { void sayMessage(String message); } private int operate(int a, int b, MathOperation mathOperation) { return mathOperation.operation(a, b); } }
验证结果
使用 javac 编译器编译类,如下所示 −
C:\JAVA>javac Java8Tester.java
现在运行 Java8Tester,如下所示 −
C:\JAVA>java Java8Tester
它应该产生以下输出 −
10 + 5 = 15 10 - 5 = 5 10 x 5 = 50 10 / 5 = 2 Hello Mahesh Hello Suresh