Java 17 Features
Java 17 (September 2021) doosri major LTS (Long-Term Support) release hai Java 11 ke baad — bahut companies isi version par migrate karti hain kyunki isme kai saal ke improvements ek saath aate hain (Java 12 se 17 tak ke saare features).
Sabse bade highlights: Records (data classes ek line mein), Sealed Classes (controlled inheritance), Pattern Matching for instanceof (auto-casting), Text Blocks (multi-line strings aasani se), aur Switch Expressions.
Interview mein Java 17 ke features bahut common hain, especially Records aur Sealed Classes — kyunki ye modern Java code likhne ka tareeka badal dete hain, boilerplate kam karte hain.
// Record — ek line mein data class
record User(String name, int age) {}
User u = new User("Aarav", 25);
System.out.println(u); // User[name=Aarav, age=25]
// Pattern Matching for instanceof
Object obj = "Hello";
if (obj instanceof String s) {
System.out.println(s.length()); // seedha use, cast nahi chahiye
}- Java 17 = LTS release (Sept 2021)
- Records = data classes ek line mein
- Sealed Classes = controlled inheritance
- Pattern Matching for instanceof = auto-cast
- Text Blocks = multi-line strings aasani se
Normal class mein ek simple data-holder (jaise Point jisme sirf x aur y hon) banane ke liye kaafi boilerplate likhna padta hai — constructor, getters, equals(), hashCode(), toString() sab manually (ya IDE se generate karke). record keyword ye sab automatically generate kar deta hai ek line mein.
record Point(int x, int y) {} likhne se compiler khud banata hai: ek constructor (dono fields set karne wala), getter methods (x() aur y() — bina "get" prefix ke), aur properly implemented equals(), hashCode(), toString(). Records implicitly final hain (extend nahi ho sakte) aur unke fields bhi implicitly final hain (immutable).
Records tab best hain jab tumhe sirf data carry karna ho, koi complex behavior nahi — jaise API responses, DTOs (Data Transfer Objects), ya coordinate pairs. Agar class mein methods/logic bhi chahiye (sirf data nahi), normal class hi better rahegi.
Interview mein pucha ja sakta hai records aur Lombok ke @Data annotation mein farq — Lombok ek third-party library hai jo compile-time code generate karti hai (annotation processing), jabki records ek native language feature hai, koi extra dependency nahi chahiye.
- Constructor — dono fields set karne wala, automatically
- Getters — x() aur y(), bina "get" prefix ke
- equals() / hashCode() — values compare karte hain, properly implemented
- toString() — readable format, jaise Point[x=3, y=4]
record Point(int x, int y) {}
Point p1 = new Point(3, 4);
System.out.println(p1.x()); // 3 (getter, "get" prefix nahi)
System.out.println(p1); // Point[x=3, y=4] (auto toString)
Point p2 = new Point(3, 4);
System.out.println(p1.equals(p2)); // true (auto equals, values compare hote hain)Normal class/interface ko koi bhi extend/implement kar sakta hai — sealed keyword se tum control karte ho *exactly* kaun-kaun extend/implement kar sakta hai. Ye especially useful hai jab tumhe pata ho ki sab possible subtypes kya hain (jaise Shape sirf Circle, Square, Triangle ho sakta hai, aur kuch nahi).
sealed class Shape permits Circle, Square, Triangle {} likhne se sirf ye teen classes hi Shape extend kar sakti hain — koi bahar ka code naya subtype nahi bana sakta. Har permitted subclass ko explicitly declare karna padta hai: final (aage extend nahi ho sakti), sealed (khud aage control karti hai), ya non-sealed (wapas normal, kuch bhi extend kar sakta hai).
Fayda: switch statements mein compiler ko pata hota hai saare possible types kya hain, isliye "exhaustiveness checking" possible hota hai (agla subtopic mein pattern matching ke saath dekhenge) — bina default case ke bhi compiler confirm kar sakta hai saare cases cover ho gaye.
Real-world use-case: API response modeling mein sealed classes bahut useful hain — jaise ApiResult sirf Success ya Failure ho sakta hai, aur kuch nahi. Ye pattern functional languages (jaise Kotlin ke sealed classes) se inspire hua hai.
- final — permitted subclass aage extend nahi ho sakti
- sealed — permitted subclass khud aage control karti hai
- non-sealed — wapas normal, kuch bhi extend kar sakta hai
sealed interface Shape permits Circle, Square, Triangle {}
final class Circle implements Shape { double radius; }
final class Square implements Shape { double side; }
final class Triangle implements Shape { double base, height; }
// Koi doosri class Shape implement NAHI kar sakti — compiler error degaPurane Java mein instanceof check karne ke baad manually cast karna padta tha — do steps, thoda repetitive: if (obj instanceof String) { String s = (String) obj; ... }. Java 16+ (17 mein stable) mein instanceof khud ek variable "bind" kar deta hai agar check pass ho jaaye.
if (obj instanceof String s) likhne se, agar obj String hai, to s automatically us cast-kiye-hue value ko point karta hai — us if block ke andar seedha s use kar sakte ho, manual cast ki zaroorat nahi. Ye code ko chhota aur safer banata hai (ClassCastException ka risk kam hota hai kyunki compiler khud type-check karta hai).
Chained conditions mein bhi kaam aata hai — if (obj instanceof String s && s.length() > 5) jaisa likh sakte ho, jaha pattern variable s turant next condition mein bhi use ho jaata hai.
Object obj = "Hello Java 17";
// Purana tareeka:
if (obj instanceof String) {
String s = (String) obj;
System.out.println(s.length());
}
// Java 16+ pattern matching:
if (obj instanceof String s) {
System.out.println(s.length()); // s seedha use ho sakta hai, cast nahi chahiye
}Multi-line String (jaise JSON, HTML, SQL query) likhna purane Java mein bahut messy tha — har line ke end mein \n, quotes escape karna, + se concatenate karna. Text block (""" se shuru aur khatam hoke) is sab ko khatam kar deta hai.
Text block automatically leading whitespace ko "smart" tareeke se strip karta hai (saari lines ka common indentation hata deta hai), line breaks ko \n mein convert kar deta hai, aur quotes ko escape karne ki zaroorat nahi (sirf edge cases mein).
SQL queries, JSON payloads, ya HTML templates likhते waqt text blocks code review mein bhi easier ho jaate hain — reviewer ko poora structure ek saath dikhta hai, string concatenation ke tute-phute pieces nahi.
- Common leading whitespace automatically strip hota hai
- Line breaks khud \n mein convert ho jaate hain
- Quotes escape karne ki zaroorat nahi (sirf edge cases mein)
// Purana tareeka:
String json1 = "{\n" +
" \"name\": \"Aarav\",\n" +
" \"age\": 25\n" +
"}";
// Text block (Java 15+):
String json2 = """
{
"name": "Aarav",
"age": 25
}
""";Switch Expression (Java 14+, stable) purane switch statement se chhota aur safer hai — arrow syntax (case X -> result) use karta hai, fall-through nahi hota (har case ke end mein break nahi chahiye), aur ek value "return" bhi kar sakta hai (assignment mein directly use karne layak).
Java 17 mein Pattern Matching for switch preview feature ke roop mein aaya (baad ki versions mein stable hua) — ab switch mein type ke basis par bhi branch kar sakte ho, instanceof jaisa hi pattern binding ke saath: case Integer i -> ..., case String s -> ....
Multiple case labels ek saath bhi likh sakte ho comma se — case 1, 2, 3 -> "Weekday"; — jo purane switch statement mein bhi possible tha, lekin ab arrow syntax ke saath aur bhi clean lagta hai.
// Purana switch statement:
int day = 3;
String name;
switch (day) {
case 1: name = "Monday"; break;
case 2: name = "Tuesday"; break;
default: name = "Other";
}
// Switch Expression (Java 14+):
String name2 = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
default -> "Other";
};
// Pattern Matching for switch (preview, Java 17):
Object obj = 42;
String result = switch (obj) {
case Integer i -> "Integer: " + i;
case String s -> "String: " + s;
default -> "Unknown";
};Purana java.util.Random ek hi algorithm use karta tha, aur naye/behtar random algorithms add karna mushkil tha (sab kuch Random class mein hi hardcoded tha). Java 17 ne RandomGenerator interface diya jo saare random number generators (naye purane) ke liye ek common API deta hai.
Naye algorithms bhi aaye — jaise Xoshiro256PlusPlus, jo purane Random se better statistical quality aur performance dete hain, especially parallel/multi-threaded use ke liye (jaise SplittableRandom jo alag-alag threads ko independent streams de sakta hai bina lock overhead ke).
Interview mein zyada deep detail expected nahi hai is topic par — bas itna pata hona chahiye ki RandomGenerator ek naya common interface hai, aur SecureRandom (cryptographically strong random numbers ke liye) is hierarchy se alag, security-sensitive cases ke liye use hota hai.
RandomGenerator rng = RandomGenerator.of("Xoshiro256PlusPlus");
System.out.println(rng.nextInt(100)); // 0-99 ke beech ek random number
// Streams of random numbers bhi easily ban sakte hain:
rng.ints(5, 1, 10).forEach(System.out::println); // 5 numbers, 1-9 ke beechJava 9 mein module system (JPMS) aaya tha, lekin backward compatibility ke liye internal JDK APIs (jaise sun.misc.Unsafe) tab bhi --illegal-access flag se access ho sakte the. Java 17 se ye internals strongly encapsulate ho gaye — by default access nahi ho sakte, chahe kuch bhi flag use karo (sirf critical ones ke liye --add-opens explicitly dena padta hai).
Ye application code ke liye directly kam relevant hai, lekin agar tumhari koi library/framework internal JDK classes use karti thi (reflection se), Java 17 upgrade karte waqt ye break ho sakta hai — isiliye migration guides mein ye ek common gotcha hai.
Ye change specifically un libraries ko affect karta hai jo "unsafe" internal APIs use karke performance optimize karti thi (jaise kuch purane ORM frameworks) — modern libraries already migrate ho chuki hain, lekin legacy codebases upgrade karte waqt is issue se takra sakte hain.
Security Manager ek purana mechanism tha jo Java applications ko sandbox mein chalane deta tha (jaise browser applets ke liye) — restrict karta tha ki code kya kar sakta hai (file access, network, etc.). Modern applications isko rarely use karte hain (containers/OS-level sandboxing zyada common ho gaya hai), aur maintain karna JDK team ke liye costly tha.
Java 17 mein ise "deprecated for removal" mark kiya gaya (baad ke versions mein completely remove ho gaya) — agar koi legacy application isko use karti hai, upgrade se pehle warning aayegi, aur eventually alternative dhoondhna padega.
Alternative approach ke roop mein ab container-level isolation (Docker), OS-level sandboxing, ya cloud-provider IAM policies use hote hain — application-level security manager ki jagah infrastructure-level security zyada practical maana jaata hai modern deployments mein.