🚀 15 Days of Java 8 – #Day11: Using `Optional` Correctly What is wrong with this common misuse of the `Optional` class? //--- Anti-Pattern --- Optional<String> name = findName(); if (name.isPresent()) { System.out.println(name.get()); } //------------------- ✅ Answer: While this code works, it's considered an anti-pattern because it's not much better than a simple `if (name != null)` check. It doesn't use the expressive, functional style that `Optional` was designed to encourage. A much better, more idiomatic way is to use the methods provided by the `Optional` class itself. //--- Better Way --- // Use ifPresent to perform an action only if a value exists findName().ifPresent(name -> System.out.println(name)); // Use orElse to provide a default value String displayName = findName().orElse("Guest"); // Use orElseThrow to throw an exception if the value is absent String requiredName = findName().orElseThrow(() -> new IllegalStateException()); //------------------ 💡 Takeaway: Avoid `.isPresent()` followed by `.get()`. Prefer the functional methods like `ifPresent()`, `map()`, `orElse()`, and `orElseThrow()` to create more fluent and readable code. 📢 Using a feature correctly is as important as knowing it exists! 🚀 Day 12: A shortcut for lambdas - Method References! 💬 The `.get()` method can still throw a `NoSuchElementException`. Can you see why? 👇 #Java #Java8 #Optional #BestPractices #CleanCode #SoftwareDesign #15DaysOfJava8
Java 8 Optional Best Practices: Avoid isPresent() and Get
More Relevant Posts
-
🚀 Day 7 – Optional Class in Java (Avoid NullPointerException like a Pro) 📘 Prepare with Pankaj Tired of NullPointerException ruining your code? 😓 Java 8 introduced Optional to handle null values in a better way. 💡 What is Optional? Optional is a container object that may or may not contain a value. 👉 Why use Optional? ✔ Avoid NullPointerException ✔ Write cleaner code ✔ Force null handling 📌 Common Methods: 1. of() → value must be present 2. ofNullable() → value can be null 3. isPresent() → check value 4. get() → get value (avoid direct use) 5. orElse() → default value 6. orElseThrow() → throw exception 💻 Example: Optional<String> name = Optional.ofNullable("Pankaj"); System.out.println(name.orElse("Default Name")); 👉 Output: Pankaj 🔥 Best Practice: Instead of: if(name != null) Use: Optional.ofNullable(name).ifPresent(System.out::println); --- 💬 Do you use Optional in your code? Comment YES / NO 👇 #PrepareWithPankaj #Java #Optional #Java8 #BackendDeveloper #Coding #InterviewPreparation
To view or add a comment, sign in
-
-
Discover Java 11 features like HTTP Client, var in lambdas, new String methods, and file I/O updates with code and JEP links.
To view or add a comment, sign in
-
🚀 Java Evolution: A Quick Comparison of Java 8, Java 17, and Java 21! 🚀 Here's a handy cheat sheet every Java dev should know: 📚👇 💡 Java 8 (2014) — The Game Changer ✨ Lambda Expressions (Say goodbye to anonymous classes!) 🛠️ Stream API (Pipeline-style data processing) 🛡️ Optional (Null-safe containers) 🔄 Default Methods in Interfaces 📅 New Date/Time API (java.time) 🔗 Method References (:: syntax) 🕰️ Java 17 (2021) — The Maturity Update 📦 Records (Immutable data classes in a single line) 🚪 Sealed Classes (Controlled inheritance) ✂️ Text Blocks (No more string concatenation nightmares) 🔄 Switch Expressions (Switch that returns a value) 🔍 Pattern Matching for instanceof (No more manual casts) 📍 Better NPE Messages (Know where it broke!) 🚀 Java 21 (2023) — The Performance Leap 💻 Virtual Threads (Project Loom) — Millions of threads, zero effort! 📋 Sequenced Collections (getFirst() / getLast() at last!) 🔀 Record Patterns (Deconstruct records in switch/if) 🔄 Pattern Matching for switch (Type-safe branching) 🏷️ String Templates (Embedded expressions in strings) ⚙️ Scoped Values (The ThreadLocal killer) 💬 Save this post & share with your team! Which version are YOU running in production? Drop it in the comments! 👇 #Java #JavaDeveloper #Java21 #Java17 #SpringBoot #BackendDevelopment #SoftwareEngineering #JVM #Programming #TechLearning #JavaProgramming #CodingLife #100DaysOfCode #VirtualThreads #CleanCode #Developer #SystemDesign #OpenSource #MicroServices #SoftwareDevelopment
To view or add a comment, sign in
-
-
🔥 Day 10 — Thread vs Runnable vs Callable in Java If you're working with concurrency in Java, you’ll constantly decide between Thread, Runnable, and Callable. Here’s a simple, practical breakdown 👇 1️⃣ Thread — The Oldest & Loudest Way Thread represents an actual execution thread. ✔ When to use - Only when you must override thread-specific behavior - Very rare in modern applications ✖ Why it's not preferred - You can’t return a result - You can’t throw checked exceptions Tight coupling: your task is also the thread Check below example: class MyThread extends Thread { public void run() { System.out.println("Running thread"); } } 2️⃣ Runnable — Lightweight Tasks (No Return Value) Runnable is the simplest abstraction for a task. ✔ When to use - You just need to run a piece of code - No result required For example : Runnable task = () -> System.out.println("Task running"); executor.submit(task); 3️⃣ Callable — Runnable with Superpowers ⚡ Callable<V> is Runnable’s upgraded version. ✔ Key advantages - Returns a value - Can throw checked exceptions - Works seamlessly with Future ✔ When to use - When your task computes a result - When you need exception handling For example: Callable<Integer> task = () -> 42; Future<Integer> result = executor.submit(task); 💡 Key Takeaway Stop creating your own Thread. - Use Runnable when you need simple execution, - Use Callable when you need a result or exception handling. #100DaysOfJavaArchitecture #Java #Concurrency #SoftwareArchitecture #Microservices
To view or add a comment, sign in
-
-
💡 The Java Habit That Instantly Made My Code Cleaner One habit improved my Java code more than any framework or library. Naming things properly. Sounds simple, but it’s surprisingly hard. Compare this: int d; vs int daysSinceLastLogin; Or this: processData(); vs calculateMonthlyRevenue(); Good naming does 3 powerful things: ✔ Makes code self-documenting ✔ Reduces the need for excessive comments ✔ Helps other developers understand your logic instantly I realized that most messy code isn't complex — it's just poorly named. Now I follow one rule: 👉 If someone can understand the code without asking me questions, the naming is good. Clean code is not just about algorithms or patterns. Sometimes it's just about choosing better words. 💬 What’s the worst variable or method name you’ve ever seen in a codebase? #Java #CleanCode #SoftwareEngineering #JavaDeveloper #CodingBestPractices #BuildInPublic
To view or add a comment, sign in
-
-
Java 8 came out over 10 years ago. And it still breaks interviews in 2026. Here are the 8 features that changed everything (and what they actually replaced): → 1. Lambda Expressions Before: 10 lines of anonymous class boilerplate. After: (a, b) -> a.compareTo(b) One line. Same result. No excuses. → 2. Stream API Stop writing for-loops to filter lists. list.stream().filter().map().collect() reads like English. Your future self will thank you. → 3. Optional NullPointerException is the most common Java error in production. Optional.ofNullable() forces you to handle the null case explicitly. This alone will save you hours of debugging. → 4. Functional Interfaces Predicate. Function. Consumer. Supplier. 4 interfaces that make your code composable, testable, and clean. → 5. Method References names.forEach(System.out::println) Instead of: names.forEach(n -> System.out.println(n)) Small change. Huge readability boost. → 6. Default Methods in Interfaces You can now add new methods to interfaces without breaking every class that implements them. This is how Java evolved the Collections API without breaking your code. → 7. New Date/Time API LocalDate. LocalTime. ZonedDateTime. Finally — date handling that is immutable, thread-safe, and actually makes sense. RIP java.util.Date. → 8. Collectors API groupingBy(). joining(). partitioningBy(). Turn raw lists into maps, strings, and partitions — in one line. Java 8 wasn't just an update. It was a shift in how we think about writing Java. From imperative → declarative. From verbose → expressive. From fragile → safe. If you're still on Java 7 patterns in a Java 17+ codebase — this is your sign. Which of these 8 features do you use the most? Drop it in the comments 👇 #Java #Java8 #SoftwareEngineering #Programming #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 Mastering Core Java | Day 12 📘 Topic: Exception Handling – throw vs throws Today, I explored one of the most important distinctions in Java exception handling: throw and throws. Understanding this difference helps write cleaner, more predictable, and maintainable code. 🔑 throw Keyword Used inside a method body Explicitly creates and throws an exception Used when we want to manually signal an error Stops the current method execution 🧩 Example: if (age < 18) { throw new IllegalArgumentException("Age must be 18 or above"); } 📌 Think of throw as raising an alarm immediately. 🔑 throws Keyword Used in the method declaration Declares exceptions that a method may pass to the caller Commonly used for checked exceptions Responsibility of handling the exception is shifted to the calling method 🧩 Example: void readFile() throws IOException { // file reading code } 📌 Think of throws as a warning sign: “Be prepared to handle this.” ⚖️ Key Difference at a Glance throw → creates & throws an exception throws → declares an exception 💡 Key Takeaway: Using throw gives you control over when and why an exception occurs, while throws ensures transparency and proper exception propagation in larger applications. Grateful to my mentor Vaibhav Barde sir for the structured explanation and real‑world clarity, making this concept easy to understand and apply. #CoreJava #ExceptionHandling #ThrowVsThrows #JavaDeveloper #LearningJourney #Day12 #ProfessionalGrowth
To view or add a comment, sign in
-
-
☕🚀 Java 8 New Features (Part - 2) Java 8 didn’t just introduce Lambdas and Streams. It also brought several improvements that made Java code safer, cleaner, and more expressive 💡 In Part 2 of my Java 8 series, I explore the features that quietly improved everyday development 👇 📘 What You Will Learn 🔹 Default Methods (Interface Evolution) Add new methods to interfaces without breaking existing implementations - a huge step forward for API design 🧩 🔹 Optional Class Write null-safe code without endless null checks: • Creating Optional objects • Checking value presence • Returning values safely • Providing default values • Filtering & transforming values 🗓️ New Date & Time API (java.time) Finally replacing the old Date and Calendar pain 😄 • LocalDate, LocalTime, LocalDateTime • ZonedDateTime • Period & Duration • Formatting & compatibility Clean, immutable, and thread-safe ✨ 🏷️ Type Annotations & Repeating Annotations More precise metadata and better static analysis support 🔁 Iterable Interface Enhancements Cleaner iteration with forEach 🧵 StringJoiner A simple yet elegant way to build delimited strings Java 8 was not just about syntax changes - it modernized the language while keeping backward compatibility 💪 If you want to better understand these features and use them properly in real-world projects, this post is for you 👨💻👩💻 🔗 https://lnkd.in/ePCt4-HT Happy coding - and may your Optionals never be empty when you need them 😄✨ #Java #Java8 #JavaDeveloper #Optional #DateTimeAPI #DefaultMethods #BackendDevelopment #SoftwareEngineering #TechBlog #LearnJava #Programming #CleanCode #DevCommunity
To view or add a comment, sign in
-
-
What’s New in Java 26 (Key Features Developers Should Know) 1. Pattern Matching Enhancements Java continues improving pattern matching for switch and instanceof. Example: if (obj instanceof String s) { System.out.println(s.toUpperCase()); } Why it matters: Cleaner, safer type checks with less boilerplate. 2. Structured Concurrency (Evolving) Helps manage multiple concurrent tasks as a single unit. Example: try (var scope = new StructuredTaskScope.ShutdownOnFailure()) { scope.fork(() -> fetchUser()); scope.fork(() -> fetchOrders()); scope.join(); } Why it matters: Simplifies multi-threaded code and error handling. 3. Scoped Values (Better than ThreadLocal) A safer alternative to ThreadLocal for sharing data. Example: ScopedValue<String> user = ScopedValue.newInstance(); ScopedValue.where(user, "admin").run(() -> { System.out.println(user.get()); }); Why it matters: Avoids memory leaks and improves thread safety. 4. Virtual Threads Improvements Virtual threads continue to mature (Project Loom). Example: Thread.startVirtualThread(() -> { System.out.println("Lightweight task"); }); Why it matters: Handle thousands of concurrent requests with minimal resources. 5. Foreign Function & Memory API (Stabilization) Interact with native code without JNI. Example: MemorySegment segment = Arena.ofAuto().allocate(100); Why it matters: High-performance native integration (AI, ML, system-level apps). 6. Performance & GC Improvements Ongoing improvements in: - ZGC - G1 GC - Startup time - Memory efficiency Why it matters: Better latency and throughput for large-scale applications. 7. String Templates (Further Refinement) Simplifies string formatting and avoids injection issues. Example: String name = "Java"; String msg = STR."Hello \{name}"; Why it matters: Cleaner and safer string construction. Stay updated, but adopt carefully especially for non-LTS releases. #Java #Java26 #BackendEngineering #SpringBoot #Concurrency #Performance #SoftwareEngineering
To view or add a comment, sign in
-
For years, I've heard that Java's Async Profiler is the only "correct" way to see how fast your code is. But just this week did I learn why. If you think about how you might write your own profiler, you'd probably come up with something like this: 1. Run your target code 2. Poll the JVM for the current stacktrace 3. Repeat at a very high frequency 4. Aggregate the results to see where your code spends its time In theory this works great, but in practice it's subject to a big problem called Safepoint Bias. It turns out that the JVM can only return a stacktrace when a thread is at a "safepoint", and not all instructions can stop on one. Even worse, the act of forcing safepoints to sample changes the performance of the code you're trying to measure, defeating the purpose of profiling. The solution, as Async Profiler's name suggests, is to step outside of the JVM: 1. 𝐔𝐬𝐞 𝐎𝐒-𝐥𝐞𝐯𝐞𝐥 𝐬𝐚𝐦𝐩𝐥𝐢𝐧𝐠 with hardware timers that trigger more reliably 2. 𝐂𝐨𝐥𝐥𝐞𝐜𝐭 𝐧𝐚𝐭𝐢𝐯𝐞 𝐬𝐭𝐚𝐜𝐤𝐭𝐫𝐚𝐜𝐞𝐬 capturing layers underneath the Java code 3. 𝐀𝐠𝐠𝐫𝐞𝐠𝐚𝐭𝐞 𝐫𝐞𝐬𝐮𝐥𝐭𝐬 𝐥𝐚𝐭𝐞𝐫 as a flame graph to avoid tainting performance Because Async Profiler's approach doesn't wait for the JVM to reach a safepoint, no bias is incurred. Overhead is minimal, usually < 2%. Pretty cool!
To view or add a comment, sign in
-
More from this author
-
How to Build a Portfolio That Gets You Hired as a Java Developer (Even With Zero Experience)
RAMA CHANDRA RAO POLAMARASETTI 🇮🇳 10h -
The 4 Pillars of OOPs That Will Make You a Better Developer (With Real-World Examples)
RAMA CHANDRA RAO POLAMARASETTI 🇮🇳 1w -
5 Reasons Why Most Java Learners Never Get Hired (And How to Fix It)
RAMA CHANDRA RAO POLAMARASETTI 🇮🇳 1w
Explore related topics
- Idiomatic Coding Practices for Software Developers
- Coding Best Practices to Reduce Developer Mistakes
- Simple Ways To Improve Code Quality
- Ways to Improve Coding Logic for Free
- Clean Code Practices For Data Science Projects
- How to Write Clean, Error-Free Code
- Tips for Exception Handling in Software Development
- How Developers Use Composition in Programming
- Maintaining Code Quality Through Regular Reviews
- How to Improve Code Maintainability and Avoid Spaghetti Code
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