🧩 Optional in Java What is Optional? A wrapper to represent a value that may be absent, helps avoid null and makes intent clear. ✅ Why use it? 1. Prevents NullPointerException 2. Forces explicit handling of missing values 3. Cleaner and more readable APIs ⚖️ Correct vs Wrong Usage 1️⃣ Return Types ❌ User findUser(int id); // may return null ✅ Optional<User> findUser(int id); 2️⃣ Fields & Params ❌ Optional<String> name; // field void process(Optional<String>); // param 👉 Adds confusion + not intended use ✅ String name; void process(String data); 3️⃣ Accessing Value ❌ user.get(); // unsafe ✅ user.orElse(defaultUser); user.orElseThrow(); 4️⃣ Best Use (Chaining 💡) return Optional.ofNullable(user) .map(User::getAddress) .map(Address::getCity) .orElse("Unknown"); 🧠 Rule of Thumb 👉 Use Optional only for return types 👉 Avoid in fields, DTOs, method params 👉 Prefer map/flatMap over null checks 👉 If you are preparing for Java backend interviews, connect & follow - I share short, practical backend concepts regularly. #Java #SpringBoot #Backend #CleanCode #CodingTips #Developers #InterviewPrep #SoftwareEngineering
Java Optional: Avoid NullPointerExceptions and Improve Code Readability
More Relevant Posts
-
⚡ Lambdas & Functional Interfaces in Java What are they? Lambda expressions = short way to write anonymous functions. Functional Interface = interface with only one abstract method. 💡 Why use them? 1. Cleaner & less boilerplate code 2. Improves readability 3. Core for Streams & modern Java APIs 4. Encourages functional-style programming 🧩 Example Without Lambda: Runnable r = new Runnable() { public void run() { System.out.println("Running..."); } }; With Lambda: Runnable r = () -> System.out.println("Running..."); 🎯 Custom Functional Interface @FunctionalInterface interface Calculator { int operate(int a, int b); } Calculator add = (a, b) -> a + b; System.out.println(add.operate(2, 3)); // 5 🔁 Common Built-in Functional Interfaces 1. Predicate<T> → boolean result 2. Function<T, R> → transform input → output 3. Consumer<T> → takes input, no return 4. Supplier<T> → returns value, no input ⚙️ Flow Input → Lambda → Functional Interface → Output 🧠 Rule of Thumb If your interface has one method, think → "Can I replace this with a lambda?" 👉 If you are preparing for Java backend interviews, connect & follow - I share short, practical backend concepts regularly. #Java #SpringBoot #Backend #FunctionalProgramming #Coding
To view or add a comment, sign in
-
-
⚡ map vs flatMap in Java (Stream API) Definition: map() → Transforms each element 1:1 flatMap() → Transforms and flattens nested structures 🤔 Why use? 1. map() - When output is a single value per input - Simple transformations 2. flatMap() - When each element produces multiple values (collections/streams) - Avoid nested structures like List<List<T>> 💻 Example List<List<Integer>> list = Arrays.asList( Arrays.asList(1, 2), Arrays.asList(3, 4), Arrays.asList(5, 6) ); // map() → creates nested structure List<Stream<Integer>> mapResult = list.stream() .map(inner -> inner.stream()) .collect(Collectors.toList()); // flatMap() → flattens into single stream List<Integer> flatMapResult = list.stream() .flatMap(inner -> inner.stream()) .collect(Collectors.toList()); 🔄 Flow map() List<List> → Stream<List> → Stream<Stream> flatMap() List<List> → Stream<List> → Stream 🧠 Rule of Thumb 👉 If your transformation returns a single value → use map() 👉 If it returns a collection/stream → use flatMap() 👉 If you are preparing for Java backend interviews, connect & follow - I share short, practical backend concepts regularly. #Java #Backend #Streams #Java8 #CodingInterview #InterviewPrep #SoftwareEngineering
To view or add a comment, sign in
-
-
Hello Connections, Post 20— Java Fundamentals A-Z This one compiles perfectly. But breaks everything at runtime. 😱 Can you spot the bug? 👇 @FunctionalInterface interface Calculator { int calculate(int a, int b); int multiply(int a, int b); // 💀 Won't compile! } The bug? A Functional Interface can have only ONE abstract method! Two abstract methods = not functional! 💀 Here’s the fix 👇 // ✅ One abstract method only! @FunctionalInterface interface Calculator { int calculate(int a, int b); // ✅ Only one! } // ✅ Use it with Lambda! Calculator add = (a, b) -> a + b; Calculator multiply = (a, b) -> a * b; Calculator subtract = (a, b) -> a - b; System.out.println(add.calculate(5, 3)); // 8 ✅ System.out.println(multiply.calculate(5, 3)); // 15 ✅ System.out.println(subtract.calculate(5, 3)); // 2 ✅ Java’s Built-in Functional Interfaces // Predicate — returns boolean Predicate<String> isEmpty = s -> s.isEmpty(); // Function — transforms input to output Function<String, Integer> length = s -> s.length(); // Consumer — takes input, returns nothing Consumer<String> print = s -> System.out.println(s); // Supplier — no input, returns value Supplier<String> greeting = () -> "Hello DBS!"; Post 20 Summary: 🔴 Unlearned → Functional Interface can have multiple methods 🟢 Relearned → Exactly ONE abstract method — that’s what makes it functional! 🤯 Biggest surprise → Built-in functional interfaces replaced 20+ custom interfaces in codebase! Which built-in functional interface do you use most? Drop below! 👇 #Java #JavaFundamentals #BackendDevelopment #LearningInPublic #SDE2 Follow along for more! 👇
To view or add a comment, sign in
-
-
📘 #Day114 of My Java Full Stack Journey Today I learned about ServletRequest, ServletResponse, HttpServletRequest, and HttpServletResponse, which handle communication between the browser and servlet in Java web applications. ✨ 𝐒𝐞𝐫𝐯𝐥𝐞𝐭𝐑𝐞𝐪𝐮𝐞𝐬𝐭 ServletRequest is used to receive data from the client. It contains information sent by the browser such as: ➜ Form data ➜ Request parameters ➜ Client details ➜ Protocol information Common methods I explored: ▪ getParameter() → Reads form data ▪ getParameterNames() → Returns parameter names ▪ getParameterValues() → Returns multiple values ✨ 𝐒𝐞𝐫𝐯𝐥𝐞𝐭𝐑𝐞𝐬𝐩𝐨𝐧𝐬𝐞 ServletResponse is used to send response back to the client. Common methods I explored: ▪ getWriter() → Sends text response to browser ▪ setContentType() → Sets response type (HTML/Text) ✨ 𝐇𝐭𝐭𝐩𝐒𝐞𝐫𝐯𝐥𝐞𝐭𝐑𝐞𝐪𝐮𝐞𝐬𝐭 HttpServletRequest extends ServletRequest and provides HTTP-specific features. Common methods I explored: ▪ getParameter() → Reads form data ▪ getHeader() → Returns request header information ▪ getMethod() → Returns request type (GET / POST) ✨ 𝐇𝐭𝐭𝐩𝐒𝐞𝐫𝐯𝐥𝐞𝐭𝐑𝐞𝐬𝐩𝐨𝐧𝐬𝐞 HttpServletResponse extends ServletResponse and is used to send HTTP response to browser. Common methods I explored: ▪ getWriter() → Sends output to browser ▪ setContentType() → Sets response format ▪ sendRedirect() → Redirects response to another resource ✨ 𝐝𝐨𝐆𝐞𝐭() 𝐯𝐬 𝐝𝐨𝐏𝐨𝐬𝐭() These methods are used inside HttpServlet to handle HTTP requests. ➤ 𝒅𝒐𝑮𝒆𝒕() ▪ Data sent through URL ▪ Suitable for retrieving data ▪ Less secure (data visible in URL) ▪ Faster execution ➤ 𝒅𝒐𝑷𝒐𝒔𝒕() ▪ Data sent inside request body ▪ Suitable for sending sensitive data ▪ More secure than doGet() ▪ Commonly used for form submissions ✨ 𝐑𝐞𝐪𝐮𝐞𝐬𝐭–𝐑𝐞𝐬𝐩𝐨𝐧𝐬𝐞 𝐅𝐥𝐨𝐰 Browser → Request → Servlet → Response → Browser ➜ These request and response objects are essential for handling communication in every servlet-based web application. Gurugubelli Vijaya Kumar | 10000 Coders #Java #Servlets #ServletRequest #ServletResponse #doGet #doPost #JavaWebDevelopment #BackendDevelopment
To view or add a comment, sign in
-
🔀 𝐂𝐨𝐧𝐜𝐮𝐫𝐫𝐞𝐧𝐭𝐌𝐨𝐝𝐢𝐟𝐢𝐜𝐚𝐭𝐢𝐨𝐧𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 𝙞𝙣 𝙅𝙖𝙫𝙖 Why does it happen? This is one exception many developers face while working with collections 𝐖𝐡𝐚𝐭 𝐢𝐬 𝐂𝐨𝐧𝐜𝐮𝐫𝐫𝐞𝐧𝐭𝐌𝐨𝐝𝐢𝐟𝐢𝐜𝐚𝐭𝐢𝐨𝐧𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧? ➡️ It occurs when we modify a collection while iterating over it 📃 Example 𝐢𝐦𝐩𝐨𝐫𝐭 𝐣𝐚𝐯𝐚.𝐮𝐭𝐢𝐥.*; 𝐩𝐮𝐛𝐥𝐢𝐜 𝐜𝐥𝐚𝐬𝐬 𝐃𝐞𝐦𝐨 { 𝐩𝐮𝐛𝐥𝐢𝐜 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐦𝐚𝐢𝐧(𝐒𝐭𝐫𝐢𝐧𝐠[] 𝐚𝐫𝐠𝐬) { 𝐋𝐢𝐬𝐭<𝐈𝐧𝐭𝐞𝐠𝐞𝐫> 𝐥𝐢𝐬𝐭 = 𝐧𝐞𝐰 𝐀𝐫𝐫𝐚𝐲𝐋𝐢𝐬𝐭<>(); 𝐥𝐢𝐬𝐭.𝐚𝐝𝐝(𝟏); 𝐥𝐢𝐬𝐭.𝐚𝐝𝐝(𝟐); 𝐥𝐢𝐬𝐭.𝐚𝐝𝐝(𝟑); 𝐟𝐨𝐫 (𝐈𝐧𝐭𝐞𝐠𝐞𝐫 𝐢 : 𝐥𝐢𝐬𝐭) { 𝐢𝐟 (𝐢 == 𝟐) { 𝐥𝐢𝐬𝐭.𝐫𝐞𝐦𝐨𝐯𝐞(𝐢); // 𝐜𝐚𝐮𝐬𝐞𝐬 𝐞𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 } } } } ⚠️ 𝐖𝐡𝐲 𝐝𝐨𝐞𝐬 𝐭𝐡𝐢𝐬 𝐡𝐚𝐩𝐩𝐞𝐧? Internally, Java collections use an Iterator When we modify the collection directly: ❌ Structure changes ❌ Iterator gets confused Throws ➡️ 𝐂𝐨𝐧𝐜𝐮𝐫𝐫𝐞𝐧𝐭𝐌𝐨𝐝𝐢𝐟𝐢𝐜𝐚𝐭𝐢𝐨𝐧𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 Ways to Fix ➡️ Use Iterator 𝐈𝐭𝐞𝐫𝐚𝐭𝐨𝐫<𝐈𝐧𝐭𝐞𝐠𝐞𝐫> 𝐢𝐭 = 𝐥𝐢𝐬𝐭.𝐢𝐭𝐞𝐫𝐚𝐭𝐨𝐫(); 𝐰𝐡𝐢𝐥𝐞 (𝐢𝐭.𝐡𝐚𝐬𝐍𝐞𝐱𝐭()) { 𝐢𝐟 (𝐢𝐭.𝐧𝐞𝐱𝐭() == 𝟐) { 𝐢𝐭.𝐫𝐞𝐦𝐨𝐯𝐞(); // 𝐬𝐚𝐟𝐞 } } ➡️ Use removeIf() (Java 8) list.removeIf(i -> i == 2); ▪️Always avoid modifying a collection directly during iteration ▪️Use safe methods provided by Java (use iterator) Have you ever faced this exception in your project? 🤔 How did you fix it? #Java #JavaDeveloper #JavaBackend #Programming #TechJourney #LearnBySharing #JavaConcepts #Collections #InterviewPrep #Developers
To view or add a comment, sign in
-
🤯 Every Java developer uses HashMap… But do you really know what happens when you call map.put("key", "value")? Let’s break it down 👇 ⚙️ Step 1 — Hashing Java calls hashCode() on the key, converting it into an integer. ⚙️ Step 2 — Bucket Calculation That hash is used to determine the index of the bucket (array slot): index = hashCode % array.length ⚙️ Step 3 — Storage The key-value pair is stored in that bucket as a Node. 🚨 What about collisions? When multiple keys map to the same bucket, a collision occurs. 👉 Before Java 8: Entries are stored using a LinkedList 👉 Java 8 and later: If entries exceed 8, it converts into a Red-Black Tree 🌳 for better performance 💡 Why this matters: ✔️ Average time complexity for get() and put() is O(1) ✔️ Not thread-safe (use ConcurrentHashMap in multi-threaded scenarios) ✔️ Always override hashCode() and equals() for custom key objects 🔑 Key Rule: If two objects are equal, they must have the same hashCode(). But the same hashCode() does not guarantee equality. This is one of the most commonly asked Java interview questions—and a fundamental concept every backend developer should truly understand. Have you faced this question in an interview? 👇 #Java #JavaDeveloper #BackendDevelopment #SpringBoot #JavaInterview #Programming #Coding #SoftwareEngineering
To view or add a comment, sign in
-
-
99% of Java devs write this bug every day. I fixed it in 3 lines. Here's how 👇 I reviewed 200+ Java codebases this year. The #1 most common bug? NullPointerException from unhandled Optional. ❌ THE PROBLEM — code most devs write: // Crashes at runtime. Every. Single. Time. Optional<User> user = repo.findById(id); String name = user.get().getName(); // ^ NullPointerException if user is empty! ✅ THE FIX — clean, safe, production-ready: // Option 1: Safe default value String name = repo.findById(id) .map(User::getName) .orElse("Unknown"); // Option 2: Throw a meaningful error User user = repo.findById(id) .orElseThrow(() -> new UserNotFoundException(id)); // Option 3: Execute only if present repo.findById(id).ifPresent(u -> sendEmail(u)); Why does this matter? ✓ No more silent NPE crashes in production ✓ Code reads like plain English ✓ Forces you to handle the null case explicitly ✓ Works perfectly with Java streams & lambdas The real rule: Never call .get() on an Optional without checking .isPresent() first. Better yet — never call .get() at all. Use the functional API. --- Drop a 🔥 if you've hit this bug before. Tag a Java dev who needs to see this! #Java #JavaDev #CleanCode #Programming #SoftwareEngineering #100DaysOfCode #Optional #NullPointer
To view or add a comment, sign in
-
Day 12 Today’s Java practice was about solving the Leader Element problem. Instead of using nested loops, I used a single traversal from right to left, which made the solution clean and efficient. A leader element is one that is greater than all the elements to its right. Example: Input: {16,17,5,3,4,2} Leaders: 17, 5, 4, 2 🧠 Approach I used: ->Start traversing from the rightmost element ->Keep track of the maximum element seen so far ->If the current element is greater than the maximum, it becomes a leader ->This is an efficient approach with O(n) time complexity and no extra space. ================================================= // Online Java Compiler // Use this editor to write, compile and run your Java code online class Main { public static void main(String[] args) { int a [] ={16,17,5,3,4,2}; int length=a.length; int maxRight=a[length-1]; System.out.print("Leader elements are :"+maxRight+" "); for(int i=a[length-2];i>=0;i--) { if(a[i]>maxRight) { maxRight=a[i]; System.out.print(maxRight+" "); } } } } Output:Leader elements are :2 4 5 17 #AutomationTestEngineer #Selenium #Java #DeveloperJourney #Arrays
To view or add a comment, sign in
-
-
🔗 Java LinkedList — The Complete Visual Guide You've Been Looking For Think LinkedList is just "another collection"? Think again! 🧠 Understanding when to use LinkedList vs ArrayList can be the difference between optimal and sluggish performance. Here's everything you need to know 👇 🔑 Basic Concepts: ✅ Doubly Linked — Each node points to both next AND previous nodes ✅ No Continuous Memory — Nodes scattered in memory, linked by pointers ✅ Dynamic Size — Grows/shrinks without resizing overhead ⚡ Key Performance Wins: ‣ addFirst() / addLast() — O(1) — Instant insertions at ends! ‣ removeFirst() / removeLast() — O(1) — Lightning fast removals ‣ add(index, e) — O(n) — Requires traversal to index ‣ get(index) — O(n)* — No direct access like arrays 💡 When to Use LinkedList: ✅ Frequent add/remove operations (especially at ends) ✅ Size fluctuates unpredictably ✅ Need bi-directional traversal ✅ Building queues, stacks, undo/redo systems 🎯 Real-World Use Cases: ・Music playlists (next/previous navigation) ・Browser history (forward/back) ・Task scheduling & LRU caches ・Undo/Redo operations ❌ When to Avoid: ❌ Need fast random access by index ❌ Memory-constrained environments (extra pointers per node) ❌ Simple sequential access (ArrayList is faster) 🧠 Advanced Pro Tip: LinkedList excels at middle insertions/deletions compared to ArrayList — no element shifting required! But remember: you still pay O(n) to traverse to that position. 🔥 The Tradeoff: More memory per node (2 pointers), but NO resizing overhead. Choose wisely based on your access patterns! Which do you prefer — ArrayList or LinkedList? Share your reasoning below! 👇 Save this guide for your next interview prep & follow for more Java deep dives! 🚀 #Java #LinkedList #DataStructures #JavaDeveloper #Programming #SoftwareEngineering #CodingTips #JavaInterview #DSA
To view or add a comment, sign in
-
-
This crashes in production at 2 AM. Every single time. 😱 Java Fundamentals A-Z | Post 22 Can you spot the bug? 👇 public String getUserEmail(int userId) { User user = userRepository.findById(userId); return user.getEmail(); // 💀 NullPointerException! } String email = getUserEmail(999); System.out.println(email.toUpperCase()); // 💀 CRASH! findById() returned null. Nobody checked. App crashes. Users complain. 2 AM alerts. 💀 Optional eliminates this forever 👇 // ✅ Return Optional — make null explicit! public Optional<String> getUserEmail(int userId) { return Optional.ofNullable( userRepository.findById(userId)) .map(User::getEmail); } // ✅ Caller handles safely! getUserEmail(999) .map(String::toUpperCase) .ifPresent(System.out::println); // ✅ Or use default value! String email = getUserEmail(999) .orElse("default@dbs.com"); // Never null! ✅ Optional eliminated 3 recurring NullPointerExceptions in our user service. 🔥 Optional cheat sheet 👇 — Optional.of() → value exists, never null — Optional.ofNullable() → value might be null — orElse() → default if empty — ifPresent() → only runs if value exists — map() → transform if present Summary: 🔴 Returning null and hoping caller checks it 🟢 Optional = explicit contract that value might be absent 🤯 Null checks disappeared from our entire user service Have you replaced null returns with Optional yet? Drop a 🎁 below! Posting real-world Java bugs and fixes. #Java #JavaFundamentals #BackendDevelopment #LearningInPublic #SDE2
To view or add a comment, sign in
-
Explore related topics
- Java Coding Interview Best Practices
- Tips for Coding Interview Preparation
- Backend Developer Interview Questions for IT Companies
- Key Skills for Backend Developer Interviews
- Code Planning Tips for Entry-Level Developers
- Common Coding Interview Mistakes to Avoid
- Advanced Programming Concepts in Interviews
- How Developers Use Composition in Programming
- Common Algorithms for Coding Interviews
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