Pattern Matching in Java 21 — this one quietly changed how we write Java. Before Java 21, checking and casting an object looked like this: if (obj instanceof String) { String s = (String) obj; System.out.println(s.toUpperCase()); } With Java 21 pattern matching for instanceof: if (obj instanceof String s) { System.out.println(s.toUpperCase()); } One line. No explicit cast. The variable s is already scoped and typed. But the real power is in pattern matching for switch (JEP 441): String result = switch (obj) { case Integer i -> "Integer: " + i; case String s -> "String: " + s; case null -> "null value"; default -> "Something else"; }; This is now stable in Java 21. It replaces chains of if-instanceof-cast that every Java developer has written a hundred times. It's also a key topic in the 1Z0-830 Oracle Java SE 21 exam. Our Java 21 OCP Exam Cram Course covers this and all 14 exam objectives — 40 hours (5 days), monthly, Woodmead JHB + online. 📋https://lnkd.in/dJYmDVqP #Java21 #PatternMatching #JavaDeveloper #OracleJava #1Z0830 #CodeCollege #JavaCertification #CleanCode #SouthAfricaTech
Java 21 Pattern Matching Simplifies Code
More Relevant Posts
-
💻 Exploring Java Data Types & Literals While revisiting Java fundamentals, I explored how literals work with different data types. Literals are fixed values assigned directly in code, and Java provides some interesting ways to use them. 📌 Here are some useful things I learned: 🔹 Binary Literal (Base 2) We can write numbers in binary using 0b Example: int num = 0b101; // Output: 5 🔹 Hexadecimal Literal (Base 16) We can use 0x to represent hexadecimal values Example: int num2 = 0x7E; // Output: 126 🔹 Using Underscore for Readability Underscores can be used to make large numbers more readable Example: int num3 = 10_00_000; // Output: 1000000 🔹 Scientific Notation (e-notation) Used to represent large values in floating-point numbers Example: double numd = 12e10; 🔹 Character Increment Trick Characters in Java are internally stored as numbers (ASCII/Unicode), so we can increment them: Example: char c = 'a'; c++; // Output: 'b' 📌 In simple terms: These features make Java code more readable and also reveal how data is handled internally. Continuing to strengthen my Java fundamentals step by step 🚀 #Java #Programming #LearningJourney #JavaBasics #BackendDevelopment
To view or add a comment, sign in
-
-
Hello Connections, Post 14 — Java Fundamentals A-Z This looks correct… but gives a completely wrong result 😵 Can you spot the bug? 👇 int a = 1_000_000; int b = 1_000_000; int result = a * b; System.out.println(result); // 💀 -727379968 Wait… what? 1,000,000 × 1,000,000 should be 1,000,000,000,000 right? But Java prints a negative number! 😱 Here’s what’s happening 👇 • int can store values only up to 2,147,483,647 • The result exceeds this limit • Java silently overflows and wraps around ⚠️ No error. No warning. Just wrong data. This is called integer overflow. Here’s the fix 👇 long result = (long) a * b; System.out.println(result); // ✅ 1000000000000 Post 14 Summary: 🔴 Unlearned → Assuming int is always safe for calculations 🟢 Relearned → Use long when dealing with large numbers to avoid overflow Have you ever faced this in real scenarios? Drop a ⚠️ below! Follow along for more Java & backend concepts 👇 #Java #JavaFundamentals #BackendDevelopment #LearningInPublic #SDE2
To view or add a comment, sign in
-
-
☕ Java 26 — JEP 500: Prepare to make final mean final class C { final int x; C() {x = 100;} } static void main() throws NoSuchFieldException, IllegalAccessException { var f = C.class.getDeclaredField( "x" ); f.setAccessible( true ); var obj = new JEP500().new C(); IO.println( obj.x ); f.set( obj, 200 ); IO.println( obj.x ); /*output: 100 200 WARNING: Final field x in class com.vv.JEP500$C has been mutated ... WARNING: Use --enable-final-field-mutation=ALL-UNNAMED ... WARNING: Mutating final fields will be blocked in a future release .... */ } • JDK 26 starts warning about deep reflection that mutates final fields. • This prepares the ecosystem for a future release where such mutation is denied by default. • For developers, the action item is simple: run tests, find reflection-heavy libraries, and see who still breaks final. #java #java26 #final Go further with Java certification: Java👇 https://bit.ly/javaOCP Spring👇 https://bit.ly/2v7222 SpringBook👇 https://bit.ly/springtify JavaBook👇 https://bit.ly/jroadmap
To view or add a comment, sign in
-
Day 03 — Also learned something in Java today that I never even heard of before. Tokens. Yeah. Tokens. Let me explain it simply because when I first saw the word I thought it was something complicated. It's actually pretty cool. What is a Token in Java? A Token is the smallest unit in a Java program. Like when you write a sentence — the smallest unit is a word, right? In Java, when the compiler reads your code — it breaks everything down into small pieces called Tokens. There are 5 types of Tokens in Java: 1. Keywords — Reserved words Java already knows Example: `int`, `class`, `if`, `return` 2. Identifiers— Names YOU give to variables, methods, classes Example: `myName`, `totalMarks` 3. Literals— Actual values written in code Example: `10`, `"Hello"`, `true` 4. Operators— Symbols that perform operations Example: `+`, `-`, `=`, `>` **5. Separators** — Punctuation that structures code Example: `{ }`, `( )`, `;` So when you write even one simple line like: `int age = 21;` The compiler sees — a keyword, an identifier, an operator, a literal, and a separator. That one line has 5 tokens. Honestly these small concepts are building my foundation and I am not rushing it anymore. Are you also learning Java? Let me know where you are #Day11 #JavaLearning #JavaBasics #Tokens #QAJourney #ManualTesting #LearningInPublic #BeginnersInTech #SoftwareTesting
To view or add a comment, sign in
-
A Simple Way to Understand JDK, JRE, and JVM When I started learning Java, the terms JDK, JRE, and JVM sounded confusing. But once I understood how they work together, everything became clear. Think of Java like building and running a program in three steps. 🔧 JDK (Java Development Kit) – The developer's toolbox It contains tools needed to write and compile Java programs, such as the "javac" compiler. ⚙️ JRE (Java Runtime Environment) – The environment to run Java programs It includes libraries and the JVM, which are required to execute Java applications. 🧠 JVM (Java Virtual Machine) – The engine that runs Java code It executes the bytecode and makes Java platform-independent. 📌 How it actually works "Hello.java" compiled by "javac" "Hello.class" (bytecode) executed by JVM Example: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, Java!"); } } You write the code once, compile it using the JDK, and the JVM runs it on any system with Java installed. That’s why Java follows the principle: Write Once, Run Anywhere. Learning how Java works internally makes programming even more interesting. 🚀 #Java #Programming #JDK #JRE #JVM #SoftwareDevelopment #LearningInPublic
To view or add a comment, sign in
-
-
In Java versions below 24 virtual threads can pin their carrier platform threads during synchronized blocks or native calls. This prevents the carrier from executing other tasks leading to thread starvation and sub-optimal resource usage. Interesting article on differences between Java 21 and Java 24 in terms how they handle virtual thread pinning. https://lnkd.in/dPpsDYHH
To view or add a comment, sign in
-
Java is quietly becoming more expressive This is not the Java you learned 5 years ago. Modern Java (21 → 25) is becoming much more concise and safer. 🧠 Old Java if (obj instanceof User) { User user = (User) obj; return user.getName(); } else if (obj instanceof Admin) { Admin admin = (Admin) obj; return admin.getRole(); } 👉 verbose 👉 error-prone 👉 easy to forget cases 🚀 Modern Java return switch (obj) { case User user -> user.getName(); case Admin admin -> admin.getRole(); default -> throw new IllegalStateException(); }; ⚡ Even better with sealed classes Java sealed interface Account permits User, Admin {} 👉 Now the compiler knows all possible types 👉 and forces you to handle them 💥 Why this matters less boilerplate safer code (exhaustive checks) fewer runtime bugs 👉 the compiler does more work for you ⚠️ What I still see in real projects old instanceof patterns manual casting everywhere missing edge cases 🧠 Takeaway Modern Java is not just about performance. It’s about writing safer and cleaner code. 🔍 Bonus Once your code is clean, the next challenge is making it efficient. That’s what I focus on with: 👉 https://joptimize.io Are you still writing Java 8-style code in 2025? #JavaDev #Java25 #Java21 #CleanCode #Backend #SoftwareEngineering
To view or add a comment, sign in
-
🔍☕ GUESS THE JAVA VERSION: CAN YOU SPOT THE CLUE? (HASHMAP) 🔸 THE CHALLENGE Here is a small Java code snippet. Your mission: guess the earliest Java version that supports it. 👇 import java.util.HashMap; class Example { class Entry { HashMap map = new HashMap(); } } Which one is correct? 🤔 ▪️ Java 1.1 ▪️ Java 1.2 ▪️ Java 1.3 ▪️ Java 15 ▪️ Java 17 🔸 BEFORE YOU CHECK THE ANSWER This question looks simple, but it tests something important: ▪️ your knowledge of Java history ▪️ your ability to spot library clues ▪️ your understanding of old language features The trap here is that the code uses two old Java concepts: ▪️ an inner class ▪️ HashMap from the Collections Framework One of these appeared earlier. The other one gives the real answer. 🎯 🔸 ANSWER ✅ Java 1.2 🔸 TLDR HashMap is the feature that gives the answer away. Inner classes were already available in Java 1.1, but HashMap arrived with the Collections Framework in Java 1.2. So the earliest valid answer is Java 1.2. ✅ 🔸 WHY THIS IS THE RIGHT ANSWER The key clue is HashMap. HashMap became part of Java when the Collections Framework was introduced in Java 1.2. So even though the code also uses an inner class, that does not decide the answer. Why? ▪️ Inner classes were added in Java 1.1 ▪️ HashMap was added in Java 1.2 That means this code could not compile in Java 1.1, because HashMap did not exist there yet. So the earliest correct answer is: 👉 Java 1.2 🔸 TAKEAWAYS ▪️ HashMap was introduced in Java 1.2 ▪️ Inner classes were introduced in Java 1.1 Would you have picked Java 1.2 on the first try? 👀 #Java #JavaDeveloper #Programming #SoftwareEngineering #Coding #TechQuiz #JavaQuiz #LearnJava #DeveloperSkills #CodeNewbie #OracleJava #JavaHistory Go further with Java certification: Java👇 https://bit.ly/javaOCP Spring👇 https://bit.ly/2v7222 SpringBook👇 https://bit.ly/springtify JavaBook👇 https://bit.ly/jroadmap
To view or add a comment, sign in
-
-
🚀 Java 25 is bringing some seriously exciting improvements I’ve published a blog post where I break down the key features you should know about in Java 25👇 🔍 Here’s a quick preview of what’s inside: 🧩 Primitive Types in Patterns (JEP 507) Pattern matching gets even more powerful by supporting primitive types - making your code more expressive and reducing boilerplate. 📦 Module Import Declarations (JEP 511) Simplifies module usage with cleaner import syntax, helping you write more readable and maintainable modular applications. ⚡ Compact Source Files & Instance Main (JEP 512) A big win for simplicity! You can write shorter programs without the usual ceremony - perfect for beginners and quick scripts. 🛠️ Flexible Constructor Bodies (JEP 513) Constructors become more flexible, giving developers better control over initialization logic and improving code clarity. 🔒 Scoped Values (JEP 506) A modern alternative to thread-local variables, designed for safer and more efficient data sharing in concurrent applications. 🧱 Stable Values (JEP 502) Helps manage immutable data more efficiently, improving performance and reliability in multi-threaded environments. 🧠 Compact Object Headers (JEP 519) Optimizes memory usage by reducing object header size - a huge benefit for high-performance and memory-sensitive applications. 🚄 Vector API (JEP 508) Enables developers to leverage modern CPU instructions for parallel computations - boosting performance for data-heavy workloads. 💡 Whether you're focused on performance, cleaner syntax, or modern concurrency, Java 25 delivers meaningful improvements across the board. 👇 Curious to learn more? Check the link of full article in my comment. #Java #Java25 #SoftwareDevelopment #Programming #Developers #Tech #JVM #Coding #Performance #Concurrency
To view or add a comment, sign in
-
-
Java Strings have evolved a lot across different versions. From the classic String API in Java 8 to Text Blocks and modern improvements in newer releases, Java has become more expressive and developer-friendly. * Java 8 gave us a strong foundation. * Java 9 improved performance with Compact Strings. * Java 11 brought practical methods like isBlank(), strip(), lines(), and repeat(). * Java 15 made multiline text much cleaner with Text Blocks. * Java 17 became a stable LTS baseline. * Java 21 introduced String Templates as a preview feature. This evolution shows how Java continues to improve not only performance, but also readability and developer productivity. Small language improvements can make a big difference in everyday coding.
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
I love Java! Nice to see how Java evolved over the years, staying right at the top!