<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sayedbaladoh on Medium]]></title>
        <description><![CDATA[Stories by Sayedbaladoh on Medium]]></description>
        <link>https://medium.com/@sayedbaladoh?source=rss-4b41e944da6d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*r-BqPjRnCY31Y2kVhGRFRA.jpeg</url>
            <title>Stories by Sayedbaladoh on Medium</title>
            <link>https://medium.com/@sayedbaladoh?source=rss-4b41e944da6d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 02:29:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sayedbaladoh/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From Java to Kotlin: What You Need to Know (With Real Examples)]]></title>
            <link>https://medium.com/@sayedbaladoh/from-java-to-kotlin-what-you-need-to-know-with-real-examples-a6527df616fb?source=rss-4b41e944da6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6527df616fb</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-vs-java]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kotlin-tutorial]]></category>
            <category><![CDATA[kotlin-examples]]></category>
            <dc:creator><![CDATA[Sayedbaladoh]]></dc:creator>
            <pubDate>Tue, 10 Jun 2025 04:46:36 GMT</pubDate>
            <atom:updated>2025-06-11T06:22:30.152Z</atom:updated>
            <content:encoded><![CDATA[<h4>Mastering Kotlin</h4><h4>Side-by-Side Guide with Code Examples</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iurC2q0RfpncblBd_dW1jw.png" /><figcaption>From Java to Kotlin</figcaption></figure><p>As a Java developer, you’ve probably heard about Kotlin’s growing popularity, especially since Google announced it as a first-class language for Android development. But what makes Kotlin special, and how different is it from Java? This comprehensive guide will walk you through the key differences with side-by-side code examples, making your transition smooth and practical.</p><h3>Why Kotlin? A Quick Overview</h3><p>Kotlin is a modern, statically-typed programming language that runs on the Java Virtual Machine (JVM). It’s designed to be fully interoperable with Java, meaning you can use Java libraries in Kotlin and vice versa. The language aims to solve many of Java’s pain points while maintaining the performance and reliability Java developers love.</p><h3>1. Hello World</h3><h4>Java</h4><pre>public class HelloWorld {<br>    public static void main(String[] args) {<br>        System.out.println(&quot;Hello, World!&quot;);<br>    }<br>}</pre><h4>Kotlin</h4><pre>fun main() {<br>    println(&quot;Hello, World!&quot;)<br>}</pre><ul><li>Kotlin removes boilerplate. No need for class declarations just to run a simple main.</li><li>Functions are top-level by default.</li></ul><h3>2. Variable Declaration: val vs var</h3><p>One of the differences you’ll notice is how Kotlin handles variable declarations.</p><h4>Java</h4><pre>// Mutable variables<br>String name = &quot;John&quot;;<br>int age = 25;<br><br>// Final (immutable) variables<br>final String country = &quot;USA&quot;;<br>final List&lt;String&gt; cities = Arrays.asList(&quot;New York&quot;, &quot;Los Angeles&quot;);</pre><h4>Kotlin</h4><pre>// Mutable variables<br>var name = &quot;John&quot;<br>var age = 25<br><br>// Immutable variables (preferred)<br>val country = &quot;USA&quot;<br>val cities = listOf(&quot;New York&quot;, &quot;Los Angeles&quot;)</pre><ul><li>val: Read-only (like final in Java).</li><li>var: Mutable.</li><li>Type inference means no need to specify types unless necessary.</li><li>Kotlin encourages immutability with val (value) for read-only variables and var (variable) for mutable ones. Type inference eliminates the need to explicitly declare types in most cases.</li></ul><h3>3. Null Safety: Goodbye NullPointerException</h3><p>Kotlin’s null safety is one of its most celebrated features, designed to eliminate the dreaded NullPointerException.</p><h4>Java</h4><pre>public String processUser(User user) {<br>    if (user != null &amp;&amp; user.getName() != null) {<br>        return user.getName().toUpperCase();<br>    }<br>    return &quot;Unknown&quot;;<br>}<br><br>// Runtime exception risk<br>String result = someMethod(); // Could return null<br>int length = result.length(); // Potential NPE!</pre><h4>Kotlin</h4><pre>fun processUser(user: User?): String {<br>    return user?.name?.uppercase() ?: &quot;Unknown&quot;<br>}<br><br>// Null safety at compile time<br>val result: String? = someMethod() // Explicitly nullable<br>val length = result?.length ?: 0 // Safe call with default</pre><p><strong>Key Features</strong>:</p><ul><li>Kotlin has built-in null safety. You must explicitly declare if a variable can hold null (?). This helps avoid NullPointerException.</li><li>? marks nullable types</li><li>?. safe call operator (nullableName?.length)</li><li>?: Elvis operator for default values (nullableName?.length ?: 0)</li><li>!! not-null assertion (use carefully!)</li></ul><h3>4. Conditional Expressions</h3><h4>Java</h4><pre>int max = (a &gt; b) ? a : b;</pre><h4>Kotlin</h4><pre>val max = if (a &gt; b) a else b</pre><ul><li>In Kotlin,if is an <strong>expression</strong>, not just a statement. This allows direct assignment from conditionals.</li></ul><h3>5. When Expression: Enhanced Switch Statement</h3><h4>Java</h4><pre>public String getStatusMessage(Status status) {<br>    switch (status) {<br>        case PENDING:<br>            return &quot;Please wait...&quot;;<br>        case APPROVED:<br>            return &quot;Request approved!&quot;;<br>        case REJECTED:<br>            return &quot;Request denied.&quot;;<br>        default:<br>            return &quot;Unknown status&quot;;<br>    }<br>}</pre><h4>Kotlin</h4><pre>fun getStatusMessage(status: Status): String = when (status) {<br>    Status.PENDING -&gt; &quot;Please wait...&quot;<br>    Status.APPROVED -&gt; &quot;Request approved!&quot;<br>    Status.REJECTED -&gt; &quot;Request denied.&quot;<br>    else -&gt; &quot;Unknown status&quot;<br>}</pre><pre>// Or with multiple conditions<br>fun categorizeAge(age: Int): String = when {<br>    age &lt; 13 -&gt; &quot;Child&quot;<br>    age in 13..19 -&gt; &quot;Teenager&quot;<br>    age in 20..59 -&gt; &quot;Adult&quot;<br>    else -&gt; &quot;Senior&quot;<br>}</pre><ul><li>When replaces switch. More powerful — supports ranges, types, and complex conditions. No need for break.</li></ul><h3>6. Looping</h3><h4>For-each loop</h4><p><strong>Java:</strong></p><pre>for (String name : names) {<br>     System.out.println(name); <br>}</pre><p><strong>Kotlin:</strong></p><pre>for (name in names) {<br>     println(name) <br>}</pre><ul><li>Kotlin uses in for cleaner syntax.</li></ul><h4>Loop with Range</h4><p><strong>Java</strong></p><pre>for (int i = 1; i &lt;= 5; i++) {<br>     System.out.println(i); <br>}</pre><p><strong>Kotlin</strong></p><pre>for (i in 1..5) {<br>     println(i) <br>}</pre><ul><li>1..5 creates a closed range (inclusive).</li></ul><h4>Loop with Step</h4><p><strong>Java</strong></p><pre>for (int i = 0; i &lt;= 10; i += 2) {<br>     System.out.println(i); <br>}</pre><p><strong>Kotlin</strong></p><pre>for (i in 0..10 step 2) {<br>     println(i) <br>}</pre><ul><li>step keyword makes stepping intuitive.</li></ul><h4>Descending Loop</h4><p><strong>Java</strong></p><pre>for (int i = 5; i &gt;= 1; i--) {<br>     System.out.println(i); <br>}</pre><p><strong>Kotlin</strong></p><pre>for (i in 5 downTo 1) {<br>     println(i) <br>}</pre><ul><li>downTo makes reverse iteration expressive.</li></ul><h4>Exclusive Range (until)</h4><p><strong>Kotlin Only</strong></p><pre>for (i in 1 until 5) {<br>     println(i) <br>}</pre><ul><li>until excludes the end value (1..4).</li></ul><h4><strong>Index-based loop</strong></h4><p><strong>Java:</strong></p><pre>for (int i = 0; i &lt; names.length; i++) {<br>     System.out.println(names[i]);<br>}</pre><p><strong>Kotlin:</strong></p><pre>for (i in names.indices) {<br>     println(names[i]) <br>}</pre><ul><li>indices is a convenient property in Kotlin.</li></ul><h4><strong>With index and value</strong></h4><p><strong>Java:</strong></p><pre>for (int i = 0; i &lt; names.length; i++) {<br>     System.out.println(i + &quot;: &quot; + names[i]); <br>}</pre><p><strong>Kotlin:</strong></p><pre>for ((i, name) in names.withIndex()) {<br>     println(&quot;$i: $name&quot;) <br>}</pre><ul><li>Kotlin supports <strong>destructuring</strong> with withIndex() for concise index-value access.</li></ul><h4><strong>While loop</strong><br><strong> Java &amp; Kotlin (almost identical):</strong></h4><pre>int i = 0; <br>while (i &lt; 5) {<br>     System.out.println(i++); <br>}</pre><h4>kotlin</h4><pre>var i = 0 while (i &lt; 5) {<br>     println(i++) <br>}</pre><h4><strong>Repeat loop (Kotlin only)</strong></h4><pre>repeat(5) {<br>     println(&quot;Hello&quot;) <br>}</pre><ul><li>Kotlin’s repeat(n) loop is great for fixed iterations.</li></ul><h4>Looping Summary:</h4><ul><li>Kotlin loops are <strong>cleaner and more expressive</strong>.</li><li>Features like withIndex(), indices, and repeat() reduce boilerplate.</li><li>Kotlin supports <strong>destructuring</strong> directly in loops.</li></ul><h3>7. Functions: More Concise and Powerful</h3><p>Kotlin functions are more flexible and concise than Java methods.</p><h4>Java</h4><pre>public class MathUtils {<br>    public static int add(int a, int b) {<br>        return a + b;<br>    }<br>    <br>    public static int multiply(int a, int b, int factor) {<br>        return (a * b) * factor;<br>    }<br>    <br>    // Method overloading for default parameters<br>    public static int multiply(int a, int b) {<br>        return multiply(a, b, 1);<br>    }<br>}</pre><h4>Kotlin</h4><pre>// Top-level functions (no class needed)<br>fun greet(name: String): String { // Use fun, and return types go after :<br>    return &quot;Hello, $name&quot;<br>}<br><br>// Single-expression function<br>fun greet(name: String) = &quot;Hello, $name&quot;<br><br>fun add(a: Int, b: Int): Int = a + b<br><br>// Default parameters eliminate overloading<br>fun multiply(a: Int, b: Int, factor: Int = 1): Int = (a * b) * factor<br>// Usage with named parameters<br>val result = multiply(a = 5, b = 3, factor = 2)<br>val simpleResult = multiply(5, 3) // Uses default factor = 1</pre><ul><li>Function declarations are concise.</li><li>Use fun, and return types go after :.</li><li>Kotlin also supports <strong>single-expression functions.</strong></li></ul><h3>8. Classes: Bye-bye Boilerplate</h3><p>Kotlin drastically reduces boilerplate compared to Java while still supporting full OOP concepts like encapsulation, inheritance, and polymorphism.</p><h4>Basic Class Declaration</h4><p><strong>Java</strong></p><pre>public class Person {<br>     private String name;<br>     private int age;<br>     <br>     public Person(String name, int age) {<br>         this.name = name;<br>         this.age = age;<br>     }<br><br>     public String getName() {<br>         return name;<br>     }<br><br>     public void setName(String name) {<br>         this.name = name;     <br>     }<br><br>     public int getAge() {<br>         return age;<br>     }<br><br>     public void setAge(int age) {<br>         this.age = age;<br>     }<br> }</pre><p><strong>Kotlin</strong></p><pre>class Person(var name: String, var age: Int)</pre><ul><li>Kotlin declares constructor and properties in one line. No getters/setters needed — it’s built-in.</li></ul><h4>Default Values in Constructor</h4><p><strong>Java</strong></p><pre>public Person() {<br>     this.name = &quot;Guest&quot;;<br>     this.age = 0;<br>}</pre><p><strong>Kotlin</strong></p><pre>class Person(var name: String = &quot;Guest&quot;, var age: Int = 0)</pre><ul><li>Kotlin supports default values directly in the constructor.</li></ul><h4>Data Class</h4><p><strong>Java</strong></p><pre>public class User {<br>     private int id;<br>     private String name;<br><br>     // constructor, getters, setters, equals(), hashCode(), toString()... <br>}</pre><p><strong>Kotlin</strong></p><pre>data class User(val id: Int, val name: String)</pre><ul><li>data class in Kotlin automatically generates common methods like equals, hashCode, toString, copy, and destructuring.</li></ul><h4>Java</h4><pre>public class Person {<br>    private String name;<br>    private int age;<br>    private String email;<br>    <br>    public Person(String name, int age, String email) {<br>        this.name = name;<br>        this.age = age;<br>        this.email = email;<br>    }<br>    <br>    // Getters and setters (50+ lines of boilerplate)<br>    public String getName() { return name; }<br>    public void setName(String name) { this.name = name; }<br>    // ... more getters/setters<br>    <br>    @Override<br>    public boolean equals(Object obj) {<br>        // 15+ lines of equals implementation<br>    }<br>    <br>    @Override<br>    public int hashCode() {<br>        // hashCode implementation<br>    }<br>    <br>    @Override<br>    public String toString() {<br>        // toString implementation<br>    }<br>}</pre><h4>Kotlin</h4><pre>data class Person(<br>    val name: String,<br>    val age: Int,<br>    val email: String<br>)<br><br>// Usage<br>val person = Person(&quot;John&quot;, 25, &quot;john@example.com&quot;)<br>val olderPerson = person.copy(age = 26)<br>println(person) // Automatic toString()</pre><h4>Inheritance</h4><p><strong>Java</strong></p><pre>public class Student extends Person {<br>     public Student(String name, int age) {<br>         super(name, age);<br>     } <br>}</pre><p><strong>Kotlin</strong></p><pre>open class Person(val name: String, val age: Int)  <br><br>class Student(name: String, age: Int) : Person(name, age)</pre><ul><li>Classes are final by default in Kotlin; use open to allow inheritance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x_fV2KCs7ZSKJFY5LPEOHQ.png" /><figcaption>Class in Kotlin VS Java</figcaption></figure><h4>9. String Templates: Cleaner String Building</h4><h4>Java</h4><pre>String name = &quot;Alice&quot;;<br>int age = 30;<br>String message = &quot;Hello, my name is &quot; + name + &quot; and I&#39;m &quot; + age + &quot; years old.&quot;;<br><br>// Or with String.format<br>String formatted = String.format(&quot;User %s (ID: %d) has %d notifications&quot;, <br>                                name, userId, count);</pre><h4>Kotlin</h4><pre>val name = &quot;Alice&quot;<br>val age = 30<br>val message = &quot;Hello, my name is $name and I&#39;m $age years old.&quot;<br><br>// Complex expressions in templates<br>val formatted = &quot;User $name (ID: ${user.id}) has ${notifications.size} notifications&quot;</pre><ul><li>Kotlin makes string interpolation easy using $ instead of concatenation.</li><li>You can also use ${expression} for complex values.</li></ul><h3>10. Arrays</h3><h4>Java</h4><pre>// Declaration<br>int[] nums = new int[3];<br><br>// Initialization<br>String[] names = {&quot;Alice&quot;, &quot;Bob&quot;};<br><br>// Accessing Elements<br>names[0] = &quot;John&quot;<br><br>// Getting Length<br>int namesSize = names.length<br><br>// Looping<br>for (String name : names) { <br>    System.out.println(name);<br>}<br><br>// Functional Operations<br>int[] arr = {1, 2, 3}<br>Arrays.stream(arr).map(x -&gt; x * 2).toArray();</pre><h4>Kotlin</h4><pre>// Declaration<br>val nums = IntArray(3)<br><br>// Initialization<br>val names = arrayOf(&quot;Alice&quot;, &quot;Bob&quot;)<br><br><br>// Accessing Elements<br>names[0] = &quot;John&quot;<br><br>// Getting Length<br>val namesSize = names.size<br><br>// Looping<br>for (name in names) { <br>    println(name);<br>}<br><br>// Functional Operations<br>val arr = IntArray.of(1, 2, 3)<br>arr.map { it * 2 };</pre><ul><li>Kotlin uses specialized types like IntArray, DoubleArray, etc.</li><li>arrayOf() is the idiomatic way to create arrays in Kotlin.</li><li>Accessing elements uses the same syntax in both Java and Kotlin.</li><li>Kotlin supports clean for-in loops and destructuring with withIndex().</li><li>Kotlin has built-in support for functional programming on arrays.</li></ul><h3>11. Collections: More Functional and Intuitive</h3><p>Kotlin provides a rich set of collection operations inspired by functional programming. Kotlin collections support map, filter, reduce, forEach, etc., using lambda syntax.</p><h4>Java</h4><pre>List&lt;String&gt; names = Arrays.asList(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;, &quot;Diana&quot;);<br><br>// Filter and transform<br>List&lt;String&gt; filteredNames = new ArrayList&lt;&gt;();<br>for (String name : names) {<br>    if (name.length() &gt; 3) {<br>        filteredNames.add(name.toUpperCase());<br>    }<br>}<br><br>// Or with Streams (Java 8+)<br>List&lt;String&gt; result = names.stream()<br>    .filter(name -&gt; name.length() &gt; 3)<br>    .map(String::toUpperCase)<br>    .collect(Collectors.toList());</pre><h4>Kotlin</h4><pre>val names = listOf(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;, &quot;Diana&quot;)<br><br>// Functional approach<br>val filteredNames = names<br>    .filter { it.length &gt; 3 }<br>    .map { it.uppercase() }<br><br>// Or even more concise<br>val result = names.filter { it.length &gt; 3 }.map(String::uppercase)</pre><h3>12. Extension Functions: Add Methods to Existing Classes</h3><p>This is one of Kotlin’s most powerful features, allowing you to <strong>extend existing classes without inheritance</strong>.</p><h4>Java</h4><pre>// Utility class approach<br>public class StringUtils {<br>    public static boolean isPalindrome(String str) {<br>        String cleaned = str.replaceAll(&quot;[^a-zA-Z0-9]&quot;, &quot;&quot;).toLowerCase();<br>        return cleaned.equals(new StringBuilder(cleaned).reverse().toString());<br>    }<br>}<br><br>// Usage<br>boolean result = StringUtils.isPalindrome(&quot;A man a plan a canal Panama&quot;);</pre><h4>Kotlin</h4><pre>// Extension function<br>fun String.isPalindrome(): Boolean {<br>    val cleaned = this.replace(Regex(&quot;[^a-zA-Z0-9]&quot;), &quot;&quot;).lowercase()<br>    return cleaned == cleaned.reversed()<br>}<br><br>// Usage - feels like a native method<br>val result = &quot;A man a plan a canal Panama&quot;.isPalindrome()</pre><h3>13. Smart Casts: Automatic Type Casting</h3><h4>Java</h4><pre>public void processObject(Object obj) {<br>    if (obj instanceof String) {<br>        String str = (String) obj; // Manual casting required<br>        System.out.println(&quot;String length: &quot; + str.length());<br>    } else if (obj instanceof Integer) {<br>        Integer num = (Integer) obj; // Manual casting required<br>        System.out.println(&quot;Number: &quot; + num);<br>    }<br>}</pre><h4>Kotlin</h4><pre>fun processObject(obj: Any) {<br>    when (obj) {<br>        is String -&gt; println(&quot;String length: ${obj.length}&quot;) // Auto-cast to String<br>        is Int -&gt; println(&quot;Number: $obj&quot;) // Auto-cast to Int<br>        is List&lt;*&gt; -&gt; println(&quot;List size: ${obj.size}&quot;) // Auto-cast to List<br>    }<br>}</pre><ul><li>Kotlin auto-casts after type checks using is. No need to manually cast like in Java ((String) obj).</li></ul><h3>14. Coroutines: Simplified Asynchronous Programming</h3><p>While Java has CompletableFuture and other async mechanisms, Kotlin’s coroutines provide a more intuitive approach.</p><h4>Java</h4><pre>public CompletableFuture&lt;String&gt; fetchUserData(int userId) {<br>    return CompletableFuture<br>        .supplyAsync(() -&gt; fetchUserFromDb(userId))<br>        .thenCompose(user -&gt; fetchUserPreferences(user.getId()))<br>        .thenApply(prefs -&gt; processUserData(user, prefs))<br>        .exceptionally(ex -&gt; {<br>            log.error(&quot;Error fetching user data&quot;, ex);<br>            return &quot;Default data&quot;;<br>        });<br>}</pre><h4>Kotlin</h4><pre>suspend fun fetchUserData(userId: Int): String {<br>    return try {<br>        val user = fetchUserFromDb(userId)<br>        val prefs = fetchUserPreferences(user.id)<br>        processUserData(user, prefs)<br>    } catch (ex: Exception) {<br>        log.error(&quot;Error fetching user data&quot;, ex)<br>        &quot;Default data&quot;<br>    }<br>}</pre><h3>15. Interoperability with Java</h3><p>Kotlin can use <strong>all Java libraries</strong>. Java can call Kotlin code (with some annotations):</p><pre>@JvmOverloads fun greet(name: String = &quot;Guest&quot;) = &quot;Hello, $name&quot;</pre><ul><li>Kotlin is 100% interoperable with Java. Use annotations like @JvmOverloads, @JvmStatic, @JvmField for better Java interop.</li></ul><h3>Kotlin vs Java</h3><pre>| **Concept**                    | **Java**                                                                                                                                        | **Kotlin**                                                                                                      | **Description**                                                                   |<br>| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |<br>| **Hello World**                | `java public class Hello { public static void main(String[] args) { System.out.println(&quot;Hello, World!&quot;); } } `                                  | `kotlin fun main() { println(&quot;Hello, World!&quot;) } `                                                               | Kotlin removes boilerplate (no need for `class`, `static`, or `public` keywords). |<br>| **Variable Declaration**       | `java final String name = &quot;Alice&quot;; int age = 30; `                                                                                              | `kotlin val name = &quot;Alice&quot; // immutable var age = 30 // mutable `                                               | `val` for read-only, `var` for mutable. Type inference reduces verbosity.         |<br>| **Function Declaration**       | `java public String greet(String name) { return &quot;Hello, &quot; + name; } `                                                                           | `kotlin fun greet(name: String): String { return &quot;Hello, $name&quot; } `                                             | Functions are declared with `fun`. String interpolation with `$`.                 |<br>| **Single-expression Function** | *Not available; always needs `{}`*                                                                                                              | `kotlin fun greet(name: String) = &quot;Hello, $name&quot; `                                                              | Kotlin allows concise single-expression functions.                                |<br>| **Null Safety**                | `java String name = null; if (name != null) name.length(); `                                                                                    | `kotlin val name: String? = null name?.length `                                                                 | Kotlin enforces null safety at compile time with `?`.                             |<br>| **Elvis Operator**             | *Manually check null and assign default*                                                                                                        | `kotlin val len = name?.length ?: 0 `                                                                           | Kotlin&#39;s `?:` operator provides a default when the value is `null`.               |<br>| **String Interpolation**       | `java String name = &quot;Java&quot;; System.out.println(&quot;Hello, &quot; + name); `                                                                             | `kotlin val name = &quot;Kotlin&quot; println(&quot;Hello, $name&quot;) `                                                           | Kotlin simplifies string formatting with `$variable` syntax.                      |<br>| **Conditional Assignment**     | `java int max = (a &gt; b) ? a : b; `                                                                                                              | `kotlin val max = if (a &gt; b) a else b `                                                                         | Kotlin uses `if` as an expression.                                                |<br>| **Switch / When Expression**   | `java switch (x) { case 1: System.out.println(&quot;One&quot;); break; default: System.out.println(&quot;Other&quot;); } `                                          | `kotlin when (x) { 1 -&gt; println(&quot;One&quot;) else -&gt; println(&quot;Other&quot;) } `                                             | `when` replaces `switch`, is more expressive and doesn&#39;t need `break`.            |<br>| **Class Declaration**          | `java public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } } ` | `kotlin class Person(val name: String, var age: Int) `                                                          | Kotlin class declaration is more concise and includes properties.                 |<br>| **Data Class**                 | *Manual implementation of equals, hashCode, toString*                                                                                           | `kotlin data class User(val id: Int, val name: String) `                                                        | `data class` generates boilerplate for you: `equals`, `hashCode`, etc.            |<br>| **List Declaration**           | `java List&lt;String&gt; list = Arrays.asList(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;); `                                                                                       | `kotlin val list = listOf(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;) `                                                                      | Kotlin has built-in support for immutable/mutable lists.                          |<br>| **Map Declaration**            | `java Map&lt;String, String&gt; map = new HashMap&lt;&gt;(); map.put(&quot;key&quot;, &quot;value&quot;); `                                                                     | `kotlin val map = mapOf(&quot;key&quot; to &quot;value&quot;) `                                                                     | Kotlin simplifies map creation with `to` syntax.                                  |<br>| **Lambda Expressions**         | `java list.stream().filter(s -&gt; s.startsWith(&quot;A&quot;)).collect(Collectors.toList()); `                                                              | `kotlin val filtered = list.filter { it.startsWith(&quot;A&quot;) } `                                                     | Kotlin&#39;s lambdas are shorter and cleaner.                                         |<br>| **Extension Function**         | *Requires utility class*                                                                                                                        | `kotlin fun String.isPalindrome(): Boolean = this == this.reversed() `                                          | Add methods to existing classes without inheritance.                              |<br>| **Smart Casts**                | `java if (obj instanceof String) { String s = (String) obj; return s.length(); } `                                                              | `kotlin if (obj is String) return obj.length `                                                                  | Kotlin smart casts automatically after type checks.                               |<br>| **Coroutines (Async)**         | *Use Threads, Future, or ExecutorService*                                                                                                       | `kotlin runBlocking { launch { delay(1000) println(&quot;Hi&quot;) } } `                                                  | Kotlin has lightweight coroutines for async tasks.                                |<br>| **Default Arguments**          | *Use method overloading*                                                                                                                        | `kotlin fun greet(name: String = &quot;Guest&quot;) = &quot;Hello, $name&quot; `                                                    | Default parameter values avoid multiple overloads.                                |<br>| **Destructuring Declaration**  | *Not available*                                                                                                                                 | `kotlin val (id, name) = user `                                                                                 | Extract multiple values from a data class concisely.                              |<br>| **Sealed Classes**             | *Simulate with abstract classes/enums*                                                                                                          | `kotlin sealed class Result class Success(val data: String): Result() class Error(val e: Exception): Result() ` | Restricts subclassing to a known set of types, useful for `when`.                 |</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xh_TykJZeJufN-5P8jfmMg.png" /><figcaption>Kotlin vs Java</figcaption></figure><h3>Making the Transition: Practical Tips</h3><h4>1. Start Small</h4><p>Begin by converting utility classes and data classes to Kotlin. These typically have the most dramatic improvements.</p><h4>2. Gradual Migration</h4><p>You can mix Java and Kotlin in the same project. Start with new features in Kotlin while keeping existing Java code.</p><h4>3. Use IDE Tools</h4><p>IntelliJ IDEA and Android Studio have excellent Java-to-Kotlin converters, though manual cleanup is often needed.</p><h4>4. Learn Kotlin Idioms</h4><p>Don’t just write Java code in Kotlin syntax. Embrace Kotlin’s features like:</p><ul><li>Prefer val over var</li><li>Use extension functions instead of utility classes</li><li>Leverage functional collection operations</li><li>Take advantage of string templates</li></ul><h3>Common Pitfalls to Avoid</h3><ol><li><strong>Overusing </strong><strong>!! operator</strong>: This defeats null safety. Use safe calls instead.</li><li><strong>Ignoring immutability</strong>: Prefer val and immutable collections.</li><li><strong>Not using data classes</strong>: They eliminate tons of boilerplate.</li><li><strong>Mixing paradigms</strong>: Don’t write Java-style code in Kotlin files.</li></ol><h3>Conclusion</h3><p>Kotlin offers a more concise, safe, and expressive alternative to Java while maintaining full interoperability. The transition doesn’t have to be overwhelming — start with small projects or new features, and gradually adopt Kotlin’s idioms and best practices.</p><p>The examples in this guide show that Kotlin can significantly reduce boilerplate code while improving safety and readability. Whether you’re building Android apps, server-side applications, or any JVM-based project, Kotlin provides modern language features that can make your development experience more enjoyable and productive.</p><p><em>Have you started using Kotlin in your projects? Share your experience and favorite Kotlin features in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6527df616fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Comprehensive Guide to Java Features from Java 8 to Java 24 with Examples]]></title>
            <link>https://medium.com/@sayedbaladoh/a-comprehensive-guide-to-java-features-from-java-8-to-java-24-with-examples-9901c859fa6d?source=rss-4b41e944da6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9901c859fa6d</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[java-developer]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sayedbaladoh]]></dc:creator>
            <pubDate>Mon, 09 Jun 2025 08:57:41 GMT</pubDate>
            <atom:updated>2025-06-28T13:18:30.082Z</atom:updated>
            <content:encoded><![CDATA[<h4>Mastering Java</h4><h4>Java 8 to Java 24: In-Depth Features with Examples</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETG2m4tuQzicLz7IJ033nA.png" /><figcaption>Java 8 to Java 24</figcaption></figure><p>Java has evolved tremendously from Java 8 to Java 24, introducing powerful language features and APIs that improve developer productivity, code clarity, and performance.</p><p>This comprehensive guide explores the key features introduced in each version, complete with practical examples.</p><h3>Java 8 (March 2014): The Functional Revolution</h3><p>Java 8 remains one of the most significant releases in Java’s history, introducing functional programming concepts that revolutionized Java development.</p><h4><strong>1. Default and Static Methods in Interfaces</strong></h4><ul><li>Allows interfaces to have method implementations without breaking existing code, enhancing backward compatibility.</li></ul><pre>interface MyInterface {<br>    default void sayHello() {<br>        System.out.println(&quot;Hello&quot;);<br>    }<br>    static void sayBye() {<br>        System.out.println(&quot;Bye&quot;);<br>    }<br>}<br><br>interface Vehicle {<br>    default void start() {<br>        System.out.println(&quot;Starting vehicle...&quot;);<br>    }<br>}</pre><h4><strong>2. Functional Interfaces</strong></h4><ul><li>An interface with just a single abstract method (SAM). Used primarily with lambda expressions.</li></ul><pre>@FunctionalInterface<br>interface MyFunction {<br>    void apply();<br>}</pre><h4><strong>3. Lambda Expressions</strong></h4><ul><li>Enabled functional-style programming by allowing us to treat functionality as a method argument.</li><li>Allowing us to write more concise and readable code.</li></ul><pre>// Java 8 with Lambda<br>List&lt;String&gt; list = Arrays.asList(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;);<br>list.forEach(item -&gt; System.out.println(item));</pre><pre>// Before Java 8<br>List&lt;String&gt; names = Arrays.asList(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;);<br>Collections.sort(names, new Comparator&lt;String&gt;() {<br>    @Override<br>    public int compare(String a, String b) {<br>        return a.compareTo(b);<br>    }<br>});<br><br>// Java 8 with Lambda<br>Collections.sort(names, (a, b) -&gt; a.compareTo(b));<br>// Or even simpler<br>Collections.sort(names, String::compareTo);</pre><h4>4. Method References</h4><ul><li>A shorthand for calling methods using the :: operator.</li><li>Used with functional interfaces and streams for concise, readable code.</li><li>Shorter lambda syntax.</li></ul><p><strong>Types of method references:</strong></p><ul><li><strong>Static </strong>methods: ClassName::staticMethodName</li><li><strong>Instance </strong>methods of a <strong>particular object</strong>: instance::methodName</li><li><strong>Instance </strong>methods of an arbitrary object of a <strong>particular type</strong>: ClassName::methodName</li><li><strong>Constructor </strong>references: ClassName::new</li></ul><pre>// Static method<br>list.forEach(System.out::println);<br><br>// Constructor reference<br>Supplier&lt;List&lt;String&gt;&gt; supplier = ArrayList::new;<br>List&lt;String&gt; newList = supplier.get();</pre><h4>5. Stream API</h4><ul><li>The Stream API revolutionized collection processing with functional-style operations.</li><li>Provides a powerful way to process collections in a declarative manner.</li><li><strong>Stream has Terminal and Intermediate Operations:</strong><br>- <strong>Intermediate operations:</strong> map(), filter(), sorted()<br>- <strong>Terminal operations:</strong> collect(), forEach(), reduce()</li></ul><pre>List&lt;Integer&gt; numbers = Arrays.asList(1, 2, 3, 4, 5);<br>List&lt;Integer&gt; squares = numbers.stream()<br>                               .map(n -&gt; n * n)<br>                               .collect(Collectors.toList());<br><br><br>List&lt;String&gt; list = Arrays.asList(&quot;a&quot;, &quot;bb&quot;, &quot;ccc&quot;);<br>list.stream().filter(s -&gt; s.length() &gt; 1).forEach(System.out::println);</pre><pre>List&lt;Person&gt; people = Arrays.asList(<br>    new Person(&quot;Alice&quot;, 30),<br>    new Person(&quot;Bob&quot;, 25),<br>    new Person(&quot;Charlie&quot;, 35)<br>);<br><br>// Filter, map, and collect<br>List&lt;String&gt; adultNames = people.stream()<br>    .filter(person -&gt; person.getAge() &gt;= 18)<br>    .map(Person::getName)<br>    .sorted()<br>    .collect(Collectors.toList());</pre><h4>6. forEach() Method</h4><ul><li>Used to iterate over elements in a collection using functional-style code.</li></ul><pre>List&lt;String&gt; list = Arrays.asList(&quot;Java&quot;, &quot;Python&quot;, &quot;C++&quot;);<br>list.forEach(language -&gt; System.out.println(language));</pre><h4>7. Collectors Utility Class</h4><ul><li>Collectors provides common reduction operations (e.g., grouping, joining, summarizing) to be used with streams</li><li>Example: collect(), toList(), joining(), groupingBy().</li></ul><pre>List&lt;String&gt; names = Arrays.asList(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;);<br><br>// Joining<br>String result = names.stream().collect(Collectors.joining(&quot;, &quot;));<br>System.out.println(result);  // Alice, Bob, Charlie<br><br>// Grouping by length<br>Map&lt;Integer, List&lt;String&gt;&gt; grouped = names.stream()<br>    .collect(Collectors.groupingBy(String::length));<br>System.out.println(grouped);</pre><h4>8. Optional Class</h4><ul><li>Improved null handling to reduce NullPointerException risks by providing a container for potentially null values, enhancing nullhandling.</li></ul><pre>// Optional for null safety<br>Optional&lt;String&gt; name = Optional.ofNullable(null);<br>System.out.println(name.orElse(&quot;Default&quot;));<br><br>Optional&lt;String&gt; name= Optional.ofNullable(&quot;Alice&quot;);<br>System.out.println(name.orElse(&quot;Default&quot;));<br><br>Optional&lt;String&gt; name = Optional.ofNullable(getName());<br>System.out.println(name.orElse(&quot;No name provided&quot;));</pre><pre>public Optional&lt;User&gt; findUserById(String id) {<br>    // Instead of returning null<br>    return userRepository.findById(id);<br>}<br><br>// Usage<br>Optional&lt;User&gt; user = findUserById(&quot;123&quot;);<br>user.ifPresent(u -&gt; System.out.println(u.getName()));<br><br>String userName = user<br>    .map(User::getName)<br>    .orElse(&quot;Unknown User&quot;);</pre><h4>9. New Date and Time API</h4><ul><li>More intuitive and immutable alternatives to java.util.Date and Calendar.</li></ul><pre>LocalDate date = LocalDate.now();<br>LocalTime time = LocalTime.now();<br>LocalDateTime dateTime = LocalDateTime.now();</pre><h3>Java 9 (September 2017): Modularity Revolution</h3><h4>1. JShell (REPL)</h4><ul><li>Interactive tool for quickly running Java code snippets without compiling full classes.</li><li>It provides a REPL (Read-Eval-Print Loop) for Java, perfect for experimentation and learning.</li></ul><pre>jshell&gt; int x = 10<br>x ==&gt; 10<br><br>jshell&gt; String greeting = &quot;Hello, Java &quot; + x<br>greeting ==&gt; &quot;Hello, Java 10&quot;<br><br>jshell&gt; System.out.println(greeting)<br>Hello, Java 10</pre><h4>2. Modules System (Project Jigsaw)</h4><ul><li>Introduces modular programming to Java, allowing better encapsulation and dependency management.</li></ul><pre>module com.example.myapp {<br>    requires java.base;<br>    exports com.example.api;<br>}</pre><pre>// module-info.java<br>module com.example.userservice {<br>    requires java.base;<br>    requires java.logging;<br>    <br>    exports com.example.userservice.api;<br>    <br>    provides com.example.userservice.spi.UserProvider <br>        with com.example.userservice.impl.DatabaseUserProvider;<br>}</pre><h4>3. Factory Methods for Collections</h4><ul><li>Simplifies creation of immutable collections (lists, sets, and maps).</li></ul><pre>List&lt;String&gt; list = List.of(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;);<br>Set&lt;String&gt; set = Set.of(&quot;x&quot;, &quot;y&quot;);</pre><pre>// Before Java 9<br>List&lt;String&gt; list = Collections.unmodifiableList(<br>    Arrays.asList(&quot;Apple&quot;, &quot;Banana&quot;, &quot;Cherry&quot;));<br><br>// Java 9<br>List&lt;String&gt; list = List.of(&quot;Apple&quot;, &quot;Banana&quot;, &quot;Cherry&quot;);<br>Map&lt;String, Integer&gt; map = Map.of(&quot;A&quot;, 1, &quot;B&quot;, 2, &quot;C&quot;, 3);<br>Set&lt;String&gt; set = Set.of(&quot;Red&quot;, &quot;Green&quot;, &quot;Blue&quot;);</pre><h4>4. Private Methods in Interfaces</h4><ul><li>Reduce code duplication.</li></ul><pre>interface DB {<br>    private void log(String msg) {<br>        System.out.println(msg);<br>    }<br>}</pre><h4>5. Stream API Improvements</h4><ul><li>Adds new methods like takeWhile, dropWhile, and iterate with predicates.</li></ul><pre>Stream.of(1, 2, 3, 4, 5)<br>      .takeWhile(n -&gt; n &lt; 4)<br>      .forEach(System.out::println);</pre><h3>Java 10 (March 2018): Type Inference</h3><h4>1. Local Variable Type Inference (var)</h4><ul><li>Allows var keyword for local variables to infer type, reducing verbosity and boilerplate code while maintaining type safety.</li></ul><pre>var list1 = new ArrayList&lt;String&gt;(); // Inferred as ArrayList&lt;String&gt;<br><br>var list2 = List.of(&quot;a&quot;, &quot;b&quot;);<br>for (var item : list2) {<br>    System.out.println(item);<br>}</pre><pre>// Before Java 10<br>Map&lt;String, List&lt;Integer&gt;&gt; complexMap = new HashMap&lt;String, List&lt;Integer&gt;&gt;();<br>FileInputStream fileInputStream = new FileInputStream(&quot;data.txt&quot;);<br><br>// Java 10<br>var complexMap = new HashMap&lt;String, List&lt;Integer&gt;&gt;();<br>var fileInputStream = new FileInputStream(&quot;data.txt&quot;);<br><br>// Works with streams too<br>var result = people.stream()<br>    .filter(person -&gt; person.getAge() &gt; 25)<br>    .collect(Collectors.toList());</pre><h3>Java 11 (September 2018 — LTS)</h3><p>Java 11 is a Long Term Support (LTS) version with several important additions.</p><h4>1. HTTP Client API</h4><ul><li>A standardized, modern, flexible, non-blocking, and built-in HTTP client replaced the need for external libraries.</li></ul><pre>HttpClient client = HttpClient.newHttpClient();<br>HttpRequest request = HttpRequest.newBuilder()<br>    .uri(URI.create(&quot;https://example.com&quot;))<br>    .build();<br>HttpResponse&lt;String&gt; response = client.send(request, HttpResponse.BodyHandlers.ofString());<br>System.out.println(response.body());</pre><pre>var client = HttpClient.newHttpClient();<br><br>var request = HttpRequest.newBuilder()<br>    .uri(URI.create(&quot;https://api.example.com/users&quot;))<br>    .header(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>    .POST(HttpRequest.BodyPublishers.ofString(&quot;{\&quot;name\&quot;:\&quot;John\&quot;}&quot;))<br>    .build();<br><br>// Synchronous<br>HttpResponse&lt;String&gt; response = client<br>    .send(request, HttpResponse.BodyHandlers.ofString());<br><br>// Asynchronous<br>CompletableFuture&lt;HttpResponse&lt;String&gt;&gt; futureResponse = client<br>    .sendAsync(request, HttpResponse.BodyHandlers.ofString());</pre><h4>2. New String Methods</h4><ul><li>New string utility methods (like isBlank(), lines(), strip(), etc) improved text processing capabilities.</li></ul><pre>System.out.println(&quot;  &quot;.isBlank());<br>&quot;Line1\nLine2&quot;.lines().forEach(System.out::println);<br><br>String multiline = &quot;Hello\nWorld&quot;;<br>multiline.lines().forEach(System.out::println);<br><br>// String API enhancements<br>String text = &quot;  Hello, Java 11!  \nNew Line&quot;;<br>System.out.println(&quot;Stripped: &#39;&quot; + text.strip() + &quot;&#39;&quot;);<br>System.out.println(&quot;Is Blank: &quot; + text.isBlank());</pre><pre>String multiline = &quot;  Line 1  \n  Line 2  \n  Line 3  &quot;;<br><br>// isBlank() - checks if string is empty or contains only whitespace<br>&quot;&quot;.isBlank(); // true<br>&quot;   &quot;.isBlank(); // true<br><br>// lines() - returns stream of lines<br>multiline.lines()<br>    .map(String::strip)<br>    .forEach(System.out::println);<br><br>// strip() - removes leading and trailing whitespace (Unicode-aware)<br>&quot;  Hello World  &quot;.strip(); // &quot;Hello World&quot;<br><br>// repeat() - repeats string n times<br>&quot;Java &quot;.repeat(3); // &quot;Java Java Java &quot;</pre><h3>Java 12 (March 2019)</h3><h4>1. Switch Expressions (Preview)</h4><ul><li>Enhances switch with expression capabilities and lambda-like syntax.</li><li>Switch expressions (preview feature) made switch statements more concise and expression-oriented.</li></ul><pre>int day = 3;<br>String result = switch (day) {<br>    case 1 -&gt; &quot;Monday&quot;;<br>    case 2 -&gt; &quot;Tuesday&quot;;<br>    case 3 -&gt; &quot;Wednesday&quot;;<br>    default -&gt; &quot;Unknown&quot;;<br>};</pre><pre>// Traditional switch<br>String dayType;<br>switch (day) {<br>    case MONDAY:<br>    case TUESDAY:<br>    case WEDNESDAY:<br>    case THURSDAY:<br>    case FRIDAY:<br>        dayType = &quot;Weekday&quot;;<br>        break;<br>    case SATURDAY:<br>    case SUNDAY:<br>        dayType = &quot;Weekend&quot;;<br>        break;<br>    default:<br>        dayType = &quot;Unknown&quot;;<br>}<br><br>// Switch expression (preview)<br>String dayType = switch (day) {<br>    case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -&gt; &quot;Weekday&quot;;<br>    case SATURDAY, SUNDAY -&gt; &quot;Weekend&quot;;<br>    default -&gt; &quot;Unknown&quot;;<br>};</pre><h3>Java 13 (September 2019)</h3><h4>1. Text Blocks (Preview)</h4><ul><li>Text blocks simplified multi-line string literals.</li><li>Multi-line string literals that preserve formatting.</li></ul><pre>String html = &quot;&quot;&quot;<br>    &lt;html&gt;<br>        &lt;body&gt;Hello, World!&lt;/body&gt;<br>    &lt;/html&gt;<br>    &quot;&quot;&quot;;</pre><pre>// Before text blocks<br>String json = &quot;{\n&quot; +<br>              &quot;  \&quot;name\&quot;: \&quot;John Doe\&quot;,\n&quot; +<br>              &quot;  \&quot;age\&quot;: 30,\n&quot; +<br>              &quot;  \&quot;city\&quot;: \&quot;New York\&quot;\n&quot; +<br>              &quot;}&quot;;<br><br>// With text blocks (preview)<br>String json = &quot;&quot;&quot;<br>    {<br>      &quot;name&quot;: &quot;John Doe&quot;,<br>      &quot;age&quot;: 30,<br>      &quot;city&quot;: &quot;New York&quot;<br>    }<br>    &quot;&quot;&quot;;<br><br>String sql = &quot;&quot;&quot;<br>    SELECT p.name, p.age, a.street, a.city<br>    FROM person p<br>    JOIN address a ON p.id = a.person_id<br>    WHERE p.age &gt;= 18<br>    ORDER BY p.name<br>    &quot;&quot;&quot;;</pre><h3>Java 14 (March 2020)</h3><h4>1. Switch Expressions (Standard)</h4><ul><li>Switch expressions became a standard feature with additional enhancements.</li><li>More concise.</li></ul><pre>String dayType = switch (day) {<br>    case &quot;MON&quot;, &quot;TUE&quot; -&gt; &quot;Weekday&quot;;<br>    default -&gt; &quot;Weekend&quot;;<br>};</pre><pre>public class Calculator {<br>    public double calculate(String operation, double a, double b) {<br>        return switch (operation) {<br>            case &quot;+&quot; -&gt; a + b;<br>            case &quot;-&quot; -&gt; a - b;<br>            case &quot;*&quot; -&gt; a * b;<br>            case &quot;/&quot; -&gt; {<br>                if (b == 0) throw new IllegalArgumentException(&quot;Division by zero&quot;);<br>                yield a / b;<br>            }<br>            default -&gt; throw new IllegalArgumentException(&quot;Unknown operation: &quot; + operation);<br>        };<br>    }<br>}</pre><h4>2. Text Blocks</h4><ul><li>Multi-line strings.</li></ul><pre>String json = &quot;&quot;&quot;<br>    {<br>        &quot;name&quot;: &quot;Alice&quot;,<br>        &quot;age&quot;: 30<br>    }<br>    &quot;&quot;&quot;;</pre><h4>3. Records (Preview)</h4><ul><li>Immutable data classes.</li><li>Concise syntax for classes that are pure data carriers.</li></ul><pre>record Person(String name, int age) {}<br>Person p = new Person(&quot;John&quot;, 25);<br>System.out.println(p.name());</pre><h4>4. Pattern Matching for instanceof (Preview)</h4><ul><li>Pattern matching reduced boilerplate code when checking types.</li><li>Simplifies casting after type check.</li></ul><pre>if (obj instanceof String s) {<br>    System.out.println(s.length());<br>}</pre><pre>// Before pattern matching<br>if (obj instanceof String) {<br>    String str = (String) obj;<br>    System.out.println(str.toUpperCase());<br>}<br><br>// With pattern matching (preview)<br>if (obj instanceof String str) {<br>    System.out.println(str.toUpperCase());<br>}<br><br>// More complex example<br>public String formatValue(Object obj) {<br>    return switch (obj) {<br>        case Integer i -&gt; &quot;Integer: &quot; + i;<br>        case String s -&gt; &quot;String: &quot; + s.toUpperCase();<br>        case Double d -&gt; &quot;Double: &quot; + String.format(&quot;%.2f&quot;, d);<br>        case null -&gt; &quot;null value&quot;;<br>        default -&gt; &quot;Unknown type: &quot; + obj.getClass().getSimpleName();<br>    };<br>}</pre><h3>Java 15 (September 2020)</h3><h4>1. Text Blocks (Standard)</h4><ul><li>Text blocks became a standard feature with additional formatting options.</li></ul><pre>public class HtmlGenerator {<br>    public String generateUserCard(User user) {<br>        return &quot;&quot;&quot;<br>            &lt;div class=&quot;user-card&quot;&gt;<br>                &lt;h2&gt;%s&lt;/h2&gt;<br>                &lt;p&gt;Age: %d&lt;/p&gt;<br>                &lt;p&gt;Email: %s&lt;/p&gt;<br>            &lt;/div&gt;<br>            &quot;&quot;&quot;.formatted(user.getName(), user.getAge(), user.getEmail());<br>    }<br>}</pre><h4><strong>2. Sealed Classes (Preview)</strong></h4><ul><li>Sealed classes provide controlled inheritance.</li><li>Restrict which other classes or interfaces may extend or implement them.</li></ul><pre>sealed interface Shape permits Circle, Square {}<br>final class Circle implements Shape {}<br>final class Square implements Shape {}</pre><pre>// Sealed class definition<br>public sealed class Shape <br>    permits Circle, Rectangle, Triangle {<br>    // Common shape methods<br>}<br><br>public final class Circle extends Shape {<br>    private final double radius;<br>    <br>    public Circle(double radius) {<br>        this.radius = radius;<br>    }<br>    <br>    public double area() {<br>        return Math.PI * radius * radius;<br>    }<br>}<br><br>public final class Rectangle extends Shape {<br>    private final double width, height;<br>    <br>    public Rectangle(double width, double height) {<br>        this.width = width;<br>        this.height = height;<br>    }<br>    <br>    public double area() {<br>        return width * height;<br>    }<br>}<br><br>// Usage with pattern matching<br>public double calculateArea(Shape shape) {<br>    return switch (shape) {<br>        case Circle c -&gt; c.area();<br>        case Rectangle r -&gt; r.area();<br>        case Triangle t -&gt; t.area();<br>    };<br>}</pre><h3>Java 16 (March 2021)</h3><h4><strong>1. Records (Standard)</strong></h4><ul><li>Finalized feature from preview.</li><li>Records provide a concise way to create data classes.</li></ul><pre>// Traditional class<br>public class PersonOld {<br>    private final String name;<br>    private final int age;<br>    <br>    public PersonOld(String name, int age) {<br>        this.name = name;<br>        this.age = age;<br>    }<br>    <br>    public String name() { return name; }<br>    public int age() { return age; }<br>    <br>    @Override<br>    public boolean equals(Object obj) {<br>        // ... boilerplate code<br>    }<br>    <br>    @Override<br>    public int hashCode() {<br>        // ... boilerplate code<br>    }<br>    <br>    @Override<br>    public String toString() {<br>        // ... boilerplate code<br>    }<br>}<br><br>// Record (much simpler!)<br>public record Person(String name, int age) {<br>    // Compact constructor for validation<br>    public Person {<br>        if (age &lt; 0) {<br>            throw new IllegalArgumentException(&quot;Age cannot be negative&quot;);<br>        }<br>    }<br>    <br>    // Additional methods can still be added<br>    public boolean isAdult() {<br>        return age &gt;= 18;<br>    }<br>}<br><br>// Usage<br>var person = new Person(&quot;Alice&quot;, 30);<br>System.out.println(person.name()); // Alice<br>System.out.println(person.age());  // 30<br>System.out.println(person.isAdult()); // true</pre><h4><strong>2. Pattern Matching for instanceof (Standard)</strong></h4><ul><li>Finalized and stable usage.</li></ul><pre>public void processValue(Object value) {<br>    if (value instanceof String str &amp;&amp; str.length() &gt; 5) {<br>        System.out.println(&quot;Long string: &quot; + str.toUpperCase());<br>    } else if (value instanceof Integer num &amp;&amp; num &gt; 0) {<br>        System.out.println(&quot;Positive number: &quot; + num);<br>    } else if (value instanceof List&lt;?&gt; list &amp;&amp; !list.isEmpty()) {<br>        System.out.println(&quot;Non-empty list with &quot; + list.size() + &quot; elements&quot;);<br>    }<br>}</pre><h3>Java 17 (September 2021 — LTS): LTS with Major Improvements</h3><p>Java 17 is the next LTS version after Java 11, bringing significant improvements.</p><h4><strong>1. Sealed Classes (Standard)</strong></h4><ul><li>Finalized and improved sealed class support.</li><li>Restricted class hierarchies for better control.</li></ul><pre>public sealed class Shape permits Circle, Square {}</pre><pre>public sealed interface Vehicle <br>    permits Car, Motorcycle, Bicycle {<br>    double getMaxSpeed();<br>}<br><br>public final class Car implements Vehicle {<br>    private final String model;<br>    private final double maxSpeed;<br>    <br>    public Car(String model, double maxSpeed) {<br>        this.model = model;<br>        this.maxSpeed = maxSpeed;<br>    }<br>    <br>    @Override<br>    public double getMaxSpeed() {<br>        return maxSpeed;<br>    }<br>}<br><br>public record Motorcycle(String brand, double maxSpeed) implements Vehicle {<br>    @Override<br>    public double getMaxSpeed() {<br>        return maxSpeed;<br>    }<br>}<br><br>// Pattern matching with sealed classes<br>public String getVehicleInfo(Vehicle vehicle) {<br>    return switch (vehicle) {<br>        case Car car -&gt; &quot;Car with max speed: &quot; + car.getMaxSpeed();<br>        case Motorcycle motorcycle -&gt; &quot;Motorcycle: &quot; + motorcycle.brand();<br>        case Bicycle bicycle -&gt; &quot;Bicycle with max speed: &quot; + bicycle.getMaxSpeed();<br>    };<br>}</pre><h4><strong>2. Pattern Matching for switch (Preview)</strong></h4><ul><li>Extends pattern matching to switch statements.</li></ul><pre>static String formatter(Object obj) {<br>    return switch (obj) {<br>        case Integer i -&gt; &quot;int: &quot; + i;<br>        case String s -&gt; &quot;string: &quot; + s;<br>        default -&gt; &quot;unknown&quot;;<br>    };<br>}</pre><h3>3. Enhanced Pseudo-Random Number Generators</h3><ul><li>Java 17 introduced new random number generator algorithms.</li></ul><pre>// Different PRNG algorithms<br>var random1 = RandomGenerator.of(&quot;L128X1024MixRandom&quot;);<br>var random2 = RandomGenerator.of(&quot;Xoshiro256PlusPlus&quot;);<br><br>// Stream of random integers<br>random1.ints(10, 1, 100)<br>    .forEach(System.out::println);<br><br>// Multiple streams<br>RandomGenerator.SplittableGenerator splittableRng = <br>    RandomGeneratorFactory.&lt;RandomGenerator.SplittableGenerator&gt;of(&quot;L128X1024MixRandom&quot;)<br>                          .create();<br><br>splittableRng.splits(4)<br>    .parallel()<br>    .forEach(rng -&gt; {<br>        // Each thread gets its own RNG<br>        System.out.println(Thread.currentThread().getName() + &quot;: &quot; + rng.nextInt());<br>    });</pre><pre>public class Java17Example {<br>    // Sealed class hierarchy<br>    sealed interface Shape permits Circle, Rectangle {<br>        double area();<br>    }<br><br>    final class Circle implements Shape {<br>        private final double radius;<br>        Circle(double radius) { this.radius = radius; }<br>        public double area() { return Math.PI * radius * radius; }<br>    }<br><br>    final class Rectangle implements Shape {<br>        private final double width, height;<br>        Rectangle(double width, double height) { this.width = width; this.height = height; }<br>        public double area() { return width * height; }<br>    }<br><br>    public static void main(String[] args) {<br>        // Pattern Matching for instanceof<br>        Shape shape = new Circle(5.0);<br>        if (shape instanceof Circle c) {<br>            System.out.println(&quot;Circle Area: &quot; + c.area());<br>        }<br><br>        // Text Block<br>        String json = &quot;&quot;&quot;<br>                      {<br>                          &quot;name&quot;: &quot;Java 17&quot;,<br>                          &quot;version&quot;: 17<br>                      }<br>                      &quot;&quot;&quot;;<br>        System.out.println(&quot;JSON:\n&quot; + json);<br>    }<br>}</pre><h3>Java 18 (March 2022)</h3><h4><strong>1. Simple Web Server</strong></h4><ul><li>Java 18 introduced a simple HTTP server for prototyping and testing.</li><li>Quickly serve static files from a directory.</li></ul><pre>$ jwebserver</pre><pre>// Create a simple file server<br>var server = SimpleFileServer.createFileServer(<br>    new InetSocketAddress(8080),<br>    Path.of(&quot;./public&quot;),<br>    SimpleFileServer.OutputLevel.VERBOSE<br>);<br><br>server.start();<br>System.out.println(&quot;Server started at http://localhost:8080&quot;);<br><br>// Or create a programmatic server<br>var httpServer = HttpServer.create(new InetSocketAddress(8081), 0);<br>httpServer.createContext(&quot;/api/hello&quot;, exchange -&gt; {<br>    String response = &quot;Hello from Java 18!&quot;;<br>    exchange.sendResponseHeaders(200, response.length());<br>    try (var os = exchange.getResponseBody()) {<br>        os.write(response.getBytes());<br>    }<br>});<br>httpServer.start();</pre><ol><li><strong>UTF-8 as Default Charset</strong></li></ol><ul><li>Java 18 made UTF-8 the default charset, improving consistency across platforms.</li><li>All APIs that depend on default charset now use UTF-8.</li></ul><pre>Files.readString(Path.of(&quot;file.txt&quot;)); // UTF-8 by default</pre><pre>// These now use UTF-8 by default on all platforms<br>Files.readString(Path.of(&quot;file.txt&quot;)); // UTF-8<br>Files.writeString(Path.of(&quot;output.txt&quot;), &quot;Hello 🌍&quot;); // UTF-8<br><br>// FileReader/FileWriter also use UTF-8 by default<br>try (var reader = new FileReader(&quot;input.txt&quot;)) {<br>    // Reads using UTF-8<br>}</pre><h3>Java 19 (September 2022)</h3><h4><strong>Virtual Threads (Preview)</strong></h4><ul><li>Virtual threads revolutionize concurrent programming by providing lightweight threads.</li><li>Lightweight threads to enable high-concurrency applications.</li></ul><pre>Thread.startVirtualThread(() -&gt; System.out.println(&quot;Hello from virtual thread&quot;));</pre><pre>// Traditional thread approach (limited scalability)<br>public void traditionalThreads() {<br>    ExecutorService executor = Executors.newFixedThreadPool(100);<br>    <br>    for (int i = 0; i &lt; 10000; i++) {<br>        final int taskId = i;<br>        executor.submit(() -&gt; {<br>            // Simulate I/O operation<br>            try {<br>                Thread.sleep(1000);<br>                System.out.println(&quot;Task &quot; + taskId + &quot; completed&quot;);<br>            } catch (InterruptedException e) {<br>                Thread.currentThread().interrupt();<br>            }<br>        });<br>    }<br>}<br><br>// Virtual threads approach (massive scalability)<br>public void virtualThreads() {<br>    try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {<br>        for (int i = 0; i &lt; 1_000_000; i++) { // 1 million tasks!<br>            final int taskId = i;<br>            executor.submit(() -&gt; {<br>                try {<br>                    Thread.sleep(Duration.ofSeconds(1));<br>                    System.out.println(&quot;Virtual task &quot; + taskId + &quot; completed&quot;);<br>                } catch (InterruptedException e) {<br>                    Thread.currentThread().interrupt();<br>                }<br>            });<br>        }<br>    }<br>}<br><br>// HTTP server with virtual threads<br>public void virtualThreadServer() throws IOException {<br>    var server = HttpServer.create(new InetSocketAddress(8080), 0);<br>    server.createContext(&quot;/&quot;, exchange -&gt; {<br>        // Each request runs on a virtual thread<br>        Thread.startVirtualThread(() -&gt; {<br>            try {<br>                // Simulate database call<br>                Thread.sleep(Duration.ofMillis(100));<br>                String response = &quot;Hello from virtual thread: &quot; + Thread.currentThread();<br>                exchange.sendResponseHeaders(200, response.length());<br>                exchange.getResponseBody().write(response.getBytes());<br>                exchange.close();<br>            } catch (Exception e) {<br>                e.printStackTrace();<br>            }<br>        });<br>    });<br>    server.start();<br>}</pre><h4><strong>2. Structured Concurrency (Incubator)</strong></h4><ul><li>Simplifies managing related concurrent tasks.</li></ul><h3>Java 20 (March 2023)</h3><h4><strong>1. Scoped Values (Incubator)</strong></h4><ul><li>Scoped values provide an alternative to ThreadLocal with better performance and clarity.</li><li>Aimed at safely and efficiently sharing immutable data across threads.</li></ul><pre>public class UserService {<br>    private static final ScopedValue&lt;User&gt; CURRENT_USER = ScopedValue.newInstance();<br>    <br>    public void processRequest(User user) {<br>        ScopedValue.where(CURRENT_USER, user)<br>                   .run(() -&gt; {<br>                       // Current user is available throughout the scope<br>                       businessLogic();<br>                   });<br>    }<br>    <br>    private void businessLogic() {<br>        auditLog();<br>        performOperation();<br>    }<br>    <br>    private void auditLog() {<br>        User currentUser = CURRENT_USER.get();<br>        System.out.println(&quot;Operation performed by: &quot; + currentUser.getName());<br>    }<br>    <br>    private void performOperation() {<br>        User currentUser = CURRENT_USER.get();<br>        // Perform operation with current user context<br>    }<br>}</pre><h4>Vector API (Fourth Incubator)</h4><ul><li>The Vector API enables SIMD (Single Instruction, Multiple Data) operations.</li></ul><pre>// Traditional scalar computation<br>public void scalarAddition(float[] a, float[] b, float[] result) {<br>    for (int i = 0; i &lt; a.length; i++) {<br>        result[i] = a[i] + b[i];<br>    }<br>}<br><br>// Vector API computation (much faster on supported hardware)<br>public void vectorAddition(float[] a, float[] b, float[] result) {<br>    var species = FloatVector.SPECIES_PREFERRED;<br>    int upperBound = species.loopBound(a.length);<br>    <br>    for (int i = 0; i &lt; upperBound; i += species.length()) {<br>        var va = FloatVector.fromArray(species, a, i);<br>        var vb = FloatVector.fromArray(species, b, i);<br>        var vc = va.add(vb);<br>        vc.intoArray(result, i);<br>    }<br>    <br>    // Handle remaining elements<br>    for (int i = upperBound; i &lt; a.length; i++) {<br>        result[i] = a[i] + b[i];<br>    }<br>}</pre><h4><strong>Pattern Matching Enhancements</strong></h4><ul><li>Further improves usability and expressiveness.</li></ul><h3>Java 21 (September 2023 — LTS)</h3><p>Java 21 is the latest LTS version, bringing several preview features to standard status.</p><h4><strong>1. Virtual Threads (Standard)</strong></h4><ul><li>Final and ready for production. Virtual threads became a standard feature, revolutionizing concurrent programming.</li><li>Simplified concurrent programming with lightweight threads.</li><li>Lightweight concurrency.</li></ul><pre>// Virtual Threads<br>Runnable task = () -&gt; System.out.println(&quot;Running in virtual thread: &quot; + Thread.currentThread());<br>Thread virtualThread = Thread.ofVirtual().start(task);<br>virtualThread.join();</pre><pre>Thread.startVirtualThread(() -&gt; System.out.println(&quot;Running in a virtual thread!&quot;));</pre><pre>public class WebCrawler {<br>    public List&lt;String&gt; crawlUrls(List&lt;String&gt; urls) {<br>        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {<br>            List&lt;Future&lt;String&gt;&gt; futures = urls.stream()<br>                .map(url -&gt; executor.submit(() -&gt; fetchContent(url)))<br>                .toList();<br>            <br>            return futures.stream()<br>                .map(future -&gt; {<br>                    try {<br>                        return future.get();<br>                    } catch (Exception e) {<br>                        return &quot;Error: &quot; + e.getMessage();<br>                    }<br>                })<br>                .toList();<br>        }<br>    }<br>    <br>    private String fetchContent(String url) {<br>        // Simulate HTTP request<br>        try {<br>            Thread.sleep(Duration.ofMillis(100));<br>            return &quot;Content from &quot; + url;<br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>            return &quot;Interrupted&quot;;<br>        }<br>    }<br>}</pre><h4><strong>2. Pattern Matching for switch (Standard)</strong></h4><ul><li>Finalized syntax and full support.</li><li>Advanced pattern matching for switch statements became standard.</li></ul><pre>public class MessageProcessor {<br>    public String processMessage(Object message) {<br>        return switch (message) {<br>            case String s when s.startsWith(&quot;ERROR&quot;) -&gt; &quot;Handling error: &quot; + s;<br>            case String s when s.startsWith(&quot;WARN&quot;) -&gt; &quot;Warning logged: &quot; + s;<br>            case String s -&gt; &quot;Info: &quot; + s;<br>            case Integer i when i &lt; 0 -&gt; &quot;Negative number: &quot; + i;<br>            case Integer i -&gt; &quot;Positive number: &quot; + i;<br>            case List&lt;?&gt; list when list.isEmpty() -&gt; &quot;Empty list&quot;;<br>            case List&lt;?&gt; list -&gt; &quot;List with &quot; + list.size() + &quot; elements&quot;;<br>            case null -&gt; &quot;Null message&quot;;<br>            default -&gt; &quot;Unknown message type&quot;;<br>        };<br>    }<br>}</pre><h4>3. Record Patterns</h4><ul><li>Record patterns enable pattern matching with records.</li></ul><pre>record Person(String name, int age) {}<br><br>// Record Pattern Matching<br>Object obj = new Person(&quot;Alice&quot;, 30);<br>if (obj instanceof Person(String name, int age)) {<br>    System.out.println(&quot;Person: &quot; + name + &quot;, Age: &quot; + age);<br>}</pre><pre>public record Point(int x, int y) {}<br>public record ColoredPoint(Point point, String color) {}<br><br>public class PatternMatchingExample {<br>    public String analyzePoint(Object obj) {<br>        return switch (obj) {<br>            case Point(int x, int y) when x == 0 &amp;&amp; y == 0 -&gt; &quot;Origin&quot;;<br>            case Point(int x, int y) when x == y -&gt; &quot;Diagonal point (&quot; + x + &quot;,&quot; + y + &quot;)&quot;;<br>            case Point(int x, int y) -&gt; &quot;Point at (&quot; + x + &quot;,&quot; + y + &quot;)&quot;;<br>            case ColoredPoint(Point(int x, int y), String color) -&gt; <br>                color + &quot; point at (&quot; + x + &quot;,&quot; + y + &quot;)&quot;;<br>            default -&gt; &quot;Not a point&quot;;<br>        };<br>    }<br>    <br>    // Pattern matching in methods<br>    public double distance(Point p1, Point p2) {<br>        return switch (p1) {<br>            case Point(int x1, int y1) -&gt; switch (p2) {<br>                case Point(int x2, int y2) -&gt; <br>                    Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));<br>            };<br>        };<br>    }<br>}</pre><h4>4. Sequenced Collections</h4><ul><li>Introduces SequencedCollection for collections with a defined sequence.</li></ul><pre>SequencedSet&lt;String&gt; set = new LinkedHashSet&lt;&gt;(List.of(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;));<br>System.out.println(set.first()); // Output: A<br>System.out.println(set.last());  // Output: C</pre><h4><strong>5. String Templates (Preview)</strong></h4><ul><li>Adds inline interpolation within strings.</li></ul><pre>String name = &quot;John&quot;;<br>String greeting = STR.&quot;Hello, \{name}!&quot;;</pre><h3>Java 22 (March 2024)</h3><h4>1. Foreign Function &amp; Memory API (Preview)</h4><p>The Foreign Function &amp; Memory API enables safe and efficient access to native code and memory.</p><pre>// Calling native C functions<br>public class NativeInterop {<br>    public void callNativeFunction() {<br>        try (var arena = Arena.ofConfined()) {<br>            // Find the C library function<br>            var linker = Linker.nativeLinker();<br>            var lookup = SymbolLookup.loaderLookup();<br>            <br>            var strlen = linker.downcallHandle(<br>                lookup.find(&quot;strlen&quot;).orElseThrow(),<br>                FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS)<br>            );<br>            <br>            // Allocate native string<br>            var cString = arena.allocateUtf8String(&quot;Hello, native world!&quot;);<br>            <br>            // Call strlen<br>            long length = (long) strlen.invoke(cString);<br>            System.out.println(&quot;String length: &quot; + length);<br>        } catch (Throwable e) {<br>            e.printStackTrace();<br>        }<br>    }<br>    <br>    // Working with native memory<br>    public void memoryOperations() {<br>        try (var arena = Arena.ofConfined()) {<br>            // Allocate native memory<br>            var segment = arena.allocate(1024);<br>            <br>            // Write data<br>            for (int i = 0; i &lt; 256; i++) {<br>                segment.set(ValueLayout.JAVA_INT, i * 4, i);<br>            }<br>            <br>            // Read data<br>            for (int i = 0; i &lt; 10; i++) {<br>                int value = segment.get(ValueLayout.JAVA_INT, i * 4);<br>                System.out.println(&quot;Value at &quot; + i + &quot;: &quot; + value);<br>            }<br>        }<br>    }<br>}</pre><h4>2. Unnamed Variables and Patterns</h4><p>Unnamed variables (using underscore) improve code readability when variables aren’t used.</p><pre>public class UnnamedVariables {<br>    // Unused lambda parameters<br>    list.stream()<br>        .map((_, index) -&gt; &quot;Item &quot; + index) // Only index is used<br>        .collect(Collectors.toList());<br>    <br>    // Unused catch parameters<br>    try {<br>        riskyOperation();<br>    } catch (IOException _) {<br>        // Don&#39;t need the exception details<br>        System.err.println(&quot;IO operation failed&quot;);<br>    }<br>    <br>    // Pattern matching with unused components<br>    public String processOrder(Object order) {<br>        return switch (order) {<br>            case Order(_, var total, _) when total &gt; 1000 -&gt; &quot;Large order&quot;;<br>            case Order(var id, _, var date) -&gt; &quot;Order &quot; + id + &quot; on &quot; + date;<br>            default -&gt; &quot;Unknown order&quot;;<br>        };<br>    }<br>}</pre><h4><strong>3. Classfile API (Preview)</strong></h4><ul><li>Programmatically inspect and generate class files.</li></ul><h4><strong>4. Statement Templates (Incubator)</strong></h4><ul><li>Enables parameterized code generation.</li></ul><h3>Java 23 (September 2024)</h3><h4>1. Primitive Patterns in Switch (Preview)</h4><p>Pattern matching now works with primitive types in switch expressions.</p><pre>public class PrimitivePatterns {<br>    public String categorizeNumber(int number) {<br>        return switch (number) {<br>            case int i when i &lt; 0 -&gt; &quot;Negative: &quot; + i;<br>            case 0 -&gt; &quot;Zero&quot;;<br>            case int i when i &gt; 0 &amp;&amp; i &lt;= 10 -&gt; &quot;Small positive: &quot; + i;<br>            case int i when i &gt; 10 &amp;&amp; i &lt;= 100 -&gt; &quot;Medium positive: &quot; + i;<br>            case int i -&gt; &quot;Large positive: &quot; + i;<br>        };<br>    }<br>    <br>    public String analyzeScore(double score) {<br>        return switch (score) {<br>            case double d when d &lt; 0.0 || d &gt; 100.0 -&gt; &quot;Invalid score&quot;;<br>            case double d when d &gt;= 90.0 -&gt; &quot;Excellent (&quot; + d + &quot;)&quot;;<br>            case double d when d &gt;= 80.0 -&gt; &quot;Good (&quot; + d + &quot;)&quot;;<br>            case double d when d &gt;= 70.0 -&gt; &quot;Satisfactory (&quot; + d + &quot;)&quot;;<br>            case double d -&gt; &quot;Needs improvement (&quot; + d + &quot;)&quot;;<br>        };<br>    }<br>}</pre><h4>2. Module Import Declarations (Preview)</h4><p>Simplified imports for modules reduce boilerplate in module-based applications.</p><pre>// module-info.java<br>module com.example.app {<br>    requires java.base;<br>    requires java.logging;<br>    requires java.net.http;<br>    <br>    // Module import - imports all exported packages<br>    import module java.util.concurrent;<br>    import module com.example.utils;<br>}<br><br>// In regular Java files, you can now use classes without explicit imports<br>public class Application {<br>    public void run() {<br>        // These classes are available due to module imports<br>        var executor = new ThreadPoolExecutor(/*...*/);<br>        var future = CompletableFuture.supplyAsync(/*...*/);<br>        <br>        // Utility classes from imported modules<br>        var helper = new StringHelper(); // from com.example.utils<br>    }<br>}</pre><h4><strong>3. Enhanced Value Classes (Preview)</strong></h4><ul><li>Improves support for immutable value types with low memory overhead.</li></ul><h4><strong>4. Concurrency Enhancements</strong></h4><ul><li>More utilities for structured and parallel programming.</li></ul><h3>Java 24 (March 2025)</h3><h4>1. Structured Concurrency (Preview)</h4><ul><li>Structured concurrency provides a cleaner way to manage concurrent operations.</li><li>Provides better lifecycle and error handling for related threads.</li></ul><pre>public class StructuredConcurrencyExample {<br>    public UserProfile getUserProfile(String userId) {<br>        try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {<br>            // Launch concurrent tasks<br>            Future&lt;User&gt; userFuture = scope.fork(() -&gt; fetchUser(userId));<br>            Future&lt;List&lt;Order&gt;&gt; ordersFuture = scope.fork(() -&gt; fetchUserOrders(userId));<br>            Future&lt;List&lt;Address&gt;&gt; addressesFuture = scope.fork(() -&gt; fetchUserAddresses(userId));<br>            <br>            // Wait for all tasks to complete<br>            scope.join();<br>            scope.throwIfFailed();<br>            <br>            // Combine results<br>            return new UserProfile(<br>                userFuture.resultNow(),<br>                ordersFuture.resultNow(),<br>                addressesFuture.resultNow()<br>            );<br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>            throw new RuntimeException(&quot;Operation interrupted&quot;, e);<br>        } catch (ExecutionException e) {<br>            throw new RuntimeException(&quot;Operation failed&quot;, e.getCause());<br>        }<br>    }<br>    <br>    private User fetchUser(String userId) {<br>        // Simulate database call<br>        try { Thread.sleep(100); } catch (InterruptedException e) { /* */ }<br>        return new User(userId, &quot;John Doe&quot;);<br>    }<br>    <br>    private List&lt;Order&gt; fetchUserOrders(String userId) {<br>        try { Thread.sleep(150); } catch (InterruptedException e) { /* */ }<br>        return List.of(new Order(&quot;order1&quot;), new Order(&quot;order2&quot;));<br>    }<br>    <br>    private List&lt;Address&gt; fetchUserAddresses(String userId) {<br>        try { Thread.sleep(80); } catch (InterruptedException e) { /* */ }<br>        return List.of(new Address(&quot;123 Main St&quot;), new Address(&quot;456 Oak Ave&quot;));<br>    }<br>}</pre><h4>2. Stream Collectors Enhancement</h4><p>New collectors for common operations.</p><pre>public class CollectorsExample {<br>    public void demonstrateNewCollectors() {<br>        List&lt;Order&gt; orders = getOrders();<br>        <br>        // Collecting to reversed list<br>        List&lt;Order&gt; reversedOrders = orders.stream()<br>            .collect(Collectors.toReversedList());<br>        <br>        // Collecting with enumeration<br>        Map&lt;Integer, Order&gt; enumeratedOrders = orders.stream()<br>            .collect(Collectors.toEnumeratedMap());<br>        <br>        // Teeing with custom combiner<br>        var result = orders.stream()<br>            .collect(Collectors.teeing(<br>                Collectors.counting(),<br>                Collectors.summingDouble(Order::getTotal),<br>                (count, sum) -&gt; new OrderSummary(count, sum)<br>            ));<br>    }<br>}</pre><h4>3. Performance and JVM Improvements</h4><p>Throughout these versions, the JVM has seen significant performance improvements:</p><h4>4. Garbage Collection Enhancements</h4><ul><li><strong>G1GC improvements</strong> (Java 9–24): Better pause times and throughput</li><li><strong>ZGC</strong> (Java 11+): Ultra-low latency garbage collector</li><li><strong>Shenandoah</strong> (Java 12+): Low-pause collector</li><li><strong>Generational ZGC</strong> (Java 21+): Even better performance for typical workloads</li></ul><h4>5. JIT Compilation</h4><ul><li><strong>Graal compiler</strong> integration</li><li><strong>Profile-guided optimization</strong> improvements</li><li><strong>Ahead-of-time compilation</strong> with GraalVM Native Image</li></ul><h4>6. JVM Startup and Memory</h4><ul><li>Faster startup times across all versions</li><li><strong>Application Class-Data Sharing</strong> (AppCDS)</li><li><strong>Compact Strings</strong> (Java 9+): 20–30% memory reduction for String storage</li><li><strong>Multi-Release JARs</strong>: Single JAR supporting multiple Java versions</li></ul><h4><strong>7. Immutable Data Structures</strong></h4><ul><li>Expected to support enhanced syntax or types for immutability.</li></ul><h4><strong>8. Universal Generics (Potential)</strong></h4><ul><li>Might introduce support for more flexible and type-safe generics.</li></ul><h3>Conclusion</h3><p>The evolution from Java 8 to Java 24 represents a remarkable transformation in the Java ecosystem. Key highlights include:</p><h4><strong>Major Paradigm Shifts:</strong></h4><ul><li><strong>Functional Programming</strong> (Java 8): Lambda expressions and Stream API</li><li><strong>Modularity</strong> (Java 9): Module system for better application structure</li><li><strong>Data-Oriented Programming</strong> (Java 14–16): Records and pattern matching</li><li><strong>Concurrent Programming Revolution</strong> (Java 19–21): Virtual threads changing scalability limits</li></ul><h4><strong>Performance Improvements:</strong></h4><ul><li>Significant JVM optimizations across all versions</li><li>Better garbage collection (G1, ZGC, Shenandoah)</li><li>Startup time improvements with AppCDS and CRaC</li><li>Memory efficiency with compact strings and improved algorithms</li></ul><h4><strong>Developer Experience Enhancements:</strong></h4><ul><li>Reduced boilerplate with records, var, and text blocks</li><li>More expressive code with pattern matching and switch expressions</li><li>Better tooling with JShell and enhanced debugging capabilities</li><li>Simplified deployment with single-file source code programs</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9901c859fa6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>