𝐉𝐚𝐯𝐚 𝟏𝟑: 𝐌𝐚𝐤𝐢𝐧𝐠 𝐭𝐡𝐞 𝐒𝐰𝐢𝐭𝐜𝐡 𝐒𝐭𝐚𝐭𝐞𝐦𝐞𝐧𝐭 𝐁𝐞𝐭𝐭𝐞𝐫! If you've ever spent hours debugging a logic error only to find you missed a single break; statement, you know the pain of the traditional Java switch. Java 12 and 13 introduced major upgrades to fix these "legacy" headaches. Here is a quick breakdown of how the Enhanced Switch makes your code cleaner and safer: 𝟏. 𝐍𝐨 𝐌𝐨𝐫𝐞 "𝐅𝐚𝐥𝐥-𝐓𝐡𝐫𝐨𝐮𝐠𝐡" 𝐓𝐫𝐚𝐩𝐬 Traditional switches require a break for every case. If you forget it, the code "falls through" to the next case. The Fix: Using the new arrow (->) syntax. It executes only the code on the right side. No break required! 𝟐. 𝐒𝐰𝐢𝐭𝐜𝐡 𝐚𝐬 𝐚𝐧 𝐄𝐱𝐩𝐫𝐞𝐬𝐬𝐢𝐨𝐧 You can now assign the result of a switch directly to a variable. This makes your code much more concise. Example: 𝐉𝐚𝐯𝐚 String device = switch (itemCode) { case 001 -> "Laptop"; case 002 -> "Desktop"; default -> "Unknown"; }; System.out.println("Output: " + device); 𝐎𝐮𝐭𝐩𝐮𝐭: Output: Laptop 𝟑. 𝐌𝐮𝐥𝐭𝐢𝐩𝐥𝐞 𝐕𝐚𝐥𝐮𝐞𝐬, 𝐎𝐧𝐞 𝐂𝐚𝐬𝐞 Gone are the days of stacking cases on top of each other. You can now comma-separate multiple values in a single line: case 001, 002, 003 -> System.out.println("Electronic Gadget"); 𝟒. 𝐓𝐡𝐞 𝐲𝐢𝐞𝐥𝐝 𝐊𝐞𝐲𝐰𝐨𝐫𝐝 In Java 13, if you are using the traditional colon syntax (:) but want to return a value from a switch expression, use yield. It returns the value and exits the switch immediately. 𝟓. 𝐄𝐱𝐡𝐚𝐮𝐬𝐭𝐢𝐯𝐞𝐧𝐞𝐬𝐬 (𝐒𝐚𝐟𝐞𝐭𝐲 𝐅𝐢𝐫𝐬𝐭!) When using switch as an expression, Java forces you to cover every possible case (or provide a default). This prevents those pesky "unhandled value" bugs from reaching production. 𝟔. 𝐌𝐨𝐝𝐞𝐫𝐧 𝐋𝐨𝐠𝐢𝐜 𝐰𝐢𝐭𝐡 𝐭𝐡𝐞 𝐰𝐡𝐞𝐧 𝐊𝐞𝐲𝐰𝐨𝐫𝐝 (𝐉𝐚𝐯𝐚 𝟐𝟏+) Introduced in Java 21, the when keyword acts as a Guard. It allows you to add extra boolean conditions directly to a case label. No more nesting if statements inside your cases! Example: 𝐉𝐚𝐯𝐚 switch (obj) { case String s when s.length() > 5 -> System.out.println("Long string: " + s); case String s -> System.out.println("Short string"); default -> System.out.println("Not a string"); } Deeply grateful to Syed Zabi Ulla Sir for his expert guidance. He has a gift for making even the trickiest Java updates feel intuitive. Thank you, sir, for helping us build such a strong technical base and for always being a guiding light in our learning journey! #Java #Programming #CodingTips #SoftwareDevelopment #Java21 #CleanCode #BackendDeveloper #Mentorship #PWIOI #LearningJourney
Java Switch Statement Enhancements: Cleaner and Safer Code with Java 12 and 13
More Relevant Posts
-
𝑫𝒊𝒇𝒇𝒆𝒓𝒆𝒏𝒄𝒆 𝒃𝒆𝒕𝒘𝒆𝒆𝒏 "𝒕𝒉𝒓𝒐𝒘" 𝒂𝒏𝒅 "𝒕𝒉𝒓𝒐𝒘𝒔" 𝒊𝒏 𝑱𝒂𝒗𝒂 Before understanding "throw" and "throws", one important point ➡️ Throwable is the parent class of Exception ➡️ Exception is the parent class of all Exceptions in Java. 🔍what actually "𝐭𝐡𝐫𝐨𝐰𝐬" mean ➡️It is used in method declaration 📃 "throws" is used to delegate (pass) the exception from one method to the calling method (the one who calls it) and not actually handles the exception. 📃JVM also does not handle it at this stage. Calling method provides try catch blocks to handle this exception. 📃 If not handled Exception goes to JVM.JVM terminates the program ❌ 🔍 Definition of "throw" 📃 "throw" is used to explicitly throw an exception. It stops the normal execution flow. 📃It is used inside a method, The exception is then passed to caller method. 👨💻 Example 𝐢𝐦𝐩𝐨𝐫𝐭 𝐣𝐚𝐯𝐚.𝐢𝐨.*; 𝐜𝐥𝐚𝐬𝐬 𝐃𝐞𝐦𝐨 { 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐫𝐞𝐚𝐝𝐅𝐢𝐥𝐞() 𝐭𝐡𝐫𝐨𝐰𝐬 𝐅𝐢𝐥𝐞𝐍𝐨𝐭𝐅𝐨𝐮𝐧𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 { 𝐅𝐢𝐥𝐞 𝐟𝐢𝐥𝐞 = 𝐧𝐞𝐰 𝐅𝐢𝐥𝐞("𝐃://𝐟𝐢𝐥𝐞𝟏.𝐭𝐱𝐭"); 𝐭𝐡𝐫𝐨𝐰 𝐧𝐞𝐰 𝐅𝐢𝐥𝐞𝐍𝐨𝐭𝐅𝐨𝐮𝐧𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧("𝐅𝐢𝐥𝐞 𝐧𝐨𝐭 𝐟𝐨𝐮𝐧𝐝"); } 𝐩𝐮𝐛𝐥𝐢𝐜 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐦𝐚𝐢𝐧(𝐒𝐭𝐫𝐢𝐧𝐠[] 𝐚𝐫𝐠𝐬) { 𝐭𝐫𝐲 { 𝐫𝐞𝐚𝐝𝐅𝐢𝐥𝐞(); } 𝐜𝐚𝐭𝐜𝐡 (𝐅𝐢𝐥𝐞𝐍𝐨𝐭𝐅𝐨𝐮𝐧𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 𝐞) { 𝐒𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧("𝐈𝐧𝐯𝐚𝐥𝐢𝐝 𝐅𝐢𝐥𝐞 𝐍𝐚𝐦𝐞"); } } } 📝𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐫𝐞𝐚𝐝𝐅𝐢𝐥𝐞() 𝐭𝐡𝐫𝐨𝐰𝐬 𝐅𝐢𝐥𝐞𝐍𝐨𝐭𝐅𝐨𝐮𝐧𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 This method is declaring an exception using throws ⚖️“I will not handle this exception” ☎️“Whoever calls me should handle it” 📝 𝐭𝐡𝐫𝐨𝐰 𝐧𝐞𝐰 𝐅𝐢𝐥𝐞𝐍𝐨𝐭𝐅𝐨𝐮𝐧𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧("𝐅𝐢𝐥𝐞 𝐧𝐨𝐭 𝐟𝐨𝐮𝐧𝐝"); ▪️Here we are manually throwing exception using throw Important: Execution stops here immediately Control goes to calling method 📝𝐭𝐫𝐲 { 𝐫𝐞𝐚𝐝𝐅𝐢𝐥𝐞();} ▪️Calling the method which has throws Since it declared exception → ▪️We must handle it using try-catch 📝 𝐜𝐚𝐭𝐜𝐡 (𝐅𝐢𝐥𝐞𝐍𝐨𝐭𝐅𝐨𝐮𝐧𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 𝐞) Catch block handles the exception ♣️ Key Difference "throws" → delegates exception (method level) ➡️ passing responsibility "throw" → actually throws exception (statement level) ➡️ creating the problem #Java #JavaDeveloper #JavaConcepts #ExceptionHandling #Programming #TechJourney #InterviewPrep
To view or add a comment, sign in
-
🤔 Ever wondered how Java handles multiple threads safely? Let’s break it down in a simple way 👇 🚀 **Synchronized vs Atomic Classes in Java — Explained Simply Multithreading is powerful, but handling shared data safely is critical. Let’s break it down 👇 🔒 What is `synchronized`? A keyword in Java used to control access to shared resources. ✔ Ensures only one thread executes at a time (Mutual Exclusion) ✔ Prevents race conditions Example: public synchronized void increment() { count++; } 🔑 How it works? * Every object has an **Intrinsic Lock (Monitor)** * Thread acquires lock → executes → releases lock * Other threads must wait Automatic: When you use the synchronized keyword, Java handles the locking and unlocking for you behind the scenes. 💡 Think: One door, one key — whoever holds the key gets access --- ### 🧠 Guarantees ✔ Mutual Exclusion(Only one thread can access a shared resource at a time) ✔ Visibility (changes visible to other threads) ✔ Ordering (Happens-Before) ⚙️ Memory Visibility (Internals) Based on Java Memory Model 1️⃣ Write → Store Barrier → Writing updated values from a thread’s local CPU cache to the shared main memory (RAM) 2️⃣ Read → Load Barrier → Ensure fresh values are read from main memory 💡 Ensures threads don’t read stale data from CPU cache ⚡ What is `AtomicInteger`? A class from: java.util.concurrent.atomic ✔ Thread-safe without locks ✔ Uses **CAS (Compare-And-Swap)** + memory barriers Example: AtomicInteger count = new AtomicInteger(0); count.incrementAndGet(); 🔄 CAS Logic If current value == expected → update Else → retry Key Methods get() // read value set() // update value incrementAndGet() // ++count getAndIncrement() // count++ compareAndSet(a, b) // CAS operation Example Thread-1: expected = 0 → update to 1 ✅ Thread-2: expected = 0 → fails ❌ (value already changed) retries → succeeds later 📦 Atomic Package Categories * **Primitive** → AtomicInteger, AtomicLong * **Reference** → AtomicReference, Stamped, Markable * **Array** → AtomicIntegerArray * **Field Updaters** → Fine-grained updates * **High Concurrency** → LongAdder, DoubleAdder 🚀 Why `LongAdder`? (Java 8) Problem with Atomic: ❌ High contention ❌ Too many CAS retries Solution: ✔ Split into multiple counters AtomicInteger → [ 0 ] ❌ ← all threads update here ❌ (bottleneck) LongAdder → [1][2][3][4] ← threads distributed ✅ ✔ Better performance under heavy load ✅ When to Use **Use synchronized** ✔ Complex operations ✔ Multiple variables **Use Atomic** ✔ Counters ✔ Simple updates **Use LongAdder** ✔ High concurrency systems (metrics, counters) 🎯 Final Takeaway 👉 Use synchronized for safety. 👉 Atomic for performance 👉LongAdder for scalability #Java #Multithreading #Concurrency #CoreJava #InterviewPrep
To view or add a comment, sign in
-
-
🚨 Error Handling in Modern Java (2025 Edition) Error handling isn’t just about catching exceptions anymore — it’s about writing resilient, readable, and maintainable code. Here’s how modern Java (Java 17+) is changing the game 👇 --- 🔹 1. Use Specific Exceptions (Avoid Generic Catch) try { int result = 10 / 0; } catch (ArithmeticException ex) { System.out.println("Cannot divide by zero: " + ex.getMessage()); } ✅ Improves clarity ❌ Avoid "catch (Exception e)" unless absolutely necessary --- 🔹 2. Multi-Catch for Cleaner Code try { // risky code } catch (IOException | SQLException ex) { ex.printStackTrace(); } 👉 Reduces duplication and keeps code concise --- 🔹 3. Try-With-Resources (Auto Resource Management) try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) { System.out.println(br.readLine()); } catch (IOException e) { e.printStackTrace(); } ✅ No need for finally blocks ✅ Prevents memory leaks --- 🔹 4. Custom Exceptions for Business Logic class InvalidUserException extends RuntimeException { public InvalidUserException(String message) { super(message); } } if (user == null) { throw new InvalidUserException("User not found"); } 👉 Makes domain errors meaningful --- 🔹 5. Use Optional Instead of Null Checks Optional<String> name = Optional.ofNullable(getUserName()); name.ifPresentOrElse( n -> System.out.println(n), () -> System.out.println("No name found") ); ✅ Avoids NullPointerException ✅ Encourages functional style --- 🔹 6. Logging > Printing Stack Trace private static final Logger logger = Logger.getLogger(MyClass.class.getName()); try { // code } catch (Exception e) { logger.severe("Error occurred: " + e.getMessage()); } 👉 Production-ready approach --- 💡 Pro Tip: Modern Java encourages fail-fast + meaningful recovery. Don’t just catch errors — design how your system responds to them. --- 🔁 Final Thought Good error handling is invisible when things work… …but invaluable when things break. --- #Java #ErrorHandling #CleanCode #SoftwareEngineering #JavaDeveloper #BackendDevelopment
To view or add a comment, sign in
-
💡 Why do we need forEach() in Java 8 when we already have loops? Java has always supported iteration using traditional loops. But with Java 8, forEach() was introduced to align with functional programming and stream processing. Let’s break it down 👇 🔹 1. Traditional for Loop for(int i = 0; i < arr.length; i++){ System.out.println(arr[i]); } ✅ Gives full control using index ✅ Supports forward & backward traversal ✅ Easy to skip elements or modify logic ⚠️ Downside: You must manage indexes manually, which can lead to errors like ArrayIndexOutOfBoundsException ------------------------------------------------------------------------------ 🔹 2. Enhanced for-each Loop for(int num : numbers){ System.out.println(num); } ✅ Cleaner and simpler syntax ✅ No need to deal with indexes ⚠️ Limitation: Only forward iteration No direct access to index ------------------------------------------------------------------------------ 🔹 3. Java 8 forEach() (Functional Approach) Arrays.stream(numbers) .forEach(num -> System.out.println(num)); 👉 Even more concise: Arrays.stream(numbers) .forEach(System.out::println); ✅ Encourages functional programming ✅ Works seamlessly with Streams API ✅ More expressive and readable ✅ Can be used with parallel streams for better performance ------------------------------------------------------------------------------ 🔍 What happens internally? forEach() is a default method in the Iterable interface It takes a Consumer functional interface The lambda you provide is executed via: void accept(T t); ------------------------------------------------------------------------------ 🚀 Final Thought While traditional loops are still useful, forEach() brings a declarative and modern way of iterating data — especially when working with streams. #Java #Java8 #Programming #Developers #Coding #FunctionalProgramming
To view or add a comment, sign in
-
✨ Most Useful Keywords In Java✨ ➡️final : The final keyword can be applied to classes, variables, methods, and blocks. Once assigned, it cannot be changed. A final class cannot be extended, a final variable cannot be reassigned, and a final method cannot be overridden. ➡️static : The static keyword can be applied to variables, methods, and blocks. Static members can be accessed using the class name without creating an object. Static methods cannot be overridden. ➡️abstract : Used to create a class or method that is incomplete and must be implemented by sub-classes ➡️assert : Used for debugging to test assumptions during runtime ➡️boolean : Represents a logical data type with values true or false ➡️break : Terminates a loop or switch statement immediately ➡️byte : Data type to store 8-bit integer values ➡️case : Defines a branch in a switch statement ➡️catch : Handles exceptions raised in a try block ➡️char : Stores a single character ➡️class : Used to declare a class ➡️continue : Skips the current loop iteration and continues with the next one ➡️default : Executes when no case matches in switch Defines default methods in interfaces ➡️do : Used in a do-while loop (executes at least once) ➡️double : Stores 64-bit decimal numbers ➡️else : Executes when an if condition is false ➡️enum :Defines a fixed set of constants ➡️extends : Used by a subclass to inherit another class ➡️finally : Block that always executes, used for cleanup ➡️float : Stores 32-bit decimal values ➡️for : Used for loop execution with initialization, condition, and increment ➡️if : Executes code when a condition is true ➡️implements : Used by a class to implement an interface ➡️import : Allows access to classes defined in other packages ➡️instanceof : Checks whether an object belongs to a specific class ➡️int : Stores 32-bit integer values ➡️interface : Used to declare a contract that classes must follow ➡️long : Stores 64-bit integer values ➡️new : Creates an object or instance ➡️package : Groups related classes and interfaces ➡️return : Sends a value back from a method and exits it ➡️short : Stores 16-bit integer values ➡️static : Belongs to the class, not object ➡️super : Refers to parent class object or constructor ➡️switch : Selects execution paths based on an expression ➡️synchronized : Controls thread access to prevent data inconsistency ➡️this : Refers to the current object ➡️throw : Explicitly throws an exception ➡️throws : Declares exceptions that a method may pass upward ➡️transient : Prevents variable from being serialized ➡️try : Wraps code that may generate exceptions ➡️void : Indicates a method returns no value ➡️volatile : Ensures variable value is read from main memory, not cache ➡️while: Executes a loop while condition remains true ➡️var: var enables local variable type inference ➡️record: record is a special immutable class used to store data only #javafeatures #oops #opentowork #fresher #softwareengineer #hiring #javadeveloper
To view or add a comment, sign in
-
𝗘𝘃𝗲𝗿 𝗵𝗲𝗮𝗿𝗱 𝗼𝗳 𝗮 𝘁𝗵𝗿𝗲𝗮𝗱 𝘄𝗮𝗸𝗲 𝘂𝗽...𝘄𝗶𝘁𝗵𝗼𝘂𝘁 𝗯𝗲𝗶𝗻𝗴 𝗻𝗼𝘁𝗶𝗳𝗶𝗲𝗱? No notify(), no interrupt() and yet it continues execution. That’s where I learnt about the 𝗦𝗽𝘂𝗿𝗶𝗼𝘂𝘀 𝗪𝗮𝗸𝗲𝘂𝗽 in Java threads. 𝗔 𝗦𝗽𝘂𝗿𝗶𝗼𝘂𝘀 𝗪𝗮𝗸𝗲𝘂𝗽 in Java threads occurs when a thread in the waiting state wakes up without being notified or without any explicit thread method. 𝗪𝗵𝘆 𝗱𝗼𝗲𝘀 𝗶𝘁 𝗵𝗮𝗽𝗽𝗲𝗻? - The JVM does not control thread execution entirely; execution relies on the operating system. OS thread systems (like pthreads) wake up threads randomly. - It is by design; Java explicitly allows this behaviour. - Java and OS don't guarantee threads wake up when notified, as it can impact the overall performance. 𝗪𝗵𝗮𝘁 𝗵𝗮𝗽𝗽𝗲𝗻𝘀 𝗶𝗻𝘁𝗲𝗿𝗻𝗮𝗹𝗹𝘆? 1. lock.wait() is called 2. The thread releases the monitor lock and goes to the waiting state. 3. JVM/OS maintains a wait queue for the object. 4. Ideally, threads wakes when notify()/notifyAll() methods is called. BUT JVM/OS can remove the thread from the wait queue randomly and put it into the runnable state. How to prevent issues due to spurious wakeups? Never use "if" with "wait()" method, always use "while" public synchronized void consume() throws InterruptedException { if (queue.isEmpty()) { wait(); // may wake up spuriously } int item = queue.remove(); } In case of a spurious wakeup, queue.remove() will execute directly. If the queue is empty, it will throw an exception. public synchronized void consume() throws InterruptedException { while (queue.isEmpty()) { wait(); // may wake up spuriously } int item = queue.remove(); } In this case, even if a spurious wakeup happens, the while loop rechecks the condition. If the queue is still empty, it goes back to the waiting state again, preventing any exceptions/errors. Have you ever faced a spurious wakeup in production or in your personal projects? Let's discuss in comments.
To view or add a comment, sign in
-
𝗝𝗮𝘃𝗮 𝟵 𝗦𝘁𝗿𝗲𝗮𝗺 𝗔𝗣𝗜 𝗘𝗻𝗵𝗮𝗻𝗰𝗲𝗺𝗲𝗻𝘁𝘀 — What's New Beyond Java 8 The Stream API was one of the most significant additions in Java 8, enabling functional-style processing of collections using Lambda Expressions. Java 9 took it further by introducing four powerful enhancements to the Stream interface. ────────────────────────── 𝟭. 𝘁𝗮𝗸𝗲𝗪𝗵𝗶𝗹𝗲() A default method that takes elements from the stream as long as the given predicate holds true. The moment the predicate returns false, processing stops and the rest of the stream is discarded. 🔑 Key distinction from filter(): → filter() scans every element in the stream. → takeWhile() short-circuits as soon as the condition fails. Example: list.stream().takeWhile(i -> i % 2 == 0).collect(Collectors.toList()); Input: [2, 4, 1, 3, 6, 5, 8] Output: [2, 4] ← stops at first odd number ────────────────────────── 𝟮. 𝗱𝗿𝗼𝗽𝗪𝗵𝗶𝗹𝗲() The complement of takeWhile(). It drops elements as long as the predicate is true, then returns the remainder of the stream once the predicate fails. Example: list.stream().dropWhile(i -> i % 2 == 0).collect(Collectors.toList()); Input: [2, 4, 1, 3, 6, 5, 8] Output: [1, 3, 6, 5, 8] ← drops until first odd number ────────────────────────── 𝟯. 𝗦𝘁𝗿𝗲𝗮𝗺.𝗶𝘁𝗲𝗿𝗮𝘁𝗲() — Enhanced with a 3-Argument Form Java 8 introduced a 2-argument iterate() that could run infinitely: Stream.iterate(1, x -> x + 1) // infinite — needs .limit() Java 9 introduced a 3-argument form with a built-in termination predicate — analogous to a traditional for loop: Stream.iterate(1, x -> x < 5, x -> x + 1).forEach(System.out::println); Output: 1 2 3 4 This eliminates the risk of accidental infinite loops and makes the intent explicit. ────────────────────────── 𝟰. 𝗦𝘁𝗿𝗲𝗮𝗺.𝗼𝗳𝗡𝘂𝗹𝗹𝗮𝗯𝗹𝗲() A static method that wraps a value in a single-element stream if non-null, or returns an empty stream if null. Particularly useful inside flatMap() to handle null values gracefully without explicit null checks. Stream.ofNullable(null) → [] Stream.ofNullable(100) → [100] Practical use: list.stream() .flatMap(o -> Stream.ofNullable(o)) .collect(Collectors.toList()); // Null elements are silently skipped — no NullPointerException ────────────────────────── 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆𝘀 ✅ takeWhile() and dropWhile() enable positional, predicate-driven slicing of streams. ✅ The 3-arg iterate() provides a safe, bounded alternative to infinite stream generation. ✅ ofNullable() promotes null-safe stream pipelines without boilerplate null checks. These enhancements make stream pipelines more expressive, safer, and efficient. If you are working with Java 9+, these additions are well worth incorporating into your day-to-day code. 💬 Which of these do you find most useful in practice? Share your thoughts in the comments. #Java #Java9 #StreamAPI #FunctionalProgramming #BackendDevelopment #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
Day 15 — #100DaysJava three things in one day. Collections, DSA, and JUnit revision. ☕ Some days you just lock in. ----------------------------- Thing 1 — Collections detail I never knew I always used ArrayList without thinking. Today I learned there are actually three different ways to create a list in Java and they behave completely differently. Arrays.asList() — fixed size. You can update values but you cannot add or remove. Most people think it works like ArrayList. It does not. List.of() — completely immutable. Nothing can change. Not even the values. And it does not allow null. This is the safest option when you want data that should never change. ArrayList — fully dynamic. Add, remove, update — everything works. This is what you use when the data needs to change. One line to remember: Arrays.asList = fixed, List.of = immutable, ArrayList = flexible. Small difference. Huge impact in interviews and real code. --- Thing 2 — Queue in Java (DSA) Queue follows FIFO — First In, First Out. Like a line at a ticket counter. First person in line gets served first. Three ways to use Queue in Java: LinkedList — simple, most common PriorityQueue — automatically sorts elements, smallest comes out first ArrayDeque — fastest, preferred in interviews The method pairs every Java developer should know: offer() vs add() — offer is safe, add throws exception if it fails poll() vs remove() — poll returns null if empty, remove throws exception peek() vs element() — peek returns null if empty, element throws exception Always use the safe version — offer, poll, peek. Problems I practiced: Reverse a queue using a stack Generate binary numbers using a queue Implement queue using two stacks --- Thing 3 — JUnit 5 revision Went back through everything from Day 13 and 14. Rewrote test cases for Calculator and String utilities from scratch without looking at notes. The AAA pattern is now muscle memory — Arrange, Act, Assert. Also revised edge cases — null inputs, empty strings, boundary values. This is where real bugs hide. --- 15 days in. The concepts are connecting now. DSA problems feel less scary when you understand the data structures behind them. If you are learning Java — save this post. Arrays.asList vs List.of vs ArrayList comes up in almost every Java interview. 📌 Day 1 ........................................Day 15 ✅ What DSA topic do you find hardest to crack in interviews? Drop it below — let us discuss! 🙏 #Java #DSA #DataStructures #Queue #Collections #JUnit #100DaysOfJava #JavaDeveloper #LearningInPublic #BackendDevelopment #100DaysOfCode #InterviewPrep #CodingInterview
To view or add a comment, sign in
-
🚨 Java Exceptions — Complete Guide (Including Edge Cases Most People Miss) Exception handling is not just about try-catch… It’s about writing robust, production-ready code. Here’s a complete breakdown 👇 🔥 What is an Exception? 👉 An exception is an event that disrupts the normal flow of a program. ⚡ Types of Exceptions 1️⃣ Checked Exceptions (Compile-time) ✔ Must be handled ✔ Example: IOException, SQLException 2️⃣ Unchecked Exceptions (Runtime) ✔ Occur at runtime ✔ Example: NullPointerException, ArrayIndexOutOfBoundsException 3️⃣ Errors ✔ Serious issues (JVM level) ✔ Example: OutOfMemoryError 🧠 Exception Handling Keywords 🔹 try Wrap risky code 🔹 catch Handle exception 🔹 finally Always executes (mostly 👇 edge cases below) 🔹 throw Used to explicitly throw exception 🔹 throws Declares exception 💡 Basic Example try { int a = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } finally { System.out.println("Cleanup done"); } ⚠️ IMPORTANT EDGE CASES (Very Frequently Asked) 🔥 1. Will finally always execute? 👉 Mostly YES, but NOT in these cases: ❌ System.exit() is called ❌ JVM crashes 🔥 2. Return in try vs finally public int test() { try { return 1; } finally { return 2; } } 👉 Output: 2 💡 Explanation: Finally block overrides return from try 🔥 3. Multiple catch blocks order 👉 Always from specific → generic catch (ArithmeticException e) {} catch (Exception e) {} 🔥 4. Can we have try without catch? 👉 YES (with finally) try { // code } finally { // cleanup } 🔥 5. Can we have catch without try? 👉 ❌ NO (compile-time error) 🔥 6. What if exception not handled? 👉 Propagates to JVM → program terminates 🔥 7. Custom Exception class MyException extends Exception { MyException(String msg) { super(msg); } } 👉 Used for business logic validation 🔥 8. Difference between throw vs throws 👉 throw → used to throw exception 👉 throws → used in method signature 🔥 9. Checked vs Unchecked (Key Insight) 👉 Checked → forced handling 👉 Unchecked → programming errors 💡 Best practice: Avoid overusing checked exceptions in modern design 🔥 10. Try-with-resources (Java 7+) try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) { // use file } 👉 Automatically closes resources 🚀 Real-Time Usage (SDET Perspective) ✔ Handle API failures ✔ Retry logic ✔ Logging failures ✔ Resource cleanup (DB, files, drivers) ❌ Common Mistakes ❌ Empty catch blocks ❌ Catching generic Exception always ❌ Ignoring exception logs ❌ Using exceptions for normal flow 🎯 Final Thought Exception handling is not about catching errors… It’s about designing systems that fail gracefully and recover intelligently 💬 Question: What is one tricky exception scenario you faced in your project? #Java #ExceptionHandling #SDET #AutomationTesting #JavaConcepts #InterviewPrep
To view or add a comment, sign in
-
Why is String Immutable in Java? 🤔 4 Reasons Every Developer Should Know 👇 1️⃣ Security Strings are widely used in: passwords database URLs API endpoints file paths Example: String password = "admin123"; If Strings were mutable, another reference could change the value unexpectedly. Immutability helps keep sensitive data safer. 2️⃣ String Pool Performance Java reuses String literals from the String Pool. Example: String s1 = "Java"; String s2 = "Java"; Both can point to the same object. This saves memory. If Strings were mutable, changing one value would affect others. 3️⃣ Thread Safety Multiple threads can safely use the same String object because it cannot change. Example: String status = "SUCCESS"; Many threads can read it without locks. No race conditions. No synchronization needed. 4️⃣ Faster Hashing Strings are commonly used as keys in HashMap. Example: Map<String, Integer> map = new HashMap<>(); map.put("Java", 1); String hashcode can be cached after first calculation because the value never changes. That improves performance. That’s why String immutability is one of Java’s smartest design decisions. Which reason did you know already? 👇 #Java #String #StringImmutability #Backend #JavaDeveloper #Programming #InterviewPrep
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