Phase 8
Java 11 LTS (with 9 & 10) • var, Unmodifiable Collections, String Suite & Files API
📂 Module 2_ Java LTS Features \ 01_Java11_Demos (and 9 & 10)
8.1 Local-Variable Type Inference (var) & Factory Methods for Collections
📖 Cay S. Horstmann • Core Java Volume I — Chapter 3, Section 3.4 ("Variables and Constants")
“In Java 10 and beyond, you do not need to declare the types of local variables if they can be inferred from the initial value. Simply use the keyword var instead of the type. Note that var can only be used with local variables inside methods. You cannot use it for instance variables or parameter types. Java remains a strongly typed language: the compiler infers the exact static type and bakes it into bytecode.”
-
Static Typing Guarantee
var is NOT dynamic typing: Unlike JavaScript
varor Python, Javavaris strictly evaluated at compile time.var x = 10; x = "hello";will NOT compile! -
Immutable Collections
Java 9 List.of(), Set.of(), Map.of(): Creates truly immutable collections. Attempting to add, remove, or modify elements throws
UnsupportedOperationException. Rejects null keys and values.
💡 Real-World Analogy: The Smart Label Maker
Imagine you place an Apple in an airtight transparent box.
• Old Java: You must write "THIS BOX CONTAINS A HONEYCRISP APPLE" on the label, even though everyone can clearly see the Honeycrisp Apple through the glass!
• Java var: You slap an automated barcode (
• Old Java: You must write "THIS BOX CONTAINS A HONEYCRISP APPLE" on the label, even though everyone can clearly see the Honeycrisp Apple through the glass!
• Java var: You slap an automated barcode (
var) on it. The scanning machine automatically inspects what is inside and stamps the exact label instantly.
⚡ Pro-Tip / Interview Memory Hook: Illegal Usages of var
var is ILLEGAL in:
1. Class fields (instance or static variables):
2. Method parameters or return types:
3. Uninitialized declarations:
4. Null initializers:
5. Lambda expressions without explicit casts:
1. Class fields (instance or static variables):
class A { var x = 10; } // ERROR
2. Method parameters or return types:
public var calculate(var a) // ERROR
3. Uninitialized declarations:
var x; // ERROR, compiler cannot infer type
4. Null initializers:
var x = null; // ERROR, null has no definite type
5. Lambda expressions without explicit casts:
var func = x -> x * 2; // ERROR
📂 Module 2_ Java LTS Features/.../Tester1002.java & Tester1005TakeDropWhile.java
package com.accenture.ltt.ten;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;
public class JavaTenElevenDemo {
public static void main(String[] args) {
// 1. Type inference for local variables (Java 10)
var count = 10; // inferred as int
var message = "Core Java 11"; // inferred as String
var items = List.of("A", "B", "C"); // inferred as List<String>
// 2. var is a reserved type name, NOT a keyword!
var var = 20; // Perfectly valid syntax!
// 3. Java 9 Stream additions: takeWhile & dropWhile
System.out.println("takeWhile < 4 (short-circuits immediately):");
IntStream.range(1, 10)
.takeWhile(i -> i < 4)
.forEach(System.out::print); // Prints: 123
System.out.println("
dropWhile < 4 (skips until predicate fails):");
IntStream.range(1, 10)
.dropWhile(i -> i < 4)
.forEach(System.out::print); // Prints: 456789
}
}
👁 Execution & Memory Breakdown • Java 11 Runtime Mechanics
Step 1 (strip vs trim):
strip() invokes Character.isWhitespace(codePoint) on each char code point, eliminating non-breaking and Unicode spaces where trim() silently fails.
Step 2 (Files.writeString): Directly maps memory byte buffers to the OS file channel using UTF-8 charset encoding by default, avoiding extra wrapper object allocations.
8.2 Java 11 String Suite (strip vs trim), Predicate.not() & Files.writeString()
📖 Cay S. Horstmann • Core Java Volume I — Chapter 3, Section 3.6 ("String Operations in Java 11")
“Java 11 brought substantial enhancements to the String class: isBlank, lines, repeat, and strip. The strip method is a Unicode-aware version of trim. Whereas trim only removes characters with code values $le$ U+0020, strip removes all Unicode whitespace characters as determined by Character.isWhitespace(int). Additionally, Files.readString and Files.writeString simplify file I/O for text files, eliminating the need for intermediate reader and writer wrappers.”
-
Unicode Whitespace Law
strip() vs trim():
trim()only strips ASCII space $le$ 32.strip()handles Japanese Ideographic Space (U+3000), non-breaking spaces, and tab spaces. -
Predicate.not()
Readable Method References: Eliminates ugly negative lambdas. Instead of
filter(s -> !s.isBlank()), writefilter(Predicate.not(String::isBlank)).
📂 Module 2_ Java LTS Features/.../Tester1005_String_Strip.java & File_Additions.java
package com.accenture.ltt.zeleven;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class Java11EnterpriseSuite {
public static void main(String[] args) throws Exception {
// 1. Unicode-Aware String Strip vs Trim
String messyText = " Mohpreet Singh ";
System.out.println("[" + messyText.strip() + "]"); // strips both ends
System.out.println("[" + messyText.stripLeading() + "]"); // strips start
System.out.println("[" + messyText.stripTrailing() + "]"); // strips end
System.out.println("Is blank? " + " ".isBlank()); // true
// 2. Predicate.not() with Method References
List<String> names = List.of("Jack", "Jim", "", "Dan", " ");
List<String> validNames = names.stream()
.filter(Predicate.not(String::isBlank))
.collect(Collectors.toList());
System.out.println("Non-blank names: " + validNames);
// 3. Java 11 Rapid File Reading & Writing
Path tempPath = Path.of("enterprise_config.txt");
Files.writeString(tempPath, "SERVER_PORT=8080
ENV=PRODUCTION");
String content = Files.readString(tempPath);
System.out.println("File Content:
" + content);
}
}