LAMBDA EXPRESSION
A lambda expression is a short block of code or an anonymous method (a function
without a name) that takes in parameters and returns a value. They are designed to be
a concise, inline way to write simple functions, typically used when you need to pass a
function as an argument to another method, such as in sorting or filtering operations.
[Link] +2
Lambda expressions generally follow a consistent basic structure across languages,
comprised of three parts:
1. Argument List: The input parameters the function accepts.
2. Arrow Token: A symbol (typically -> or => ) that separates the arguments from the
body.
3. Body: The expression or block of statements that defines the function's logic.
Oracle +4
Syntax and Examples (Java)
In Java, the syntax is defined as (parameter_list) -> {function_body} .
BeginnersBook
No parameters: Empty parentheses () are used.
java
() -> [Link]("Hello, World!");
One parameter: Parentheses can be omitted.
java
name -> [Link]("Hello, " + name);
Multiple parameters: Parameters are enclosed in parentheses and comma-separated.
java
(int x, int y) -> x + y; // returns the sum of x and y
Code block: For more complex logic, the body is enclosed in braces {} and may
require a return statement.
java
(int x, int y) -> {
int sum = x + y;
return sum;
};
Key Definition Points
Anonymous: Lambda expressions do not have a name, unlike regular methods or
functions.
Concise: They provide a short, horizontal solution for code that might otherwise require
several lines or a separate class.
Functional: They are particularly useful for functional programming concepts, allowing
behavior to be passed as data (method arguments).
Single Purpose: They are best suited for simple, "throwaway" functions used
immediately where they are defined.
METHOD REFERENCE
In Java, a method reference is a shorthand notation for a lambda expression that
simply calls an existing method. It uses the :: (double colon) operator to point to a
method by its name instead of invoking it.
GeeksforGeeks +3
General Syntax
java
ClassNameOrObject::methodName
Use code with caution.
The 4 Types with Examples
Type Syntax Example Lambda Equivalent
Static ClassName::methodNam Math::abs (n) -> [Link](n)
Method e
Instance object::methodName [Link]::printl (x) ->
Method of a n [Link](x
Specific )
Object
Instance ClassName::methodNam String::toUpperCas (s) ->
Method of e e [Link]()
an
Arbitrary
Object
Constructo ClassName::new ArrayList::new () -> new
r ArrayList()
Simple Code Example
This example shows how to print all elements in a list using
the [Link] object's println method.
WsCube Tech +1
java
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
List<String> names = [Link]("Alice", "Bob", "Charlie");
// 1. Using Lambda Expression
[Link](n -> [Link](n));
// 2. Using Method Reference (Cleaner)
[Link]([Link]::println);
}
}
Use code with caution.
Why use them?
Conciseness: It removes boilerplate code like parameters and arrows -> .
Readability: Directly shows which method is being used, making the code
more declarative.
Reusability: Reuses existing method implementations instead of defining new logic
inline.
FUNCTIONAL INTERFACE - JAVADOCS
In Java, a functional interface is an interface that contains exactly one abstract
method.
Scaler +1
Also known as Single Abstract Method (SAM) interfaces, they serve as the target
types for lambda expressions and method references.
DEV Community +1
Definition & Core Rules
Single Abstract Method: It must have only one method without an implementation.
Additional Methods: It can contain any number of default or static methods.
Object Class Methods: Overriding public methods
from [Link] (like equals() or toString() ) does not count toward the
single abstract method limit.
Annotation: Use @FunctionalInterface to let the compiler verify these rules.
Stack Overflow +5
Syntax
java
@FunctionalInterface
public interface InterfaceName {
// Exactly one abstract method
ReturnType methodName(Parameters);
// Optional: Any number of default/static methods
default void commonLogic() {
[Link]("Default behavior");
}
}
Use code with caution.
Common Built-in Examples
Java provides many predefined functional interfaces in
the [Link] package:
GeeksforGeeks +1
Interface Method Purpose Example
Predicate boolean test(T Checks a condition n -> n > 10
t)
Function<T, R apply(T t) Transforms input to s -> [Link]()
R> output
Consumer void accept(T Performs an action (no s ->
t) return) [Link](s)
Supplier T get() Provides a result (no () -> [Link]()
input)
Simple Code Example
This example demonstrates a custom functional interface used with a lambda
expression.
java
@FunctionalInterface
interface MathOperation {
int operate(int a, int b); // Single abstract method
}
public class Main {
public static void main(String[] args) {
// Implementation using Lambda
MathOperation addition = (a, b) -> a + b;
[Link]("Result: " + [Link](5, 3)); // Output: 8
}
}
ANNOTATIONS
In Java, annotations are a form of metadata that provide additional information about a
program without being part of the program's actual logic. They do not directly affect the
execution of the code but are used by the compiler, development tools, or the runtime
environment to process it.
Medium +3
Definition & Core Rules
Metadata: Annotations act as "tags" or "labels" for classes, methods, fields, and other
elements.
Symbol: Every annotation starts with the @ symbol.
Non-invasive: They do not change the behavior of the compiled program by
themselves.
Use Cases: Commonly used for compiler instructions (e.g., detecting errors), compile-
time processing (e.g., generating code), and runtime processing (e.g., dependency
injection in Spring).
GeeksforGeeks +6
Syntax
Annotations can be applied with or without parameters:
Marker Annotation (No elements):
java
@AnnotationName
Use code with caution.
Single-Value Annotation:
java
@AnnotationName("value")
Use code with caution.
Multi-Value Annotation:
java
@AnnotationName(key1 = "value1", key2 = 10)
Use code with caution.
Predefined Examples
Java provides several built-in annotations in the [Link] package:
Oracle +1
Annotation Purpose
@Override Tells the compiler a method is intended to override a superclass method.
@Deprecated Marks an element as outdated; the compiler will issue a warning if it is used.
@SuppressWarnings Instructs the compiler to ignore specific warnings (e.g., "unchecked").
Simple Code Example
This example demonstrates how @Override helps catch errors at compile-time:
W3Schools
java
class Animal {
void makeSound() {
[Link]("Generic sound");
}
}
class Dog extends Animal {
// Correctly informs the compiler this overrides the parent method
@Override
void makeSound() {
[Link]("Bark");
}
// If you had a typo like "makesound()", @Override would cause a compiler
error
}
Use code with caution.
Custom Annotations
You can define your own using the @interface keyword:
GeeksforGeeks +1
java
import [Link].*;
@Retention([Link]) // Available at runtime
@Target([Link]) // Can only be used on methods
public @interface MyTest {
String value() default "No description";
}
ASSERTION
In Java, an assertion is a debugging tool used to test your assumptions about the
program's state. It is a statement that you believe will always be true at a specific point
in the code.
GeeksforGeeks +4
Definition & Core Rules
Purpose: Used to catch logical errors during development (e.g., verifying an internal
variable is never negative).
Runtime Behavior: Assertions are disabled by default. They must be explicitly
enabled using the -ea flag; otherwise, they are ignored by the JVM with zero
performance penalty.
Failure Outcome: If an enabled assertion fails (evaluates to false ), the system throws
an AssertionError and typically terminates the program.
Key Constraint: Never use assertions for public method argument validation or any
logic required for the program to function, as they may be turned off in production.
TheServerSide +5
Syntax
There are two forms of the assert statement:
[Link] +1
1. Simple Form:
java
assert condition;
Use code with caution.
2. Message Form (Recommended for easier debugging):
java
assert condition : "Custom error message if false";
Use code with caution.
Simple Code Example
This example demonstrates a "postcondition" check where we assume a calculation
result must be positive.
WsCube Tech +1
java
public class Main {
public static void main(String[] args) {
int age = -5; // This is a bug in our logic
// If enabled, this throws an AssertionError
assert age >= 0 : "Age cannot be negative! Found: " + age;
[Link]("Age is: " + age);
}
}
Use code with caution.
How to Run with Assertions
Because they are off by default, you must use the Enable Assertions flag in your
terminal or IDE:
University of San Francisco +1
Terminal: java -ea Main
IntelliJ/Eclipse: Add -ea to the VM Arguments in your Run Configuration.