Checked vs unchecked exceptions in Java:- The primary difference between checked and unchecked exceptions in Java lies in whether the compiler forces you to handle them. 🧐 Checked Exceptions Definition: These are exceptions that are checked at compile time. The Java compiler ensures that a program either handles them (using a try-catch block) or declares them (using the throws keyword in the method signature). Inheritance: They generally inherit from the java.lang.Exception class (excluding RuntimeException and its subclasses). Purpose: They represent situations that are typically recoverable and outside the direct control of the programmer, such as issues with I/O, database connections, or network access. The program is expected to anticipate and handle these errors. Examples: IOException, SQLException, FileNotFoundException. 🚫 Unchecked Exceptions Definition: These are exceptions that are not checked at compile time. The compiler does not force you to handle or declare them. Inheritance: They inherit from the java.lang.RuntimeException class or its subclasses, and also from java.lang.Error. Purpose: They usually represent programming errors or defects (logic errors) that often cannot be reasonably recovered from at runtime, such as passing a null argument or accessing an array index out of bounds. The expectation is that the code should be fixed to prevent these. Examples: NullPointerException, ArrayIndexOutOfBoundsException, IllegalArgumentException, ArithmeticException. #java #corejava #automationtesting #fullstackdevelopmment
Java Checked vs Unchecked Exceptions: What's the Difference?
More Relevant Posts
-
Mastering volatile in Java: Ensuring Thread-Safe Visibility Without Compromising Performance Deep Dive: volatile in Java Multithreading In concurrent Java applications, ensuring thread safety and memory visibility is critical. The volatile keyword is often misunderstood, so here’s a clear perspective. Purpose of volatile Guarantees visibility: A write to a volatile variable by one thread is immediately visible to others. Prevents caching inconsistencies: Threads always read the latest value from main memory. volatile boolean running = true;Limitations of volatile ❌ Does not ensure atomicity. Operations like counter++ remain non-thread-safe. ❌ Does not provide mutual exclusion. Use synchronized blocks or AtomicInteger for compound operations. ❌ Only applies guarantees to the volatile variable itself, not to other related variables.Practical Example in Spring Boot @Component public class BackgroundTask { private volatile boolean running = true; @Scheduled(fixedRate = 1000) public void task() { if (running) { // task logic } } public void stopTask() { running = false; } } Here, the volatile keyword ensures the flag update is immediately visible to the scheduled task, avoiding subtle synchronization issues.Takeaway: Use volatile for shared state that requires visibility guarantees, but for atomic operations or complex data structures, prefer Atomic classes or explicit synchronization. Understanding these nuances is essential for building robust, high-performance multithreaded applications in Java This makes it ideal for flags, signals, or implementing double-checked locking in singleton patterns. #Java #SpringBoot #Multithreading #Concurrency #DeveloperInsights #CleanCode
To view or add a comment, sign in
-
💡 Understanding Java Garbage Collection (GC): Why You Shouldn’t Call It Manually In Java, Garbage Collection (GC) automatically manages memory by removing unused objects from the heap — one of the core reasons Java is called a “memory-safe” language. 🗑️ How It Works: The Memory Cycle The JVM runs the garbage collector in the background, freeing up memory when it detects objects that are no longer reachable. This process often involves checking different memory pools, like the Young and Old generations, to efficiently prioritize removing short-lived objects. ⚠️ Can We Call It Manually? Yes, we can request garbage collection by calling: System.gc(); or Runtime.getRuntime().gc(); However, this is just a request — the JVM may or may not execute GC immediately. 🛑 Why We Shouldn’t Call GC Manually 🚫 It can impact performance significantly, as GC is a heavy operation that typically involves a "Stop-The-World" pause for the application. 🚫 The JVM’s own memory manager is much smarter at deciding the best, least disruptive time to perform GC based on heap usage and object lifetime. 🚫 Frequent or forced GC calls can cause unnecessary CPU usage and latency spikes, especially in high-throughput production systems. 👉 In short: Let the JVM handle it! The automatic garbage collector is optimized for efficiency, and manual intervention often does more harm than good. #Java #GarbageCollection #JVM #Performance #CodingTips #MemoryManagement
To view or add a comment, sign in
-
"The hidden truth about Java Generics:-It's all about the reference type"👇👇 Java Generics: Who Really Enforces Type Safety? Here’s a concept that even seasoned Java devs sometimes miss: 👉 The compiler enforces type safety based only on the reference side, not on the object creation side. Example: List<String> list = new ArrayList<String>(); // Safe List<String> list = new ArrayList<>(); // Type inferred List list = new ArrayList<String>(); // Compiles but not type-safe Even though the right side (new ArrayList<String>()) has <String>, the compiler stops enforcing type checks if the reference (List) is raw. So this compiles: List list = new ArrayList<String>(); list.add(10); list.add("Hi"); …but explodes later at runtime: String s = (String) list.get(0); // ClassCastException Why? Because Java generics use type erasure — at runtime, the JVM only sees raw types (no <String>, <Integer>, etc.). Summary: Compile-time → Checked by compiler (reference type matters) Runtime → JVM sees only raw types ✅ Always declare generics on the reference side: List<String> names = new ArrayList<>(); Because type safety travels with the reference, not the object creation. #Java #Generics #ProgrammingTips #TypeSafety #CodeBetter #SoftwareEngineering #JavaDeveloper
To view or add a comment, sign in
-
💡 == Operator vs. .equals() Method: Why Context Matters in Java 🧐 When comparing two variables or objects in Java, the choice between the == operator and the .equals() method is critical. They perform two fundamentally different types of comparisons! 1. The == Operator (Identity Comparison) What it compares: The == operator always compares memory addresses (references). Primitives: When used with primitives (int, char, boolean, etc.), it checks if the values stored in those memory locations are identical. Example: (5 == 5) is true. Objects: When used with objects (including String), it checks if the two variables refer to the exact same object in the Heap memory. Example: (obj1 == obj2) is only true if they point to the same memory location (same object ID). 2. The .equals() Method (Content Comparison) What it compares: The .equals() method is used to check for content equality. It determines if two objects are meaningfully equal based on their data. Default Behavior: Since this method is inherited from the base Object class, its default behavior is the same as == (checking references). The Power of Overriding: For almost all custom classes and core classes (like String), this method is overridden. String overrides .equals() to check if the sequence of characters (the content) is identical. You must override it in your custom classes (like Employee) to define when two distinct objects are considered equal based on their field values (id, name, etc.). Always use .equals() when comparing the content of objects, and reserve == for comparing primitives or checking if two variables are references to the exact same physical object. Thank you sir Anand Kumar Buddarapu,Saketh Kallepu,Uppugundla Sairam,Codegnan #Java #ProgrammingTips #OOP #ObjectEquality #SoftwareDevelopment #TechEducation
To view or add a comment, sign in
-
-
💫 Understanding the Exception Hierarchy in Java In Java, all errors and exceptions stem from a common base class called Throwable, forming a clear and well-structured exception hierarchy. 📌 1. Throwable Throwable is the superclass for all error and exception types in Java. It has two major subclasses: 🔹 Error 🔹 Exception 💥 2. Errors Errors represent serious issues that arise from the Java Virtual Machine (JVM). They are not meant to be handled by application code as they usually indicate conditions beyond the developer’s control. Examples: 🔸 OutOfMemoryError 🔸 VirtualMachineError 🔸 StackOverflowError ⚠️ 3. Exceptions Exceptions represent conditions that an application might want to catch and handle. Exceptions are classified into two categories: 🟧Checked Exceptions Checked exceptions are validated at compile-time. The compiler ensures the developer handles them using try-catch or throws. Common Checked Exceptions: ▪️ ClassNotFoundException ▪️ IOException ▪️ SQLException ▪️ InterruptedException 🔴Unchecked Exceptions Unchecked exceptions occur at runtime and extend from RuntimeException. They typically represent programming mistakes or logic errors. Common Unchecked Exceptions: 🔹NullPointerException 🔹 ArrayIndexOutOfBoundsException 🔹 ArithmeticException 🔹 ClassCastException ✨ Why This Hierarchy Matters 👉 Encourages clean, maintainable code 👉 Helps differentiate between recoverable and unrecoverable issues 👉 Improves application stability through structured error management
To view or add a comment, sign in
-
-
☘️ 1. Exception Hierarchy in Java In Java, every error or unusual event starts from the top-level class Throwable. From there, Java divides problems into two major categories: 1️⃣ Exception These are issues that your program can handle. Common examples include invalid input, missing files, number format issues, etc. 2️⃣ Error These indicate serious problems generated by the JVM itself. They’re not meant to be handled by programmers — like OutOfMemoryError or StackOverflowError. Within Exception, Java further classifies them into: ✔ Checked Exceptions ✔ Unchecked Exceptions ☘️ 2. Checked vs Unchecked Exceptions ✔ Checked Exceptions Verified by the compiler at compile time. Java forces you to handle them using try-catch or throws. Mostly occur when interacting with external systems (files, databases, networks). These help catch issues before the program runs. ✔ Unchecked Exceptions Not checked during compilation; they appear only at runtime. Usually caused by logical mistakes inside the code (like dividing by zero, null access, wrong index). Handling them is optional — but if not handled, the program crashes at runtime. Thanks to Anand Kumar Buddarapu sir for guiding me in strengthening these concepts. #Java #ExceptionHandling #JavaDeveloper #CodingConcepts #JavaExceptions #CheckedException #UncheckedException
To view or add a comment, sign in
-
-
Demystifying the `volatile` Keyword in Java Ever wondered what `volatile` really does in Java? Here’s a quick guide with real-world context! Single-threaded programs: In single-threaded applications, declaring a variable as `volatile` has almost no practical effect. Since only one thread interacts with the variable, there’s no risk of stale or inconsistent values due to caching or compiler optimisation—so `volatile` is generally redundant here. Multi-threaded programs: The real power of `volatile` shines in multi-threaded Java programs. When multiple threads access and modify a shared variable, declaring it as `volatile` guarantees: - Visibility: All threads see the latest value immediately; there’s no caching. - Ordering: Prevents subtle bugs from the JVM or CPU reordering reads and writes that involve volatile variables. However, do note that `volatile` does not ensure atomicity (for example, operations like `i++` can still result in race conditions). For atomic operations, consider using `synchronized` or Atomic classes. Typical use case: Perfect for communicating status flags, cancellation signals, or single-value indicators across threads — for example, a “stop” flag for gracefully shutting down a thread. The key takeaway? Use `volatile` in Java multi-threaded code when you need to keep all threads immediately aware of the latest value — but remember, it’s not an alternative for atomicity and synchronization. #Java #Programming #JavaDevelopment #SoftwareEngineering #Coding #Multithreading #Concurrency #JavaConcurrency #ThreadSafety #Performance #TechCommunity #DeveloperLife #CodeNewbie #SoftwareDeveloper #TechJobs #Engineering #Technology
To view or add a comment, sign in
-
-
Learn about the Arrays class in Java, its methods for sorting, searching, converting arrays to lists, and how to efficiently manipulate arrays
To view or add a comment, sign in
-
🚀 The Taxonomy of Java Exceptions: Checked vs. Unchecked 🚦 Exception handling is a critical part of Java development, and understanding the types of exceptions determines how you write robust code. Exceptions fall into two main categories: User-Defined and Built-in. The most crucial distinction is within the Built-in group: Checked vs. Unchecked. 1. Built-in Exceptions (The Core) These are the exceptions predefined by the Java language, divided into two types: 🔹 Checked Exceptions (The Compiler Enforces) Definition: These exceptions must be declared in a method signature (using throws) or handled using a try-catch block. The Java compiler checks for this requirement. If you ignore them, the code won't compile. Use Case: They represent expected, external problems that are usually recoverable, such as resource access issues. Examples: IOException, SQLException, FileNotFoundException, and ClassNotFoundException. 🔹 Unchecked Exceptions (The Runtime Problems) Definition: These exceptions do not need to be explicitly declared or handled (the compiler doesn't check them). They are a subclass of RuntimeException. Use Case: They typically indicate programming errors that could have been avoided with better coding practice (e.g., validating input or array bounds). Examples: NullPointerException (the most famous!), ArithmeticException (division by zero), and ArrayIndexOutOfBoundsException. 2. User-Defined Exceptions (The Custom Ones) Definition: These are custom exception classes created by the developer to handle specific application-level errors or business logic violations (e.g., an InsufficientFundsException). Implementation: By convention, if you want your custom exception to be Checked, you extend the base Exception class. If you want it to be Unchecked, you extend the RuntimeException class. Understanding the Checked/Unchecked split is vital because it tells you exactly what the compiler expects from you in terms of error management! Thank you sir Anand Kumar Buddarapu,Saketh Kallepu,Uppugundla Sairam,Codegnan #Java #ProgrammingTips #ExceptionHandling #CheckedExceptions #SoftwareDevelopment #TechEducation
To view or add a comment, sign in
-
-
Why does Integer a = 100; Integer b = 100; are equal But Not for 128? 🤔 Let’s talk about a sneaky little JVM optimization called Integer Caching, one that silently saves memory and boosts performance in your Java apps. What’s Happening Behind the Scenes? When you write: Integer a = 100; Integer b = 100; System.out.println(a == b); // true Both a and b point to the same cached Integer object, no new object created! But if you do this: Integer x = 128; Integer y = 128; System.out.println(x == y); // false Now they’re different objects. Why? Because Java caches Integer objects only in the range -128 to +127 by default. These are the most frequently used numbers (loop counters, indexes, etc.), so reusing them saves a lot of memory and object creation overhead. Remember == compares object references, not values. So always use: a.equals(b) for value comparisons. #java #jvm #performance
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