5 Modern Java Features to Boost Your Code

Java 26 just dropped! But most developers have not even adopted Java 21 features yet.  Here are 5 modern Java features you should be using every single day. —— 1. Switch Expressions: clean and exhaustive (Java 14+) // Before: verbose, fall-through prone String label; switch (status) {  case ACTIVE: label = "Active"; break;  case PENDING: label = "Pending"; break;  default:   label = "Unknown"; } // After: String label = switch (status) {  case ACTIVE -> "Active";  case PENDING -> "Pending";  default   -> "Unknown"; }; No fall-through bugs. Compiler ensures all cases are handled. —— 2. Text Blocks: readable multiline strings (Java 15+) // Before: String json = "{\n \"name\": \"Alice\",\n \"role\": \"admin\"\n}"; // After: String json = """   {    "name": "Alice",    "role": "admin"   }   """; Clean SQL, JSON, HTML — no escape characters. Just readable strings. —— 3. Optional: use it properly (Java 8+, daily practice) // Bad: Optional user = userRepo.findById(id); if (user.isPresent()) { return user.get(); } return null; // Good: return userRepo.findById(id)  .orElseThrow(() -> new UserNotFoundException("User not found: " + id)); Optional exists to eliminate null checks — not to wrap them. Never use .get() alone. Always orElseThrow() or orElse(). —— 4. Pattern Matching for Switch: Java 21 flagship (Java 21) // Before: fragile instanceof chain if (obj instanceof Integer i) return "int: " + i; if (obj instanceof String s) return "str: " + s; // After: clean, compiler-verified return switch (obj) {  case Integer i -> "int: " + i;  case String s -> "str: " + s;  default    -> "unknown"; }; // Even better with guards: return switch (order) {  case Order o when o.isPaid()  -> "Paid";  case Order o when o.isPending() -> "Pending";  default             -> "Unknown"; }; Replaces entire if-instanceof chains. Safe, readable, exhaustive. —— 5. New String methods: small but mighty (Java 11–17) input.strip();          // Unicode-aware trim() input.isBlank();         // true if empty or whitespace input.repeat(3);         // repeats string N times "line1\nline2".lines();      // Stream by line "hello %s".formatted("world");  // cleaner than String.format() No libraries needed. Used constantly. Zero excuses not to. ---------------------------------------------------------------- Java is not the verbose language it used to be. Pick one feature. Use it in your next PR. Then the next one. Java 26 post coming next. Stay tuned! Which one are you already using daily? Drop a number below.. #Java #Java17 #Java21 #BackendDevelopment #SpringBoot #SoftwareEngineering #CleanCode

To view or add a comment, sign in

Explore content categories