? Java Version Features (8–21) – Quick PDF Guide ??
? Java Version Features (8–21) – Quick PDF Guide ??
● Lambda Expressions:
Enable functional programming
by writing
functions inline.
●
Stream API:
Process collections in a functional
style.
●
Functional Interfaces:
Interfaces with a single
abstract method.
●
Optional
: Avoid NullPointerException.
●
Default Methods
: Add default implementations in
interfaces.
●
Date and Time API
: Improved handling of dates and
times.
●
Method References
: Simplified syntax for calling
methods.
Lambda Expression:
ambda expression is an Anonymous function.
L
1.Not having any name, Not having any return type and Not having any
access modifier.
yntax:
S
(parameters) -> { body }
A Functional Interface
has only one abstract method.
Lambda
expressions are used to implement them.
Type of Stream:
ParallelStream():
It Allows processing of data concurrently
using
ultiple threads. ParallelStream runs with the help of Fork Join
m
Pool which divides the data into chunks and processes them
.
independently and then combines into the result
Function<T, R>
Consumer<T>
Supplier<T>
Predicate<T>
• BiFunction<T, U, R>:
Takes two inputs and returns
a result.
•
BiConsumer<T, U>:
Takes two inputs and returns nothing.
•
BiPredicate<T, U>:
Takes two inputs and returns
a boolean.
•
UnaryOperator<T>:
A Function where input and output
are the same
type.
•
BinaryOperator<T>:
A BiFunction where input and
output are the
same type.
Evolution of Java Interfaces (Before and After Java 8)
efore Java 8
B
• Interfaces were 100% abstract and could only contain abstract
methods and constants.
• Adding a new method to an interface broke all implementing
classes.
xample:
E
interface Vehicle { void start(); }
Java 8 Enhancements
o allow interface evolution without breaking existing code, Java 8
T
introduced:
efault Methods
D
• Provide default implementation inside the interface without
breaking the existing code or functionality.
• If a class implements the default method then the class can change
the Implementation of the default method if needed.
Analogy:
It’s like adding a new feature to a smartphone
via software
update, without forcing every phone to be rebuilt
xample:
E
default void stop() { System.out.println("Stopped"); }
tatic Methods
S
• Utility methods that belong to the interface itself (not
instance).
•
Why:
Static methods in interfaces were introduced
in Java 8 to
allow us to write utility/helper methods directly inside the
interface. This keeps related code in one place, making the
interface more self-contained and easier to use. It avoids the need
for separate utility classes and improves code organization.
xample:
E
static int square(int x) { return x * x; }
Why These Changes?
• Enable backward-compatible interface evolution.
• Avoid breaking existing code when APIs are updated.
• Make interfaces more powerful with shared utility methods and
behavior.
Optional
Class:
ptional<T>
O class introduced in Java 8 to handle null
values safely.
OR To avoid
NullPointerExceptions
.
It either contains a non-null value or is empty.
System.out.println("*************************************");
1.
Static Method Reference
👉
Syntax:ClassName::staticMethod
👉
Used when you want to refer to astatic method
.
📌
Example:
Math::sqrt
2.
Instance Method Reference of a Particular Object
👉
Syntax:object::instanceMethod
👉
Used when you already have an object and want to call its
method.
📌
Example:
System.out::println
3.
Instance Method Reference of an Arbitrary Object of a Class
👉
Syntax:ClassName::instanceMethod
👉
Used when method will be called oneach object
in a
collection (like in
forEach
).
📌
Example:
String::toLowerCase
4.
Constructor Reference
👉
Syntax:ClassName::new
👉
Used when you want to refer to a
constructor
to
create
objects.
📌
Example:
ArrayList::new
✅ Date and Time API
🔹 Why Java 8 introduced a new Date and Time API?
●
The old API (java.util.Date, Calendar)
was:
○ Mutable
– not thread-safe.
○ Poorly designed
– confusing method names and behaviors.
○
No clear time zone or formatting support
.
🔄
Java 8 introduced the newjava.time
package to fix all these problems
with a
clean, immutable, thread-safe design
.
1.
LocalDate
●
Represents a date (yyyy-MM-dd) without time or timezone.
mport java.time.LocalDate;
i
public class Demo {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(2000,05,29);
System.out.println("Today: " + today);
System.out.println("Birthday: " + birthday);
}
}
2.
LocalTime
●
Represents only time (hh:mm:ss).
mport java.time.LocalTime;
i
public class Demo {
public static void main(String[] args) {
LocalTime now = LocalTime.now();
System.out.println("Current Time: " + now);
}
}
3.
LocalDateTime
●
Combines date + time but still no timezone.
mport java.time.LocalDateTime;
i
public class Demo {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println("Now: " + now);
}
}
4.
ZonedDateTime
●
Date and time with a timezone.
mport java.time.ZonedDateTime;
i
public class Demo {
public static void main(String[] args) {
ZonedDateTime now = ZonedDateTime.now();
System.out.println("Zoned DateTime: " + now);
}
}
5.
Period
and
Duration
● Period
is used for date-based amounts (e.g., 2 years, 3 months).
●
Duration
is used for time-based amounts (e.g., 5 hours, 20 seconds).
mport java.time.LocalDate;
i
import java.time.Period;
public class Demo {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate futureDate = LocalDate.of(2025, 12, 25);
Period period = Period.between(today, futureDate);
System.out.println("Period: " + period.getYears() + " years, " + period.getMonths() +
" months");
}
}
● java.time
○ dates
○ times
○ Instants
○ durations
○ time-zones
○ periods
● Java.time.format
● Java.time.temporal
● java.time.zone
✅ Top Java 11 Features (Interview-Focused)
hat?
W You can now use
var
to declare lambda parameters (introduced in Java
10, enhanced in 11).
Why?
Useful for annotations or better readability.
✅Example:
✅Important ones:
● i sBlank()
→ Returns true if the string is empty or contains only
white spaces.
● lines()
→ Converts string into a stream of lines.
● strip()
→ Removes leading/trailing white spaces (Unicode-aware).
● stripLeading()
,
stripTrailing()
→ Removes whitespaces from start/end.
●
repeat(int count)
→ Repeats the string n times.
✅Examples:
🔹 3.Optional.isEmpty()
What?
Checks if an
Optional
is empty (instead of using
!isPresent()
).
✅Example:
✅Example:
✅Example:
ava Hello.java
j
(No need to compile with
javac
first!)
🔹 6. CollectiontoArray(IntFunction<T[]>)Improvement
Why?
Safer, cleaner way to convert to arrays.
✅Example:
ome APIs were removed or deprecated in Java 11 (not asked often, but worth
S
knowing):
●
Removed:
Java EE modules like
javax.xml.bind
,
javax.activation
●
Deprecated:
Nashorn JavaScript engine
var
in lambda etter
B (var x) -> x*x
readability/annotations
String
methods seful string handling
U " ".isBlank()
improvements
Optional.isEmpty()
Cleaner null handling
opt.isEmpty()
HttpClient
REST APIs in Java
ttpClient.newHttpClien
H
t()
un
R .java
without aves time for small/test
S java Hello.java
compile
code
oArray()
t ype-safe conversion to
T ist.toArray(String[]::
l
improvement
array
new)
✅ Java 17 Features
🔹 1. Sealed Classes
hat?
W Sealed classes restrict which other classes can extend or implement
them.
hy?
W To provide
better security and maintainability
by
restricting
inheritance
.
✅Example:
🧠
Think of it like: “Only selected children allowed to extend the
parent.”
What?
No need to cast after using
instanceof
.
Why?
Reduces boilerplate and improves readability.
Why?
Makes switch
shorter, safer, and expressive
.
✅Example:
What?
Multi-line strings using
"""
.
Why?
Clean, readable format for HTML, JSON, SQL, etc.
✅Example:
<html>
<body>Hello</body>
</html>
""";
What?
A compact way to create immutable data classes.
Why?
Avoids boilerplate for getters, constructors,
toString
, etc.
✅Example:
✅
String
.stripIndent()
Removes common indentation in multi-line strings.
✅Optional.ifPresentOrElse()
opt.ifPresentOrElse(
val -> System.out.println(val),
() -> System.out.println("No value")
);
✅Java 21 Features
1. Virtual Threads (Final) – JEP 444
● Allows creating thousands/millions of lightweight threads.
●
Great for high-concurrency tasks like web servers.
Thread.startVirtualThread(() -> {
System.out.println("Running in virtual thread: " +
Thread.currentThread());
});
●
Simplifies pattern matching with records.
●
Allows using
switch
with types and patterns, making it more powerful.
● New interfaces:
SequencedCollection
,
SequencedSet
,
SequencedMap
.
●
Maintains a
defined encounter order
for consistent element access.
Example:
o
T make string concatenation cleaner
To
avoid messy
+
operators
or
String.format()
calls