☕ #ThinkingInJava — Post No. 6 💡 Tricky Exception Handling Behavior Consider this code: class Test { public static void main(String[] args) { try { System.out.println(10/0); } catch (ArithmeticException e) { System.out.println(10/0); } finally { String s = null; System.out.println(s.length()); } } } 🤔 What will be the final exception? Many expect ArithmeticException. But the output is: Exception in thread "main" java.lang.NullPointerException 🎯 Key Concept 👉 The default exception handler handles only ONE exception at a time — the most recently raised exception. Execution flow: 1️⃣ 10/0 in try → ArithmeticException 2️⃣ 10/0 in catch → ArithmeticException again 3️⃣ s.length() in finally → NullPointerException Since the finally block runs last, the NullPointerException becomes the most recent exception. So the JVM reports NullPointerException, not ArithmeticException. 🔖 Takeaway When multiple exceptions occur, the most recently thrown exception is the one handled by the JVM's default exception handler. #Java #AutomationMeetsFuture #TestAutomationSpecialist
Java Exception Handling: NullPointerException Triggers JVM
More Relevant Posts
-
📌 Exception Handling in Java — Understanding Exception Propagation The diagram represents how Java manages exceptions using the call stack and identifies the appropriate handler. 🔹 Execution Flow: • An exception is thrown in "divideByZero()" • The method does not handle it → exception is propagated • "computeDivision()" receives the exception but does not handle it • The exception continues to propagate up the call stack • "main()" contains the appropriate "catch" block and handles the exception 🔹 Internal Mechanism: The JVM performs stack unwinding, examining each method in the call stack sequentially to locate a matching exception handler. If no handler is found, the program terminates and a stack trace is generated. 🔹 Key Takeaways: • Exception propagation ensures centralized and structured error handling • Not every method should handle exceptions — only where recovery is possible • Proper handling improves system stability and maintainability 🔹 Best Practices: ✔ Catch specific exceptions instead of generic ones ✔ Avoid unnecessary try-catch blocks ✔ Use meaningful logging for debugging and monitoring ✔ Rethrow exceptions with additional context when needed ✔ Design applications with clear error-handling strategies 🔹 Conclusion: Effective exception handling is not just a language feature — it is a critical part of designing robust and maintainable systems. #Java #ExceptionHandling #SoftwareEngineering #BackendDevelopment #CleanCode
To view or add a comment, sign in
-
-
🎯 Java Performance: String Concatenation Stop using `+` for string concatenation in loops: ```java // Bad - O(n²) String result = ""; for (int i = 0; i < 1000; i++) { result += i; // Creates new String each time } // Good - O(n) StringBuilder sb = new StringBuilder(); for (int i = 0; i < 1000; i++) { sb.append(i); } String result = sb.toString(); // Better - Java 8+ streams String result = IntStream.range(0, 1000) .mapToObj(String::valueOf) .collect(Collectors.joining()); ``` What's your Java performance lesson? #Java #Performance #StringBuilder #Optimization
To view or add a comment, sign in
-
🚀 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
-
-
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
-
-
Day 50 – Java 2026: Smart, Stable & Still the Future Multi-Line Static Initializer in Java A multi-line static initializer is a static block that contains multiple statements used to initialize static variables with logic. It executes only once when the class is loaded into memory by the JVM ClassLoader. This is useful when initialization requires conditions, calculations, or multiple steps, not just a single assignment. class Configuration { static int maxUsers; static String environment; static { System.out.println("Static initializer started"); maxUsers = 100; if(maxUsers > 50) { environment = "Production"; } else { environment = "Development"; } System.out.println("Environment: " + environment); } public static void main(String[] args) { System.out.println("Application Started"); System.out.println("Max Users: " + maxUsers); } } Output Static initializer started Environment: Production Application Started Max Users: 100 Key Idea: A multi-line static initializer allows complex initialization logic and runs only once during class loading, making it efficient for setting up configurations, constants, or system settings. #Java #JavaDeveloper #JVM #Programming #BackendDevelopment
To view or add a comment, sign in
-
📘 1. TOP 15 CORE JAVA QUESTIONS (WITH SHORT ANSWERS) 🔥 Core Java (1–15) 1. What is JVM? → Runs Java bytecode 2. JDK vs JRE → Dev vs Runtime 3. == vs equals() → Reference vs Content 4. Why String immutable? → Security + caching 5. String pool? → Memory optimization 6. OOP principles → 4 pillars 7. Encapsulation → Data hiding 8. Inheritance → Code reuse 9. Polymorphism → Many forms 10. Abstraction → Hiding complexity 11. final vs finally vs finalize 12. Exception hierarchy 13. Checked vs unchecked 14. Multithreading → concurrency 15. Synchronization → thread safety # java #Code #Java #springboot
To view or add a comment, sign in
-
30 Days - 30 Questions Journey Completed! 💻🔥 💡 Question: What is the difference between volatile and Atomic variables in Java? 🔹 volatile volatile ensures visibility of changes across threads. It guarantees that a variable is always read from main memory, not from thread cache. Example: ```java id="p8k3l2" volatile int count = 0; ``` --- 🔹 Problem with volatile volatile does NOT guarantee atomicity. Example: ```java id="x7m2q1" count++; // Not thread-safe ``` Because this operation is: Read → Modify → Write Multiple threads can interfere here. --- 🔹 Atomic Variables Atomic variables provide both: • Visibility • Atomicity Example: ```java id="d3k9s1" AtomicInteger count = new AtomicInteger(0); count.incrementAndGet(); ``` --- 🔹 Key Differences volatile • Ensures visibility • Not thread-safe for operations • Lightweight Atomic • Ensures visibility + atomicity • Thread-safe operations • Uses CAS (Compare-And-Swap) --- ⚡ Quick Facts • volatile is good for flags (true/false) • Atomic is used for counters and updates • Atomic classes are part of java.util.concurrent --- 📌 Interview Tip Use volatile for simple state visibility Use Atomic when performing read-modify-write operations --- Follow this series for 30 Days of Java Interview Questions. #java #javadeveloper #codinginterview #backenddeveloper #softwareengineer #programming #developers #tech
To view or add a comment, sign in
-
-
Still using loops in Java? You might be missing something powerful… 🚀 Day 6 of Prepare with Pankaj 💻 🔹 What is Stream? A Stream is a sequence of elements used to process collections (List, Set) in a functional and efficient way. 🔹 Why use Streams? ✔ Less code (no complex loops) ✔ Better readability ✔ Easy parallel processing 🔹 Common Operations: 👉 filter() Used to filter data Example: Get only even numbers 👉 map() Used to transform data Example: Multiply each number by 2 👉 collect() Used to collect the result into a List or Set 🔹 Simple Example: import java.util.*; import java.util.stream.*; public class Main { public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); List<Integer> result = list.stream() .filter(n -> n % 2 == 0) .map(n -> n * 2) .collect(Collectors.toList()); System.out.println(result); } } 💡 Conclusion: Streams help you write clean, concise, and efficient code. Must-know for every Java developer! #Java #Java8 #Streams #BackendDeveloper #Coding #PrepareWithPankaj 🚀
To view or add a comment, sign in
-
-
🚀 Day 2 – Subtle Java Behavior That Can Surprise You Today I explored the difference between "==" and ".equals()" in Java — and it’s more important than it looks. String a = "hello"; String b = "hello"; System.out.println(a == b); // true System.out.println(a.equals(b)); // true Now this: String c = new String("hello"); System.out.println(a == c); // false System.out.println(a.equals(c)); // true 👉 "==" compares reference (memory location) 👉 ".equals()" compares actual content 💡 The catch? Because of the String Pool, sometimes "==" appears to work correctly… until it doesn’t. This small misunderstanding can lead to tricky bugs, especially while working with collections or APIs. ✔ Rule I’m following: Always use ".equals()" for value comparison unless you explicitly care about references. #Java #BackendDevelopment #JavaBasics #LearningInPublic
To view or add a comment, sign in
-
💡 Question: What is JVM Architecture in Java? 🔹 What is JVM? JVM (Java Virtual Machine) is a part of JRE that runs Java bytecode and provides platform independence. Write Once, Run Anywhere. 🔹 How Java Code Executes .java file → compiled by javac → .class (bytecode) → JVM loads and executes it 🔹 JVM Components ClassLoader Loads .class files into memory Execution Engine Executes bytecode (Interpreter + JIT Compiler) Runtime Data Areas Memory used during execution 🔹 Runtime Data Areas Method Area Stores class metadata, static variables, constants Heap Stores objects and instance variables Java Stack Stores method calls and local variables PC Register Stores current executing instruction address 🔹 Execution Flow ClassLoader → Execution Engine → Memory (Heap + Stack) → Output 🔹 Key Concepts Platform Independence Same bytecode runs on any OS JIT Compiler Improves performance by converting bytecode to native code Garbage Collection Automatically removes unused objects ⚡ Quick Summary • JVM executes Java bytecode • Contains ClassLoader, Execution Engine, Memory Areas • Provides platform independence • Handles memory management automatically 📌 Interview Tip Focus on Heap vs Stack, ClassLoader working, and JIT compiler — these are most asked in interviews. Follow this series for 30 Days of Java Interview. #java #javadeveloper #jvm #codinginterview #backenddeveloper #softwareengineer #programming #developers #tech
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