Compare commits

...
4 Commits
90 changed files with 1088 additions and 0 deletions
+8
View File
@@ -96,3 +96,11 @@ These modules keep only sources, a `run.sh` and their transcripts (`output/`). T
HTTP/3 was not spoken to a real HTTP/3 server (no UDP egress). JEP 522 was not benchmarked. JDK-8377013 could not be reproduced.
MIT licensed, see `LICENSE`.
## Java version guides
Modules for the Java 8 / 11 / 17 / 21 feature articles, one folder each, each with `src/`, `broken/`, `output/` and `run.sh`:
- `java8-features/` — see its README
- `java11-features/` — see its README
- `java17-features/` — see its README
- `java21-features/` — see its README
+13
View File
@@ -0,0 +1,13 @@
# java11-features — Java 11 features with examples
Companion code for the ankurm.com article **Java 11 Features with Examples (and What Changed from Java 8)**. The explanation lives in the article; this folder holds the runnable sources and the transcripts they produced. There is no `docs/` folder: the depth is inside the article itself.
```bash
JDK8=/path/to/jdk8 JDK11=/path/to/jdk11 ./run.sh # regenerates output/*.txt
```
- `src/` compiles and runs unchanged on the JDK named in each output header.
- `broken/` fails to compile on purpose; the compiler's own message is committed in `output/`.
- `output/` is real captured output, regenerated by `run.sh`.
Tested on: Temurin 1.8.0_504 and 11.0.32.1.
+8
View File
@@ -0,0 +1,8 @@
import javax.xml.bind.JAXBContext;
/** Compiles on 8, fails on 11: JEP 320 removed the Java EE modules (java.xml.bind and friends). */
public class JaxbRemoved {
public static void main(String[] args) throws Exception {
System.out.println(JAXBContext.class.getName());
}
}
@@ -0,0 +1,9 @@
import java.util.function.BiFunction;
/** Fails to compile on purpose: you cannot mix var and explicit types in one lambda's parameters. */
public class VarWithoutLambda {
public static void main(String[] args) {
BiFunction<Integer, Integer, Integer> f = (var a, Integer b) -> a + b;
System.out.println(f.apply(1, 2));
}
}
@@ -0,0 +1,7 @@
$ javac src/StringMethods.java && java StringMethods (11.0.32.1)
trim() length : 9
strip() length : 5
isBlank(" ") : true isEmpty: false
lines() : [a, b, c]
repeat(3) : ababab
stripLeading : [x ] stripTrailing: [ x]
+3
View File
@@ -0,0 +1,3 @@
$ javac src/FilesDemo.java && java FilesDemo (11.0.32.1)
read back : one|two|three
Path.of : a/b/c.txt
@@ -0,0 +1,4 @@
$ javac src/HttpClientDemo.java && java HttpClientDemo (11.0.32.1)
sync : 200 hello from server version=HTTP_1_1
header : X-Demo=yes
async : hello from server
+3
View File
@@ -0,0 +1,3 @@
$ javac src/VarLambda.java && java VarLambda (11.0.32.1)
(var a, var b) : 5
with annotation : x-y
@@ -0,0 +1,2 @@
$ java src/SingleFile.java (11.0.32.1)
launched from source, java.version=11.0.32.1
+4
View File
@@ -0,0 +1,4 @@
$ javac src/NestMates.java && java NestMates (11.0.32.1)
nest host : NestMates
inner can read : 42
access$ methods on outer: 0
@@ -0,0 +1,20 @@
$ javac broken/JaxbRemoved.java (1.8.0_504)
(compiled cleanly)
$ javac broken/JaxbRemoved.java (11.0.32.1)
broken/JaxbRemoved.java:1: error: package javax.xml.bind does not exist
import javax.xml.bind.JAXBContext;
^
broken/JaxbRemoved.java:6: error: cannot find symbol
System.out.println(JAXBContext.class.getName());
^
symbol: class JAXBContext
location: class JaxbRemoved
2 errors
$ javac broken/VarWithoutLambda.java (11.0.32.1)
broken/VarWithoutLambda.java:6: error: invalid lambda parameter declaration
BiFunction<Integer, Integer, Integer> f = (var a, Integer b) -> a + b;
^
(cannot mix 'var' and explicitly-typed parameters)
1 error
@@ -0,0 +1,33 @@
# trim vs strip on the same string, Java 8 has no strip(); the Java 8 compile of src/StringMethods.java:
$ javac src/StringMethods.java (1.8.0_504)
src/StringMethods.java:9: error: cannot find symbol
System.out.println("strip() length : " + padded.strip().length());
^
symbol: method strip()
location: variable padded of type String
src/StringMethods.java:10: error: cannot find symbol
System.out.println("isBlank(\" \") : " + " ".isBlank() + " isEmpty: " + " ".isEmpty());
^
symbol: method isBlank()
location: class String
src/StringMethods.java:11: error: cannot find symbol
System.out.println("lines() : " + "a\nb\r\nc".lines().collect(Collectors.toList()));
^
symbol: method lines()
location: class String
src/StringMethods.java:12: error: cannot find symbol
System.out.println("repeat(3) : " + "ab".repeat(3));
^
symbol: method repeat(int)
location: class String
src/StringMethods.java:13: error: cannot find symbol
System.out.println("stripLeading : [" + " x ".stripLeading() + "] stripTrailing: [" + " x ".stripTrailing() + "]");
^
symbol: method stripLeading()
location: class String
src/StringMethods.java:13: error: cannot find symbol
System.out.println("stripLeading : [" + " x ".stripLeading() + "] stripTrailing: [" + " x ".stripTrailing() + "]");
^
symbol: method stripTrailing()
location: class String
6 errors
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
# Java 11 features: every demo compiled and run on real JDKs; regenerates output/*.txt
# JDK8=/path JDK11=/path ./run.sh
set -uo pipefail
unset JAVA_TOOL_OPTIONS
HERE="$(cd "$(dirname "$0")" && pwd)"
JDK8="${JDK8:-/opt/jdks/jdk8}"; JDK11="${JDK11:-/opt/jdks/jdk11}"
OUT="$HERE/output"; mkdir -p "$OUT"; B="$(mktemp -d)"; trap 'rm -rf "$B"' EXIT
cd "$HERE"
ver() { "$1/bin/java" -version 2>&1 | sed -n 1p | sed 's/.*"\(.*\)".*/\1/'; }
cr() { local jdk="$1" src="$2" cls="$3" o; o="$(mktemp -d -p "$B")"
echo "\$ javac $src && java $cls ($(ver "$jdk"))"
"$jdk/bin/javac" -encoding UTF-8 -d "$o" "$src" 2>&1 | grep -v '^Note:'; "$jdk/bin/java" -cp "$o" "$cls" 2>&1; }
co() { local jdk="$1" src="$2" o; o="$(mktemp -d -p "$B")"
echo "\$ javac $src ($(ver "$jdk"))"; local r; r="$("$jdk/bin/javac" -encoding UTF-8 -d "$o" "$src" 2>&1)"; if [ -n "$r" ]; then echo "$r"; else echo "(compiled cleanly)"; fi; }
cr "$JDK11" src/StringMethods.java StringMethods > "$OUT/01-string-methods.txt"
cr "$JDK11" src/FilesDemo.java FilesDemo > "$OUT/02-files.txt"
cr "$JDK11" src/HttpClientDemo.java HttpClientDemo > "$OUT/03-http-client.txt"
cr "$JDK11" src/VarLambda.java VarLambda > "$OUT/04-var-lambda.txt"
{ echo "\$ java src/SingleFile.java ($(ver "$JDK11"))"; "$JDK11/bin/java" src/SingleFile.java 2>&1; } > "$OUT/05-single-file.txt"
cr "$JDK11" src/NestMates.java NestMates > "$OUT/06-nest-mates.txt"
{ co "$JDK8" broken/JaxbRemoved.java; echo; co "$JDK11" broken/JaxbRemoved.java; echo; co "$JDK11" broken/VarWithoutLambda.java; } > "$OUT/07-compile-errors.txt"
{ echo "# the Java 8 compile of src/StringMethods.java: these String methods do not exist on 8"; co "$JDK8" src/StringMethods.java; } > "$OUT/08-string-methods-on-8.txt"
exit 0
+13
View File
@@ -0,0 +1,13 @@
import java.nio.file.*;
/** Files.readString / writeString and Path.of, new in 11. */
public class FilesDemo {
public static void main(String[] args) throws Exception {
Path p = Files.createTempFile("demo", ".txt");
Files.writeString(p, "one\ntwo\nthree");
String s = Files.readString(p);
System.out.println("read back : " + s.replace("\n", "|"));
System.out.println("Path.of : " + Path.of("a", "b", "c.txt"));
Files.delete(p);
}
}
+30
View File
@@ -0,0 +1,30 @@
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.*;
import java.util.concurrent.CompletableFuture;
/** The standard java.net.http client (JEP 321): sync, async, against a local server so the output is stable. */
public class HttpClientDemo {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/hello", ex -> {
byte[] body = "hello from server".getBytes();
ex.getResponseHeaders().add("X-Demo", "yes");
ex.sendResponseHeaders(200, body.length);
ex.getResponseBody().write(body); ex.close();
});
server.start();
String url = "http://127.0.0.1:" + server.getAddress().getPort() + "/hello";
HttpClient client = HttpClient.newHttpClient();
HttpRequest req = HttpRequest.newBuilder(URI.create(url)).GET().build();
HttpResponse<String> r = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println("sync : " + r.statusCode() + " " + r.body() + " version=" + r.version());
System.out.println("header : X-Demo=" + r.headers().firstValue("X-Demo").orElse("?"));
CompletableFuture<String> f = client.sendAsync(req, HttpResponse.BodyHandlers.ofString()).thenApply(HttpResponse::body);
System.out.println("async : " + f.get());
server.stop(0);
}
}
+13
View File
@@ -0,0 +1,13 @@
import java.lang.reflect.Modifier;
/** JEP 181: nest-based access. Private members of nest mates no longer need synthetic accessor methods. */
public class NestMates {
private int secret = 42;
static class Inner { int peek(NestMates n) { return n.secret; } }
public static void main(String[] args) {
System.out.println("nest host : " + Inner.class.getNestHost().getSimpleName());
System.out.println("inner can read : " + new Inner().peek(new NestMates()));
long synthetic = java.util.Arrays.stream(NestMates.class.getDeclaredMethods()).filter(m -> m.getName().startsWith("access$")).count();
System.out.println("access$ methods on outer: " + synthetic);
}
}
+6
View File
@@ -0,0 +1,6 @@
/** Run directly with: java SingleFile.java (JEP 330, no javac step). */
public class SingleFile {
public static void main(String[] args) {
System.out.println("launched from source, java.version=" + System.getProperty("java.version"));
}
}
+15
View File
@@ -0,0 +1,15 @@
import java.util.stream.Collectors;
/** The String additions in Java 11: isBlank, lines, strip, repeat. */
public class StringMethods {
public static void main(String[] args) {
String em = String.valueOf((char) 0x2003); // EM SPACE: whitespace to strip(), not to trim()
String padded = em + " hello " + em;
System.out.println("trim() length : " + padded.trim().length());
System.out.println("strip() length : " + padded.strip().length());
System.out.println("isBlank(\" \") : " + " ".isBlank() + " isEmpty: " + " ".isEmpty());
System.out.println("lines() : " + "a\nb\r\nc".lines().collect(Collectors.toList()));
System.out.println("repeat(3) : " + "ab".repeat(3));
System.out.println("stripLeading : [" + " x ".stripLeading() + "] stripTrailing: [" + " x ".stripTrailing() + "]");
}
}
+15
View File
@@ -0,0 +1,15 @@
import java.util.function.BiFunction;
/** JEP 323: var in lambda parameters. The point is annotations, not brevity. */
public class VarLambda {
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(java.lang.annotation.ElementType.PARAMETER)
@interface NonNull {}
public static void main(String[] args) {
BiFunction<Integer, Integer, Integer> add = (var a, var b) -> a + b;
BiFunction<String, String, String> join = (@NonNull var a, @NonNull var b) -> a + "-" + b;
System.out.println("(var a, var b) : " + add.apply(2, 3));
System.out.println("with annotation : " + join.apply("x", "y"));
}
}
+13
View File
@@ -0,0 +1,13 @@
# java17-features — Java 17 features with examples
Companion code for the ankurm.com article **Java 17 Features with Examples: Records, Sealed Classes, Text Blocks, Switch Expressions**. The explanation lives in the article; this folder holds the runnable sources and the transcripts they produced. There is no `docs/` folder: the depth is inside the article itself.
```bash
JDK11=/path/to/jdk11 JDK17=/path/to/jdk17 ./run.sh # regenerates output/*.txt
```
- `src/` compiles and runs unchanged on the JDK named in each output header.
- `broken/` fails to compile on purpose; the compiler's own message is committed in `output/`.
- `output/` is real captured output, regenerated by `run.sh`.
Tested on: Temurin 17.0.20.1, plus 11.0.32.1 for the strong-encapsulation comparison.
@@ -0,0 +1,5 @@
/** Fails to compile on purpose: record fields are final. */
public class RecordFieldMutation {
record Point(int x, int y) { void move() { this.x = 10; } }
public static void main(String[] args) { }
}
@@ -0,0 +1,7 @@
/** Fails to compile on purpose: a class that is not in the permits list cannot extend a sealed type. */
public class SealedViolation {
sealed interface Shape permits Circle {}
record Circle(double r) implements Shape {}
record Triangle(double b, double h) implements Shape {}
public static void main(String[] args) { }
}
@@ -0,0 +1,5 @@
/** Fails on 17 without --enable-preview: pattern matching for switch is only a preview feature in 17 (JEP 406). */
public class SwitchPatternOn17 {
static String f(Object o) { return switch (o) { case String s -> "string"; default -> "other"; }; }
public static void main(String[] args) { System.out.println(f("x")); }
}
+6
View File
@@ -0,0 +1,6 @@
$ javac src/RecordsDemo.java && java RecordsDemo (17.0.20.1)
toString : Point[x=3, y=4]
equals : true hashCode equal: true
accessor : p.x() = 3, distance = 5.0
compact ctor : negative coordinate: -1,2
shallow : Team[name=core, members=[a, b]] <- the record's list changed after construction
+6
View File
@@ -0,0 +1,6 @@
$ javac src/SealedDemo.java && java SealedDemo (17.0.20.1)
Circle[r=1.0] area = 3.142
Square[side=2.0] area = 4.000
Rect[w=2.0, h=3.0] area = 6.000
permitted : [Circle, Square, Rect]
isSealed : true
@@ -0,0 +1,8 @@
$ javac src/TextBlocksDemo.java && java TextBlocksDemo (17.0.20.1)
{
"name": "Ankur",
"city": "Mumbai"
}
lines : 4
backslash-newline: joined on one line
formatted : Hello, reader!
@@ -0,0 +1,5 @@
$ javac src/SwitchExprDemo.java && java SwitchExprDemo (17.0.20.1)
MON -> 9 working hours
SAT -> 0 working hours
WED -> 8 working hours
old fall-through: one two
@@ -0,0 +1,6 @@
$ javac src/PatternInstanceofDemo.java && java PatternInstanceofDemo (17.0.20.1)
long string hello
other hi
int 42
Stream.toList : [1, 2, 3]
toList() result is unmodifiable
@@ -0,0 +1,2 @@
$ javac src/HelpfulNpeDemo.java && java HelpfulNpeDemo (17.0.20.1)
Cannot read field "city" because "u.address" is null
@@ -0,0 +1,13 @@
$ javac src/EncapsulationDemo.java && java EncapsulationDemo (11.0.32.1)
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by EncapsulationDemo (file:/…/) to field java.lang.String.value
WARNING: Please consider reporting this to the maintainers of EncapsulationDemo
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
read String.value: byte[]
$ javac src/EncapsulationDemo.java && java EncapsulationDemo (17.0.20.1)
java.lang.reflect.InaccessibleObjectException: Unable to make field private final byte[] java.lang.String.value accessible: module java.base does not "opens java.lang" to unnamed module @<hash>
$ java --add-opens java.base/java.lang=ALL-UNNAMED EncapsulationDemo (17.0.20.1)
read String.value: byte[]
@@ -0,0 +1,4 @@
$ javac src/RandomDemo.java && java RandomDemo (17.0.20.1)
L64X128MixRandom nextInt(100) x3: 98 1 80
ThreadLocalRandom implements RandomGenerator: true
algorithms >= 10: true
@@ -0,0 +1,18 @@
$ javac broken/SealedViolation.java (17.0.20.1)
broken/SealedViolation.java:5: error: class is not allowed to extend sealed class: Shape (as it is not listed in its permits clause)
record Triangle(double b, double h) implements Shape {}
^
1 error
$ javac broken/RecordFieldMutation.java (17.0.20.1)
broken/RecordFieldMutation.java:3: error: cannot assign a value to final variable x
record Point(int x, int y) { void move() { this.x = 10; } }
^
1 error
$ javac broken/SwitchPatternOn17.java (17.0.20.1)
broken/SwitchPatternOn17.java:3: error: patterns in switch statements are a preview feature and are disabled by default.
static String f(Object o) { return switch (o) { case String s -> "string"; default -> "other"; }; }
^
(use --enable-preview to enable patterns in switch statements)
1 error
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env bash
# Java 17 features: every demo compiled and run on a real JDK 17 (and 11 for the encapsulation comparison); regenerates output/*.txt
# JDK11=/path JDK17=/path ./run.sh
set -uo pipefail
unset JAVA_TOOL_OPTIONS
HERE="$(cd "$(dirname "$0")" && pwd)"
JDK11="${JDK11:-/opt/jdks/jdk11}"; JDK17="${JDK17:-/opt/jdks/jdk17}"
OUT="$HERE/output"; mkdir -p "$OUT"; B="$(mktemp -d)"; trap 'rm -rf "$B"' EXIT
cd "$HERE"
ver() { "$1/bin/java" -version 2>&1 | sed -n 1p | sed 's/.*"\(.*\)".*/\1/'; }
cr() { local jdk="$1" src="$2" cls="$3" o; o="$(mktemp -d -p "$B")"
echo "\$ javac $src && java $cls ($(ver "$jdk"))"
"$jdk/bin/javac" ${JFLAGS:-} -encoding UTF-8 -d "$o" "$src" 2>&1 | grep -v '^Note:'; "$jdk/bin/java" -cp "$o" "$cls" 2>&1; }
co() { local jdk="$1" src="$2" o; o="$(mktemp -d -p "$B")"
echo "\$ javac $src ($(ver "$jdk"))"; local r; r="$("$jdk/bin/javac" -encoding UTF-8 -d "$o" "$src" 2>&1)"; if [ -n "$r" ]; then echo "$r"; else echo "(compiled cleanly)"; fi; }
cr "$JDK17" src/RecordsDemo.java RecordsDemo > "$OUT/01-records.txt"
cr "$JDK17" src/SealedDemo.java SealedDemo > "$OUT/02-sealed.txt"
cr "$JDK17" src/TextBlocksDemo.java TextBlocksDemo > "$OUT/03-text-blocks.txt"
cr "$JDK17" src/SwitchExprDemo.java SwitchExprDemo > "$OUT/04-switch-expressions.txt"
cr "$JDK17" src/PatternInstanceofDemo.java PatternInstanceofDemo > "$OUT/05-instanceof-pattern.txt"
JFLAGS=-g cr "$JDK17" src/HelpfulNpeDemo.java HelpfulNpeDemo > "$OUT/06-helpful-npe.txt"
{ cr "$JDK11" src/EncapsulationDemo.java EncapsulationDemo; echo; cr "$JDK17" src/EncapsulationDemo.java EncapsulationDemo
o="$(mktemp -d -p "$B")"; "$JDK17/bin/javac" -d "$o" src/EncapsulationDemo.java
echo; echo "\$ java --add-opens java.base/java.lang=ALL-UNNAMED EncapsulationDemo ($(ver "$JDK17"))"
"$JDK17/bin/java" --add-opens java.base/java.lang=ALL-UNNAMED -cp "$o" EncapsulationDemo 2>&1; } | sed -E 's#\(file:[^)]*\)#(file:/…/)#; s#unnamed module @[0-9a-f]+#unnamed module @<hash>#' > "$OUT/07-strong-encapsulation.txt"
cr "$JDK17" src/RandomDemo.java RandomDemo > "$OUT/08-random-generator.txt"
{ co "$JDK17" broken/SealedViolation.java; echo; co "$JDK17" broken/RecordFieldMutation.java; echo; co "$JDK17" broken/SwitchPatternOn17.java; } > "$OUT/09-compile-errors.txt"
exit 0
@@ -0,0 +1,15 @@
import java.lang.reflect.Field;
/** JEP 403: strong encapsulation of JDK internals. Same code, different outcome on 11 and 17. */
public class EncapsulationDemo {
public static void main(String[] args) throws Exception {
Field f = String.class.getDeclaredField("value");
try {
f.setAccessible(true);
Object v = f.get("abc");
System.out.println("read String.value: " + v.getClass().getSimpleName());
} catch (RuntimeException e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
+10
View File
@@ -0,0 +1,10 @@
/** Helpful NullPointerException messages (JEP 358): on by default since 15. */
public class HelpfulNpeDemo {
static class Address { String city; }
static class User { Address address; }
public static void main(String[] args) {
User u = new User();
try { System.out.println(u.address.city.length()); }
catch (NullPointerException e) { System.out.println(e.getMessage()); }
}
}
@@ -0,0 +1,16 @@
/** Pattern matching for instanceof (final in 16, JEP 394) and Stream.toList() (16). */
public class PatternInstanceofDemo {
static String describe(Object o) {
if (o instanceof String s && s.length() > 3) return "long string " + s;
if (o instanceof Integer i) return "int " + (i + 1);
return "other " + o;
}
public static void main(String[] args) {
System.out.println(describe("hello"));
System.out.println(describe("hi"));
System.out.println(describe(41));
var list = java.util.stream.Stream.of(3, 1, 2).sorted().toList();
System.out.println("Stream.toList : " + list);
try { list.add(4); } catch (UnsupportedOperationException e) { System.out.println("toList() result is unmodifiable"); }
}
}
+12
View File
@@ -0,0 +1,12 @@
import java.util.random.RandomGenerator;
import java.util.random.RandomGeneratorFactory;
/** JEP 356: RandomGenerator interface and named algorithms. Seeded, so the output is stable. */
public class RandomDemo {
public static void main(String[] args) {
RandomGenerator g = RandomGeneratorFactory.of("L64X128MixRandom").create(42L);
System.out.println("L64X128MixRandom nextInt(100) x3: " + g.nextInt(100) + " " + g.nextInt(100) + " " + g.nextInt(100));
System.out.println("ThreadLocalRandom implements RandomGenerator: " + (java.util.concurrent.ThreadLocalRandom.current() instanceof RandomGenerator));
System.out.println("algorithms >= 10: " + (RandomGeneratorFactory.all().count() >= 10));
}
}
+21
View File
@@ -0,0 +1,21 @@
/** Records (final in 16, JEP 395): what the compiler generates, compact constructors, and the shallow-immutability caveat. */
public class RecordsDemo {
record Point(int x, int y) {
Point { if (x < 0 || y < 0) throw new IllegalArgumentException("negative coordinate: " + x + "," + y); }
double distance() { return Math.sqrt(x * x + y * y); }
}
record Team(String name, java.util.List<String> members) {}
public static void main(String[] args) {
Point p = new Point(3, 4);
System.out.println("toString : " + p);
System.out.println("equals : " + p.equals(new Point(3, 4)) + " hashCode equal: " + (p.hashCode() == new Point(3, 4).hashCode()));
System.out.println("accessor : p.x() = " + p.x() + ", distance = " + p.distance());
try { new Point(-1, 2); } catch (IllegalArgumentException e) { System.out.println("compact ctor : " + e.getMessage()); }
java.util.List<String> list = new java.util.ArrayList<>(java.util.List.of("a"));
Team t = new Team("core", list);
list.add("b");
System.out.println("shallow : " + t + " <- the record's list changed after construction");
}
}
+21
View File
@@ -0,0 +1,21 @@
/** Sealed classes (final in 17, JEP 409): the compiler knows every permitted subtype. */
public class SealedDemo {
sealed interface Shape permits Circle, Square, Rect {}
record Circle(double r) implements Shape {}
record Square(double side) implements Shape {}
record Rect(double w, double h) implements Shape {}
// On 17 the switch must still be an if-chain: pattern matching for switch is only a preview here (JEP 406)
static double area(Shape s) {
if (s instanceof Circle c) return Math.PI * c.r() * c.r();
if (s instanceof Square q) return q.side() * q.side();
if (s instanceof Rect r) return r.w() * r.h();
throw new AssertionError("unreachable for a sealed Shape");
}
public static void main(String[] args) {
for (Shape s : new Shape[] { new Circle(1), new Square(2), new Rect(2, 3) })
System.out.printf("%-26s area = %.3f%n", s, area(s));
System.out.println("permitted : " + java.util.Arrays.stream(Shape.class.getPermittedSubclasses()).map(Class::getSimpleName).toList());
System.out.println("isSealed : " + Shape.class.isSealed());
}
}
+20
View File
@@ -0,0 +1,20 @@
/** Switch expressions (final in 14, JEP 361): arrow form, no fall-through, yield, and exhaustiveness on enums. */
public class SwitchExprDemo {
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }
public static void main(String[] args) {
for (Day d : new Day[] { Day.MON, Day.SAT, Day.WED }) {
int len = switch (d) {
case SAT, SUN -> 0;
case MON, TUE, WED, THU, FRI -> {
int hours = d == Day.MON ? 9 : 8;
yield hours;
}
};
System.out.println(d + " -> " + len + " working hours");
}
// old style: forgetting break falls through
int n = 1; StringBuilder sb = new StringBuilder();
switch (n) { case 1: sb.append("one "); case 2: sb.append("two "); break; case 3: sb.append("three"); }
System.out.println("old fall-through: " + sb.toString().trim());
}
}
+19
View File
@@ -0,0 +1,19 @@
/** Text blocks (final in 15, JEP 378): indentation stripping, trailing-space and escape rules. */
public class TextBlocksDemo {
public static void main(String[] args) {
String json = """
{
"name": "Ankur",
"city": "Mumbai"
}
""";
System.out.print(json);
System.out.println("lines : " + json.lines().count());
String oneLine = """
joined \
on one line""";
System.out.println("backslash-newline: " + oneLine);
System.out.println("formatted : " + """
Hello, %s!""".formatted("reader"));
}
}
+13
View File
@@ -0,0 +1,13 @@
# java21-features — Java 21 features with examples
Companion code for the ankurm.com article **Java 21 Features with Examples: Virtual Threads, Record Patterns, Sequenced Collections**. The explanation lives in the article; this folder holds the runnable sources and the transcripts they produced. There is no `docs/` folder: the depth is inside the article itself.
```bash
JDK21=/path/to/jdk21 ./run.sh # regenerates output/*.txt
```
- `src/` compiles and runs unchanged on the JDK named in each output header.
- `broken/` fails to compile on purpose; the compiler's own message is committed in `output/`.
- `output/` is real captured output, regenerated by `run.sh`.
Tested on: OpenJDK 21.0.12.1 (the preview and incubator demos need --enable-preview / --add-modules, which run.sh passes).
@@ -0,0 +1,5 @@
/** Fails to compile on purpose: a more general pattern before a specific one makes the later case unreachable. */
public class DominatedCase {
static String f(Object o) { return switch (o) { case CharSequence cs -> "cs"; case String s -> "s"; default -> "d"; }; }
public static void main(String[] args) { }
}
@@ -0,0 +1,8 @@
/** Fails to compile on purpose: a pattern switch over a sealed type must cover every permitted subtype. */
public class NonExhaustive {
sealed interface S permits A, B {}
record A() implements S {}
record B() implements S {}
static String f(S s) { return switch (s) { case A a -> "a"; }; }
public static void main(String[] args) { }
}
@@ -0,0 +1,4 @@
/** Fails to compile on purpose: string templates are a preview feature in 21 and are off by default. */
public class PreviewWithoutFlag {
public static void main(String[] args) { String n = "x"; System.out.println(STR."hi \{n}"); }
}
@@ -0,0 +1,5 @@
$ javac src/VirtualThreadsDemo.java && java VirtualThreadsDemo (21.0.12.1)
tasks completed : 10000
finished in < 5s: true (10,000 x 1s sleeps)
isVirtual : true, daemon=true
platform isVirtual: false
@@ -0,0 +1,5 @@
$ javac src/RecordPatternsDemo.java && java RecordPatternsDemo (21.0.12.1)
line from (0,0) to (3,4) length^2=25
box of String hi
box of Integer 7
no match
@@ -0,0 +1,3 @@
$ javac src/PatternSwitchDemo.java && java PatternSwitchDemo (21.0.12.1)
big circle | circle | square 2.0 | rect 2.0x3.0
null handled in the switch | large int | int | string of 4 | other
@@ -0,0 +1,11 @@
$ javac src/SequencedCollectionsDemo.java && java SequencedCollectionsDemo (21.0.12.1)
getFirst/getLast: a c
reversed view : [c, b, a]
addFirst+removeLast: [z, a, b]
LinkedHashSet reversed: [3, 2, 1]
firstEntry/lastEntry : x=1 z=3
putFirst : {w=0, x=1, y=2, z=3}
reversed map : {z=3, y=2, x=1, w=0}
view sees add : [3, 2, 1]
immutable list : UnsupportedOperationException
HashSet : no getFirst (unordered)
+5
View File
@@ -0,0 +1,5 @@
$ javac src/KemDemo.java && java KemDemo (21.0.12.1)
algorithm : DHKEM
secrets equal : true
secret length : 32 bytes
ciphertext length: 32 bytes
@@ -0,0 +1,9 @@
$ javac src/GcNamesDemo.java && java -XX:+UseZGC GcNamesDemo (21.0.12.1)
gc bean : ZGC Cycles
gc bean : ZGC Pauses
$ javac src/GcNamesDemo.java && java -XX:+UseZGC -XX:+ZGenerational GcNamesDemo (21.0.12.1)
gc bean : ZGC Minor Cycles
gc bean : ZGC Minor Pauses
gc bean : ZGC Major Cycles
gc bean : ZGC Major Pauses
+6
View File
@@ -0,0 +1,6 @@
$ javac --add-modules jdk.incubator.vector src/VectorDemo.java && java --add-modules jdk.incubator.vector VectorDemo (21.0.12.1)
warning: using incubating module(s): jdk.incubator.vector
1 warning
WARNING: Using incubator modules: jdk.incubator.vector
vector == scalar: true
lanes >= 2 : true
@@ -0,0 +1,2 @@
$ javac --release 21 --enable-preview src/StringTemplatesPreview.java && java --enable-preview StringTemplatesPreview (21.0.12.1)
Hello Ankur, 3 + 4 = 7
@@ -0,0 +1,4 @@
$ javac --release 21 --enable-preview src/UnnamedPreview.java && java --enable-preview UnnamedPreview (21.0.12.1)
x only : 5
loop count : 3
caught, name not needed
@@ -0,0 +1,2 @@
$ java --enable-preview --source 21 src/UnnamedMainPreview.java (21.0.12.1)
no class, no static, no String[] args
@@ -0,0 +1,3 @@
$ javac --release 21 --enable-preview src/ScopedValuesPreview.java && java --enable-preview ScopedValuesPreview (21.0.12.1)
inside handler : user=ankur
outside : bound=false
@@ -0,0 +1,3 @@
$ javac --release 21 --enable-preview src/StructuredConcurrencyPreview.java && java --enable-preview StructuredConcurrencyPreview (21.0.12.1)
both subtasks : ankur / 42
failure shuts down siblings: java.lang.IllegalStateException: boom
+2
View File
@@ -0,0 +1,2 @@
$ javac --release 21 --enable-preview src/FfmPreview.java && java --enable-preview --enable-native-access=ALL-UNNAMED FfmPreview (21.0.12.1)
strlen("Hello Ankur") = 11
@@ -0,0 +1,18 @@
$ javac broken/PreviewWithoutFlag.java (21.0.12.1)
broken/PreviewWithoutFlag.java:3: error: string templates are a preview feature and are disabled by default.
public static void main(String[] args) { String n = "x"; System.out.println(STR."hi \{n}"); }
^
(use --enable-preview to enable string templates)
1 error
$ javac broken/NonExhaustive.java (21.0.12.1)
broken/NonExhaustive.java:6: error: the switch expression does not cover all possible input values
static String f(S s) { return switch (s) { case A a -> "a"; }; }
^
1 error
$ javac broken/DominatedCase.java (21.0.12.1)
broken/DominatedCase.java:3: error: this case label is dominated by a preceding case label
static String f(Object o) { return switch (o) { case CharSequence cs -> "cs"; case String s -> "s"; default -> "d"; }; }
^
1 error
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env bash
# Java 21 features: every demo compiled and run on a real JDK 21; regenerates output/*.txt
# JDK21=/path/to/jdk21 ./run.sh
set -uo pipefail
unset JAVA_TOOL_OPTIONS
HERE="$(cd "$(dirname "$0")" && pwd)"
JDK21="${JDK21:-/opt/jdks/jdk21}"
OUT="$HERE/output"; mkdir -p "$OUT"; B="$(mktemp -d)"; trap 'rm -rf "$B"' EXIT
cd "$HERE"
ver() { "$1/bin/java" -version 2>&1 | sed -n 1p | sed 's/.*"\(.*\)".*/\1/'; }
# cr FILE CLASS [javac flags...] -- [java flags...]
cr() { local src="$1" cls="$2"; shift 2; local jf=() rf=(); while [ $# -gt 0 ] && [ "$1" != "--" ]; do jf+=("$1"); shift; done; [ "${1:-}" = "--" ] && shift; rf=("$@")
local o; o="$(mktemp -d -p "$B")"
echo "\$ javac ${jf[*]:-} $src && java ${rf[*]:-} $cls ($(ver "$JDK21"))"
"$JDK21/bin/javac" "${jf[@]}" -encoding UTF-8 -d "$o" "$src" 2>&1 | grep -v -e '^Note:' ; "$JDK21/bin/java" "${rf[@]}" -cp "$o" "$cls" 2>&1; }
co() { local src="$1"; shift; local o; o="$(mktemp -d -p "$B")"
echo "\$ javac $* $src ($(ver "$JDK21"))"; local r; r="$("$JDK21/bin/javac" "$@" -encoding UTF-8 -d "$o" "$src" 2>&1 | grep -v -e '^Note:')"; if [ -n "$r" ]; then echo "$r"; else echo "(compiled cleanly)"; fi; }
PV=(--release 21 --enable-preview)
cr src/VirtualThreadsDemo.java VirtualThreadsDemo > "$OUT/01-virtual-threads.txt"
cr src/RecordPatternsDemo.java RecordPatternsDemo > "$OUT/02-record-patterns.txt"
cr src/PatternSwitchDemo.java PatternSwitchDemo > "$OUT/03-pattern-switch.txt"
cr src/SequencedCollectionsDemo.java SequencedCollectionsDemo > "$OUT/04-sequenced-collections.txt"
cr src/KemDemo.java KemDemo > "$OUT/05-kem.txt"
{ cr src/GcNamesDemo.java GcNamesDemo -- -XX:+UseZGC; echo; cr src/GcNamesDemo.java GcNamesDemo -- -XX:+UseZGC -XX:+ZGenerational; } > "$OUT/06-generational-zgc.txt"
cr src/VectorDemo.java VectorDemo --add-modules jdk.incubator.vector -- --add-modules jdk.incubator.vector > "$OUT/07-vector-api.txt"
cr src/StringTemplatesPreview.java StringTemplatesPreview "${PV[@]}" -- --enable-preview > "$OUT/08-string-templates.txt"
cr src/UnnamedPreview.java UnnamedPreview "${PV[@]}" -- --enable-preview > "$OUT/09-unnamed-patterns.txt"
{ echo "\$ java --enable-preview --source 21 src/UnnamedMainPreview.java ($(ver "$JDK21"))"; "$JDK21/bin/java" --enable-preview --source 21 src/UnnamedMainPreview.java 2>&1 | grep -v '^Note:'; } > "$OUT/10-unnamed-main.txt"
cr src/ScopedValuesPreview.java ScopedValuesPreview "${PV[@]}" -- --enable-preview > "$OUT/11-scoped-values.txt"
cr src/StructuredConcurrencyPreview.java StructuredConcurrencyPreview "${PV[@]}" -- --enable-preview > "$OUT/12-structured-concurrency.txt"
cr src/FfmPreview.java FfmPreview "${PV[@]}" -- --enable-preview --enable-native-access=ALL-UNNAMED > "$OUT/13-ffm.txt"
{ co broken/PreviewWithoutFlag.java; echo; co broken/NonExhaustive.java; echo; co broken/DominatedCase.java; } > "$OUT/14-compile-errors.txt"
exit 0
+16
View File
@@ -0,0 +1,16 @@
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
/** JEP 442 (third preview in 21): call C's strlen without JNI. Needs --enable-preview. */
public class FfmPreview {
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
MethodHandle strlen = linker.downcallHandle(linker.defaultLookup().find("strlen").orElseThrow(),
FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS));
try (Arena arena = Arena.ofConfined()) {
MemorySegment s = arena.allocateUtf8String("Hello Ankur");
long len = (long) strlen.invokeExact(s);
System.out.println("strlen(\"Hello Ankur\") = " + len);
}
}
}
+8
View File
@@ -0,0 +1,8 @@
import java.lang.management.*;
/** JEP 439 (final): Generational ZGC is opt-in on 21 with -XX:+ZGenerational. Prints the GC beans each mode registers. */
public class GcNamesDemo {
public static void main(String[] args) {
for (GarbageCollectorMXBean b : ManagementFactory.getGarbageCollectorMXBeans()) System.out.println("gc bean : " + b.getName());
}
}
+20
View File
@@ -0,0 +1,20 @@
import javax.crypto.*;
import java.security.*;
import java.util.Arrays;
/** JEP 452 (final): Key Encapsulation Mechanism API, with the DHKEM implementation that ships in 21. */
public class KemDemo {
public static void main(String[] args) throws Exception {
KeyPairGenerator g = KeyPairGenerator.getInstance("X25519");
KeyPair kp = g.generateKeyPair();
KEM kem = KEM.getInstance("DHKEM");
KEM.Encapsulator enc = kem.newEncapsulator(kp.getPublic());
KEM.Encapsulated e = enc.encapsulate();
SecretKey sender = e.key();
SecretKey receiver = kem.newDecapsulator(kp.getPrivate()).decapsulate(e.encapsulation());
System.out.println("algorithm : " + kem.getAlgorithm());
System.out.println("secrets equal : " + Arrays.equals(sender.getEncoded(), receiver.getEncoded()));
System.out.println("secret length : " + sender.getEncoded().length + " bytes");
System.out.println("ciphertext length: " + e.encapsulation().length + " bytes");
}
}
@@ -0,0 +1,29 @@
/** JEP 441 (final): patterns in switch, guards with `when`, case null, and exhaustiveness over a sealed type. */
public class PatternSwitchDemo {
sealed interface Shape permits Circle, Square, Rect {}
record Circle(double r) implements Shape {}
record Square(double side) implements Shape {}
record Rect(double w, double h) implements Shape {}
static String size(Shape s) {
return switch (s) { // no default: the compiler checks all three cases
case Circle c when c.r() > 10 -> "big circle";
case Circle c -> "circle";
case Square q -> "square " + q.side();
case Rect(double w, double h) -> "rect " + w + "x" + h;
};
}
static String any(Object o) {
return switch (o) {
case null -> "null handled in the switch";
case Integer i when i > 100 -> "large int";
case Integer i -> "int";
case String str -> "string of " + str.length();
default -> "other";
};
}
public static void main(String[] args) {
System.out.println(size(new Circle(11)) + " | " + size(new Circle(1)) + " | " + size(new Square(2)) + " | " + size(new Rect(2, 3)));
System.out.println(any(null) + " | " + any(500) + " | " + any(5) + " | " + any("abcd") + " | " + any(2.0));
}
}
@@ -0,0 +1,20 @@
/** JEP 440 (final): deconstruct records in instanceof and switch, nested. */
public class RecordPatternsDemo {
record Point(int x, int y) {}
record Line(Point from, Point to) {}
record Box<T>(T content) {}
static String describe(Object o) {
if (o instanceof Line(Point(var x1, var y1), Point(var x2, var y2)))
return "line from (" + x1 + "," + y1 + ") to (" + x2 + "," + y2 + ") length^2=" + ((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
if (o instanceof Box<?>(String s)) return "box of String " + s;
if (o instanceof Box<?>(Integer i)) return "box of Integer " + i;
return "no match";
}
public static void main(String[] args) {
System.out.println(describe(new Line(new Point(0, 0), new Point(3, 4))));
System.out.println(describe(new Box<>("hi")));
System.out.println(describe(new Box<>(7)));
System.out.println(describe(new Box<>(2.5)));
}
}
@@ -0,0 +1,9 @@
/** JEP 446 (preview in 21): ScopedValue binds a value for the dynamic extent of a call. Needs --enable-preview. */
public class ScopedValuesPreview {
static final ScopedValue<String> USER = ScopedValue.newInstance();
static void handler() { System.out.println("inside handler : user=" + USER.get()); }
public static void main(String[] args) {
ScopedValue.where(USER, "ankur").run(ScopedValuesPreview::handler);
System.out.println("outside : bound=" + USER.isBound());
}
}
@@ -0,0 +1,29 @@
import java.util.*;
/** JEP 431 (final): SequencedCollection, SequencedSet, SequencedMap. */
public class SequencedCollectionsDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<>(List.of("a", "b", "c"));
System.out.println("getFirst/getLast: " + list.getFirst() + " " + list.getLast());
System.out.println("reversed view : " + list.reversed());
list.addFirst("z"); list.removeLast();
System.out.println("addFirst+removeLast: " + list);
LinkedHashSet<Integer> set = new LinkedHashSet<>(List.of(1, 2, 3));
System.out.println("LinkedHashSet reversed: " + set.reversed());
LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
map.put("x", 1); map.put("y", 2); map.put("z", 3);
System.out.println("firstEntry/lastEntry : " + map.firstEntry() + " " + map.lastEntry());
map.putFirst("w", 0);
System.out.println("putFirst : " + map);
System.out.println("reversed map : " + map.reversed());
// reversed() is a view, not a copy
List<String> src = new ArrayList<>(List.of("1", "2")); List<String> rev = src.reversed(); src.add("3");
System.out.println("view sees add : " + rev);
try { List.of(1, 2).addFirst(0); } catch (UnsupportedOperationException e) { System.out.println("immutable list : UnsupportedOperationException"); }
try { new HashSet<>(List.of(1)).getClass().getMethod("getFirst"); } catch (NoSuchMethodException e) { System.out.println("HashSet : no getFirst (unordered)"); }
}
}
@@ -0,0 +1,7 @@
/** JEP 430 (preview in 21, withdrawn in later releases). Needs --enable-preview. */
public class StringTemplatesPreview {
public static void main(String[] args) {
String name = "Ankur"; int a = 3, b = 4;
System.out.println(STR."Hello \{name}, \{a} + \{b} = \{a + b}");
}
}
@@ -0,0 +1,20 @@
import java.util.concurrent.StructuredTaskScope;
/** JEP 453 (preview in 21): fork subtasks, join, and let the scope own their lifetime. Needs --enable-preview. */
public class StructuredConcurrencyPreview {
public static void main(String[] args) throws Exception {
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
var user = scope.fork(() -> { Thread.sleep(50); return "ankur"; });
var order = scope.fork(() -> { Thread.sleep(80); return 42; });
scope.join().throwIfFailed();
System.out.println("both subtasks : " + user.get() + " / " + order.get());
}
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
scope.fork(() -> { throw new IllegalStateException("boom"); });
scope.fork(() -> { Thread.sleep(5_000); return "never"; });
scope.join().throwIfFailed();
} catch (java.util.concurrent.ExecutionException e) {
System.out.println("failure shuts down siblings: " + e.getCause());
}
}
}
@@ -0,0 +1,4 @@
/** JEP 445 (preview in 21): an unnamed class with an instance main. Needs --enable-preview --source 21. */
void main() {
System.out.println("no class, no static, no String[] args");
}
+12
View File
@@ -0,0 +1,12 @@
/** JEP 443 (preview in 21): unnamed patterns and variables, `_`. Needs --enable-preview. */
public class UnnamedPreview {
record Point(int x, int y) {}
public static void main(String[] args) {
Object o = new Point(5, 9);
if (o instanceof Point(var x, _)) System.out.println("x only : " + x);
int total = 0;
for (var _ : java.util.List.of("a", "b", "c")) total++;
System.out.println("loop count : " + total);
try { Integer.parseInt("zz"); } catch (NumberFormatException _) { System.out.println("caught, name not needed"); }
}
}
+16
View File
@@ -0,0 +1,16 @@
import jdk.incubator.vector.*;
/** JEP 448 (sixth incubator): needs --add-modules jdk.incubator.vector. Result must equal the scalar loop. */
public class VectorDemo {
static final VectorSpecies<Integer> S = IntVector.SPECIES_PREFERRED;
public static void main(String[] args) {
int n = 1000; int[] a = new int[n], b = new int[n], c = new int[n], d = new int[n];
for (int i = 0; i < n; i++) { a[i] = i; b[i] = 2 * i; }
int i = 0;
for (; i < S.loopBound(n); i += S.length()) IntVector.fromArray(S, a, i).add(IntVector.fromArray(S, b, i)).intoArray(c, i);
for (; i < n; i++) c[i] = a[i] + b[i];
for (int k = 0; k < n; k++) d[k] = a[k] + b[k];
System.out.println("vector == scalar: " + java.util.Arrays.equals(c, d));
System.out.println("lanes >= 2 : " + (S.length() >= 2));
}
}
@@ -0,0 +1,22 @@
import java.time.Duration;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
/** JEP 444 (final): 10,000 blocking tasks on virtual threads. Timing is machine dependent, so only counts are asserted. */
public class VirtualThreadsDemo {
public static void main(String[] args) throws Exception {
AtomicInteger done = new AtomicInteger();
long t0 = System.nanoTime();
try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++) ex.submit(() -> { Thread.sleep(Duration.ofSeconds(1)); done.incrementAndGet(); return null; });
}
long ms = (System.nanoTime() - t0) / 1_000_000;
System.out.println("tasks completed : " + done.get());
System.out.println("finished in < 5s: " + (ms < 5_000) + " (10,000 x 1s sleeps)");
Thread v = Thread.ofVirtual().name("demo-vt").start(() -> System.out.println("isVirtual : " + Thread.currentThread().isVirtual() + ", daemon=" + Thread.currentThread().isDaemon()));
v.join();
Thread p = Thread.ofPlatform().name("demo-pt").start(() -> System.out.println("platform isVirtual: " + Thread.currentThread().isVirtual()));
p.join();
}
}
+13
View File
@@ -0,0 +1,13 @@
# java8-features — Java 8 features with examples
Companion code for the ankurm.com article **Java 8 Features with Examples: Lambdas, Streams, Optional, Default Methods and java.time**. The explanation lives in the article; this folder holds the runnable sources and the transcripts they produced. There is no `docs/` folder: the depth is inside the article itself.
```bash
JDK8=/path/to/jdk8 ./run.sh # regenerates output/*.txt
```
- `src/` compiles and runs unchanged on the JDK named in each output header.
- `broken/` fails to compile on purpose; the compiler's own message is committed in `output/`.
- `output/` is real captured output, regenerated by `run.sh`.
Tested on: Temurin 1.8.0_504 (JDK 8).
+11
View File
@@ -0,0 +1,11 @@
import java.util.function.Supplier;
/** Fails to compile on purpose: a lambda may only capture effectively final locals. */
public class CaptureError {
public static void main(String[] args) {
int counter = 0;
Supplier<Integer> s = () -> counter;
counter++;
System.out.println(s.get());
}
}
+7
View File
@@ -0,0 +1,7 @@
/** Fails to compile on purpose: two default methods with the same signature and no override. */
public class DiamondError {
interface A { default String move() { return "a"; } }
interface B { default String move() { return "b"; } }
static class C implements A, B { }
public static void main(String[] args) { System.out.println(new C().move()); }
}
+7
View File
@@ -0,0 +1,7 @@
$ javac src/LambdaDemo.java && java LambdaDemo (1.8.0_504)
anonymous class : [Zoya, Meera, Ankur, Bhaskar]
lambda : [Ankur, Bhaskar, Meera, Zoya]
method reference: [Ankur, Bhaskar, Meera, Zoya]
captured base : 15
lambda this : LambdaDemo
anonymous this : LambdaDemo$2
+8
View File
@@ -0,0 +1,8 @@
$ javac src/StreamsDemo.java && java StreamsDemo (1.8.0_504)
distinct+upper : [STREAM, LAMBDA, OPTIONAL, DEFAULT, TIME]
sum of lengths : 37
pipeline built, nothing printed yet
filtering stream
first match : stream
reuse : stream has already been operated upon or closed
groupingBy : {long=[stream, lambda, optional, default], short=[time]}
+8
View File
@@ -0,0 +1,8 @@
$ javac src/OptionalDemo.java && java OptionalDemo (1.8.0_504)
present : VALUE-1
absent : none
orElse (value present):
expensive() called
orElseGet (value present):
get() on empty : No value present
Optional.of(null): NullPointerException
@@ -0,0 +1,3 @@
$ javac src/DefaultMethodsDemo.java && java DefaultMethodsDemo (1.8.0_504)
diamond resolved: walk + swim
default + static: Hello, Ankur
+8
View File
@@ -0,0 +1,8 @@
$ javac src/TimeDemo.java && java TimeDemo (1.8.0_504)
plusMonths : 2026-11-20 (original still 2026-10-20)
end of month : 2026-02-28
days between : 292
Period : P6Y7M21D
Duration : PT2H15M
same instant NY : 2026-10-20 13:05 EDT
old Date month : new java.util.Date(126, 9, 20) -> month index 9 (October is 9)
@@ -0,0 +1,7 @@
$ javac src/FunctionalInterfacesDemo.java && java FunctionalInterfacesDemo (1.8.0_504)
andThen : 11
compose : 12
negate : true
Supplier : supplied
BiFunction : 7
UnaryOperator : OK
@@ -0,0 +1,11 @@
$ javac broken/CaptureError.java (1.8.0_504)
broken/CaptureError.java:7: error: local variables referenced from a lambda expression must be final or effectively final
Supplier<Integer> s = () -> counter;
^
1 error
$ javac broken/DiamondError.java (1.8.0_504)
broken/DiamondError.java:5: error: class C inherits unrelated defaults for move() from types A and B
static class C implements A, B { }
^
1 error
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
# Java 8 features: every demo compiled and run on a real JDK 8; regenerates output/*.txt
# JDK8=/path/to/jdk8 JDK21=/path/to/jdk21 ./run.sh
set -uo pipefail
unset JAVA_TOOL_OPTIONS
HERE="$(cd "$(dirname "$0")" && pwd)"
JDK8="${JDK8:-/opt/jdks/jdk8}"; JDK21="${JDK21:-}"
OUT="$HERE/output"; mkdir -p "$OUT"; B="$(mktemp -d)"; trap 'rm -rf "$B"' EXIT
cd "$HERE"
ver() { "$1/bin/java" -version 2>&1 | sed -n 1p | sed 's/.*"\(.*\)".*/\1/'; }
cr() { local jdk="$1" src="$2" cls="$3" o; o="$(mktemp -d -p "$B")"
echo "\$ javac $src && java $cls ($(ver "$jdk"))"
"$jdk/bin/javac" -d "$o" "$src" 2>&1 | grep -v '^Note:' ; "$jdk/bin/java" -cp "$o" "$cls" 2>&1; }
co() { local jdk="$1" src="$2" o; o="$(mktemp -d -p "$B")"
echo "\$ javac $src ($(ver "$jdk"))"; "$jdk/bin/javac" -d "$o" "$src" 2>&1; }
cr "$JDK8" src/LambdaDemo.java LambdaDemo > "$OUT/01-lambda.txt"
{ cr "$JDK8" src/StreamsDemo.java StreamsDemo; } > "$OUT/02-streams.txt"
cr "$JDK8" src/OptionalDemo.java OptionalDemo > "$OUT/03-optional.txt"
cr "$JDK8" src/DefaultMethodsDemo.java DefaultMethodsDemo > "$OUT/04-default-methods.txt"
cr "$JDK8" src/TimeDemo.java TimeDemo > "$OUT/05-java-time.txt"
cr "$JDK8" src/FunctionalInterfacesDemo.java FunctionalInterfacesDemo > "$OUT/06-functional-interfaces.txt"
{ co "$JDK8" broken/CaptureError.java; echo; co "$JDK8" broken/DiamondError.java; } > "$OUT/07-compile-errors.txt"
exit 0
@@ -0,0 +1,18 @@
/** Default and static interface methods, and the diamond that forces you to choose. */
public class DefaultMethodsDemo {
interface Walker { default String move() { return "walk"; } }
interface Swimmer { default String move() { return "swim"; } }
static class Duck implements Walker, Swimmer {
// without this override the class does not compile: "types Walker and Swimmer are incompatible"
public String move() { return Walker.super.move() + " + " + Swimmer.super.move(); }
}
interface Greeter {
String name();
default String greet() { return "Hello, " + name(); }
static Greeter of(String n) { return () -> n; }
}
public static void main(String[] args) {
System.out.println("diamond resolved: " + new Duck().move());
System.out.println("default + static: " + Greeter.of("Ankur").greet());
}
}
@@ -0,0 +1,19 @@
import java.util.function.*;
/** The core java.util.function interfaces and composition. */
public class FunctionalInterfacesDemo {
public static void main(String[] args) {
Function<Integer, Integer> doubler = x -> x * 2;
Function<Integer, Integer> plusOne = x -> x + 1;
System.out.println("andThen : " + doubler.andThen(plusOne).apply(5));
System.out.println("compose : " + doubler.compose(plusOne).apply(5));
Predicate<String> empty = String::isEmpty;
System.out.println("negate : " + empty.negate().test("abc"));
Supplier<String> s = () -> "supplied";
System.out.println("Supplier : " + s.get());
BiFunction<Integer, Integer, Integer> add = Integer::sum;
System.out.println("BiFunction : " + add.apply(3, 4));
UnaryOperator<String> up = String::toUpperCase;
System.out.println("UnaryOperator : " + up.apply("ok"));
}
}
+38
View File
@@ -0,0 +1,38 @@
import java.util.*;
import java.util.function.*;
/** Lambdas: the old anonymous-class way, the lambda way, a method reference, and what "effectively final" means. */
public class LambdaDemo {
public static void main(String[] args) {
List<String> names = Arrays.asList("Meera", "Ankur", "Zoya", "Bhaskar");
// Java 7 style
Collections.sort(names, new Comparator<String>() {
@Override public int compare(String a, String b) { return a.length() - b.length(); }
});
System.out.println("anonymous class : " + names);
// Java 8 lambda, then a method reference
names.sort((a, b) -> a.compareTo(b));
System.out.println("lambda : " + names);
names.sort(String::compareToIgnoreCase);
System.out.println("method reference: " + names);
// capture: the local variable must be effectively final
int base = 10;
Function<Integer, Integer> addBase = x -> x + base;
System.out.println("captured base : " + addBase.apply(5));
// 'this' inside a lambda is the enclosing object, not the lambda
new LambdaDemo().thisDemo();
}
void thisDemo() {
Runnable lambda = () -> System.out.println("lambda this : " + this.getClass().getSimpleName());
Runnable anon = new Runnable() {
public void run() { System.out.println("anonymous this : " + this.getClass().getName()); }
};
lambda.run();
anon.run();
}
}
+20
View File
@@ -0,0 +1,20 @@
import java.util.*;
/** Optional: the null-chain it replaces, map/orElse, and the orElse vs orElseGet trap. */
public class OptionalDemo {
static String lookup(String key) { return "k1".equals(key) ? "value-1" : null; }
static String expensive() { System.out.println(" expensive() called"); return "fallback"; }
public static void main(String[] args) {
System.out.println("present : " + Optional.ofNullable(lookup("k1")).map(String::toUpperCase).orElse("none"));
System.out.println("absent : " + Optional.ofNullable(lookup("k2")).map(String::toUpperCase).orElse("none"));
System.out.println("orElse (value present):");
Optional.of("x").orElse(expensive());
System.out.println("orElseGet (value present):");
Optional.of("x").orElseGet(OptionalDemo::expensive);
try { Optional.empty().get(); } catch (NoSuchElementException e) { System.out.println("get() on empty : " + e.getMessage()); }
try { Optional.of(null); } catch (NullPointerException e) { System.out.println("Optional.of(null): NullPointerException"); }
}
}
+26
View File
@@ -0,0 +1,26 @@
import java.util.*;
import java.util.stream.*;
/** Streams: filter/map/collect, laziness, groupingBy, and why a stream cannot be reused. */
public class StreamsDemo {
public static void main(String[] args) {
List<String> words = Arrays.asList("stream", "lambda", "optional", "default", "time", "stream");
System.out.println("distinct+upper : " + words.stream().distinct().map(String::toUpperCase).collect(Collectors.toList()));
System.out.println("sum of lengths : " + words.stream().mapToInt(String::length).sum());
// laziness: nothing runs until the terminal operation
Stream<String> lazy = words.stream().filter(w -> { System.out.println(" filtering " + w); return w.length() > 5; });
System.out.println("pipeline built, nothing printed yet");
System.out.println("first match : " + lazy.findFirst().get());
// reuse is an error
Stream<String> once = words.stream();
once.count();
try { once.count(); } catch (IllegalStateException e) { System.out.println("reuse : " + e.getMessage()); }
Map<String, List<String>> byLen = words.stream().distinct().collect(Collectors.groupingBy(w -> w.length() > 5 ? "long" : "short"));
System.out.println("groupingBy : " + new TreeMap<>(byLen));
}
}
+18
View File
@@ -0,0 +1,18 @@
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
/** java.time: immutable value types, zones, Period vs Duration, and the old Date month trap. */
public class TimeDemo {
public static void main(String[] args) {
LocalDate d = LocalDate.of(2026, 10, 20);
System.out.println("plusMonths : " + d.plusMonths(1) + " (original still " + d + ")");
System.out.println("end of month : " + LocalDate.of(2026, 1, 31).plusMonths(1));
System.out.println("days between : " + ChronoUnit.DAYS.between(LocalDate.of(2026, 1, 1), d));
System.out.println("Period : " + Period.between(LocalDate.of(2020, 2, 29), d));
System.out.println("Duration : " + Duration.ofMinutes(135));
ZonedDateTime mumbai = ZonedDateTime.of(2026, 10, 20, 22, 35, 0, 0, ZoneId.of("Asia/Kolkata"));
System.out.println("same instant NY : " + mumbai.withZoneSameInstant(ZoneId.of("America/New_York")).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm z")));
System.out.println("old Date month : new java.util.Date(126, 9, 20) -> month index " + new java.util.Date(126, 9, 20).getMonth() + " (October is 9)");
}
}