JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Lambda expression syntax example


In Java, anonymous inner classes provide a way to implement classes that may occur only once in an application. Lambda expressions address the bulkiness of anonymous inner classes by converting five lines of code into a single statement. This simple horizontal solution solves the "vertical problem" presented by inner classes.

A lambda expression is composed of three parts.

Argument List Arrow Token Body
(int x, int y) -> x + y

The body can be either single expression or block of statements. In the expression form, the body is simply evaluated and returned. In the block form, the body is evaluated like a method body and a return statement returns control to the caller of the anonymous method. The break and continue keywords are illegal at the top level, but are permitted within loops. If the body produces a result, every control path must return something or throw an exception.

Here are few example syntaxes:

Output:
(int x, int y) -> x + y

() -> 90

(String str) -> {System.out.println(str);}

The first expression takes two arguments called x, y, and returns sum of x, y.

The second expression takes no argument, and returns an integer 90.

The third expression takes String as an argument. It contains a block to print the string. This block of code is not returning nothing.

 Next Program >>

Java-8 Lambda expression examples

  1. Lambda expression syntax example
  2. Lambda example with single method interface implementation.
  3. Comparator example with Lambda implementation.
  4. How to return lambda as an object?
Knowledge Centre
What is java static import?
By using static imports, we can import the static members from a class rather than the classes from a given package. For example, Thread class has static sleep method, below example gives an idea:

import static java.lang.Thread;
public class MyStaticImportTest {
public static void main(String[] a) {
try{
sleep(100);
} catch(Exception ex){

}
}
}
Famous Quotations
It’s not that I’m so smart, it’s just that I stay with problems longer.
-- Albert Einstein

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2022 by Nataraja Gootooru. All Rights Reserved.