🚀 Mastering Dynamic Arrays in Java with ArrayList Today, I worked on an interesting problem that highlights the power of dynamic data structures in Java — specifically using ArrayList. 💡 Problem Insight: We are given multiple lines of input where each line can have a different number of integers. Then, we need to answer queries to fetch specific elements based on position. 👉 Sounds simple? The twist is: Each row has variable length Some queries may be invalid We must handle errors gracefully 🔧 Key Learning Points: ✅ Using ArrayList of ArrayLists to handle dynamic 2D data ✅ Understanding 0-based vs 1-based indexing ✅ Writing clean exception handling for invalid queries ✅ Avoiding fixed-size arrays when data is unpredictable 📌 Core Concept: ArrayList<ArrayList<Integer>> list = new ArrayList<>(); This allows each row to grow independently — something traditional arrays cannot handle efficiently. ⚠️ Important Tip: Instead of checking bounds manually every time, using try-catch simplifies error handling: public class Solution1 { public static void main(String[] args) { Scanner sn = new Scanner(System.in); int n = sn.nextInt(); // number of lines // ArrayList of ArrayLists ArrayList<ArrayList<Integer>> list = new ArrayList<>(); // Input lines for (int i = 0; i < n; i++) { int d = sn.nextInt(); // number of elements in this line ArrayList<Integer> row = new ArrayList<>(); for (int j = 0; j < d; j++) { row.add(sn.nextInt()); } list.add(row); } // Queries int q = sn.nextInt(); for (int i = 0; i < q; i++) { int x = sn.nextInt(); // line number int y = sn.nextInt(); // position try { // x-1 and y-1 because indexing starts from 0 System.out.println(list.get(x - 1).get(y - 1)); } catch (Exception e) { System.out.println("ERROR!"); }} sn.close();} } 🎯 Why this matters? Problems like these are commonly asked in: Coding interviews Competitive programming Real-world applications dealing with dynamic datasets 💬 As a Java trainer, I always emphasize: Choosing the right data structure simplifies half the problem. #Java #ArrayList #DataStructures #CodingInterview #JavaProgramming #Learning #Developers #ProgrammingTips
Mastering Dynamic Arrays in Java with ArrayList
More Relevant Posts
-
🚀 Java Revision Journey – Day 29 Today I revised TreeSet in Java, an important Set implementation used when sorted data is required. 📝 TreeSet Overview TreeSet is a class in java.util that implements the SortedSet and NavigableSet interfaces. It stores elements in a sorted order using a Red-Black Tree internally. 📌 Key Characteristics: • Stores unique elements only (no duplicates) • Maintains sorted order (ascending by default) • Does not allow null values (throws NullPointerException) • Provides navigation methods like higher(), lower(), ceiling(), floor() • Not thread-safe (can be synchronized using Collections.synchronizedSet()) 💻 Example TreeSet<Integer> set = new TreeSet<>(); set.add(30); set.add(10); set.add(20); System.out.println(set); // Output: [10, 20, 30] 🏗️ Constructors Default Constructor TreeSet<Integer> set = new TreeSet<>(); With Comparator TreeSet<Integer> set = new TreeSet<>(Comparator.reverseOrder()); From Collection TreeSet<Integer> set = new TreeSet<>(list); From SortedSet TreeSet<Integer> set = new TreeSet<>(sortedSet); 🔑 Basic Operations Adding Elements: • add() → Adds element in sorted order (duplicates ignored) Accessing Elements: • contains() → Checks existence • first() → Returns smallest element • last() → Returns largest element Removing Elements: • remove() → Removes specific element • pollFirst() / pollLast() → Removes first/last element 🔁 Iteration • Using enhanced for-loop • Using Iterator for (Integer num : set) { System.out.println(num); } ⚙️ Custom Sorting (Important) 👉 If objects don’t implement Comparable, use a Comparator: TreeSet<Integer> set = new TreeSet<>((a, b) -> b - a); 💡 Key Insight TreeSet is widely used when you need: • Automatically sorted data (no need to sort manually) • Fast search operations (O(log n)) • Range-based operations like finding closest elements • Implementing features like leaderboards, rankings, etc. 📌 Understanding TreeSet is essential for handling sorted and navigable data efficiently, especially in DSA and backend logic. Continuing to strengthen my Java fundamentals step by step 💪🔥 #Java #JavaLearning #TreeSet #DataStructures #JavaDeveloper #BackendDevelopment #Programming #JavaRevisionJourney 🚀
To view or add a comment, sign in
-
-
🚀 Java Revision Journey – Day 33 Today I revised TreeMap in Java, a powerful Map implementation used for storing sorted key-value pairs. 📝 TreeMap Overview TreeMap is a class in java.util that implements the Map interface and stores elements in a sorted order based on keys. Sorting can be done using: • Natural ordering (default) • Custom Comparator 📌 Key Characteristics: • Stores key → value pairs • Maintains sorted order of keys • Uses Red-Black Tree internally • Time complexity → O(log n) for operations • Does not allow null keys (allows null values) • Not thread-safe 💻 Example TreeMap<Integer, String> map = new TreeMap<>(); map.put(3, "C"); map.put(1, "A"); map.put(2, "B"); System.out.println(map); // Output: {1=A, 2=B, 3=C} 🏗️ Constructors Default Constructor TreeMap<Integer, String> map = new TreeMap<>(); With Comparator TreeMap<Integer, String> map = new TreeMap<>(Comparator.reverseOrder()); From Existing Map TreeMap<Integer, String> map = new TreeMap<>(existingMap); 🔑 Basic Operations Adding Elements: • put(key, value) → Inserts in sorted order Updating Elements: • put(key, newValue) → Replaces existing value Removing Elements: • remove(key) → Deletes mapping 🔁 Iteration for (Map.Entry<Integer, String> entry : map.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } ⚙️ Internal Working (Important) • Uses Red-Black Tree (self-balancing BST) • Maintains sorted keys automatically • Ensures balanced height → O(log n) operations 💡 Key Insight TreeMap is widely used when you need: • Sorted key-value data automatically • Range-based operations (like finding nearest keys) • Implementing leaderboards, rankings, ordered data • Efficient searching with ordered traversal Understanding TreeMap is essential when working with sorted maps and ordered data processing, especially in DSA and backend systems. Day 33 done ✅ — you're building strong mastery step by step 💪🔥 #Java #JavaLearning #TreeMap #DataStructures #JavaDeveloper #BackendDevelopment #Programming #JavaRevisionJourney 🚀
To view or add a comment, sign in
-
-
🚀 Java Revision Journey – Day 31 Today I revised HashMap in Java, one of the most important and widely used data structures for handling key-value pairs efficiently. 📝 HashMap Overview HashMap is a class in java.util that implements the Map interface. It stores data in key → value pairs, where: Keys are unique Values can be duplicated 📌 Key Characteristics: • Uses hashing for fast operations • Average time complexity → O(1) for insert, delete, search • Does not maintain insertion order • Allows one null key and multiple null values • Not thread-safe (use Collections.synchronizedMap() if needed) 💻 Declaration public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable • K → Key type • V → Value type ⚙️ Example HashMap<String, Integer> map = new HashMap<>(); map.put("A", 1); map.put("B", 2); map.put("A", 3); // Replaces old value System.out.println(map); // Order not guaranteed 📊 Capacity & Load Factor • Default capacity = 16 • Default load factor = 0.75 When threshold exceeds: New Capacity = Old Capacity × 2 Threshold Formula: Threshold = capacity × load factor 🏗️ Constructors Default HashMap<String, Integer> map = new HashMap<>(); With Initial Capacity HashMap<String, Integer> map = new HashMap<>(10); With Capacity + Load Factor HashMap<String, Integer> map = new HashMap<>(10, 0.75f); From Another Map HashMap<String, Integer> map = new HashMap<>(existingMap); 🔑 Basic Operations Adding Elements: • put(key, value) → Adds or inserts Updating Elements: • put(key, newValue) → Replaces existing value Removing Elements: • remove(key) → Deletes mapping 🔁 Traversal for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } ⚙️ Internal Working (Important) • Uses array of buckets • Index decided by hashCode() • Handles collisions using: → LinkedList (chaining) → Red-Black Tree (Java 8+) 💡 Key Insight HashMap is widely used when you need: • Fast lookup using keys (like ID → Object) • Caching and storing configurations • Frequency counting (very common in DSA problems) • Backend systems handling large-scale data Mastering HashMap is essential because it is the backbone of many real-world applications and frameworks. Day 31 done ✅ — Strong consistency, keep going 💪🔥 #Java #JavaLearning #HashMap #DataStructures #JavaDeveloper #BackendDevelopment #Programming #JavaRevisionJourney 🚀
To view or add a comment, sign in
-
-
💻 Getting Started with File Input/Output in Java When we first learn Java, most of our programs interact through the console using: System.in (input) System.out (output) But real-world programs often need to read from and write to files 📂 — here’s a simple breakdown of how that works. 📖 Reading from a File To read data from a file, we use the Scanner class along with the File class. First, create a file reference: File file = new File("input.txt"); Scanner sc = new Scanner(file); Now you can read data using methods like: next() nextInt() nextDouble() Example: while (sc.hasNextDouble()) { double value = sc.nextDouble(); // process value } ✍️ Writing to a File To write data, we use the PrintWriter class: PrintWriter out = new PrintWriter("output.txt"); out.println("Hello, people!"); ✔️ If the file exists → it gets overwritten ✔️ If it doesn’t exist → a new file is created ⚠️ Don’t Forget to Close! sc.close(); out.close(); Closing is important because: 👉 If you don’t close the writer, some data may never actually get written to the file. 🤔 Why pass File to Scanner but not PrintWriter? If you do: Scanner sc = new Scanner("input.txt"); It reads the string "input.txt", not the file contents. So for reading, you must pass a File object. For writing, PrintWriter can directly take the file path. 🔍 Understanding next() next() reads tokens, not lines. A token = any sequence of characters separated by whitespace (spaces, tabs, newlines). 🔧 Custom Delimiters You can control how input is split using useDelimiter() with regular expressions: sc.useDelimiter("[0-9]+"); 👉 This ignores digits and returns only non-digit sequences. 🔤 Reading Character by Character By default, Scanner reads word-by-word. To read one character at a time: sc.useDelimiter(""); while (sc.hasNext()) { char ch = sc.next().charAt(0); // process ch } Remember!!! Methods like nextInt() and nextDouble(): Skip whitespace before reading ❗ Do NOT consume the newline after the value 📚 Inspired by concepts from Cay Horstmann
To view or add a comment, sign in
-
𝐈𝐬 𝐄𝐯𝐞𝐫𝐲𝐭𝐡𝐢𝐧𝐠 𝐚 𝐎𝐛𝐣𝐞𝐜𝐭 𝐈𝐧 𝐉𝐚𝐯𝐚? In Java, we often hear that "everything is an object"—but that’s not entirely true. We still rely on 𝐩𝐫𝐢𝐦𝐢𝐭𝐢𝐯𝐞 𝐝𝐚𝐭𝐚 𝐭𝐲𝐩𝐞𝐬 (like int, char, and boolean) for performance and simplicity. However, there are moments when these primitives aren't enough. That is where 𝐖𝐫𝐚𝐩𝐩𝐞𝐫 𝐂𝐥𝐚𝐬𝐬𝐞𝐬 come into play. 𝐖𝐡𝐚𝐭 𝐢𝐬 𝐚 𝐖𝐫𝐚𝐩𝐩𝐞𝐫 𝐂𝐥𝐚𝐬𝐬? A Wrapper class is exactly what it sounds like: a class that "wraps" or encapsulates a primitive data type into an object. This allows you to treat a simple value as a full-fledged object. 𝐖𝐡𝐲 𝐝𝐨 𝐰𝐞 𝐧𝐞𝐞𝐝 𝐭𝐡𝐞𝐦? You might wonder, "Why go through the extra effort of creating an object?" Here are the primary reasons: •𝐂𝐨𝐥𝐥𝐞𝐜𝐭𝐢𝐨𝐧𝐬 & 𝐆𝐞𝐧𝐞𝐫𝐢𝐜𝐬: Java Collections (like ArrayList or HashMap) cannot store primitives. You can’t have an ArrayList<int>, but you can have an ArrayList<Integer>. •𝐍𝐮𝐥𝐥 𝐕𝐚𝐥𝐮𝐞𝐬: Primitives must have a value (e.g., 0 for int). Wrapper objects can be null, which is essential for representing "no data" in databases or APIs. •𝐔𝐭𝐢𝐥𝐢𝐭𝐲 𝐌𝐞𝐭𝐡𝐨𝐝𝐬: Wrapper classes provide helpful tools. For example, Integer.parseInt("123") or Character.isDigit('5'). 𝐓𝐡𝐞 𝐌𝐚𝐠𝐢𝐜 𝐨𝐟 𝐀𝐮𝐭𝐨𝐛𝐨𝐱𝐢𝐧𝐠 𝐚𝐧𝐝 𝐔𝐧𝐛𝐨𝐱𝐢𝐧𝐠 Java makes the transition between primitives and objects seamless through two features: 𝟏. 𝐀𝐮𝐭𝐨𝐛𝐨𝐱𝐢𝐧𝐠 This is the automatic conversion of a primitive to its corresponding wrapper class. 𝐄𝐱𝐚𝐦𝐩𝐥𝐞: Java int b = 357; Integer a = b; // 𝐀𝐮𝐭𝐨𝐦𝐚𝐭𝐢𝐜𝐚𝐥𝐥𝐲 𝐜𝐨𝐧𝐯𝐞𝐫𝐭𝐬 𝐢𝐧𝐭 -> 𝐈𝐧𝐭𝐞𝐠𝐞𝐫 𝟐. 𝐔𝐧𝐛𝐨𝐱𝐢𝐧𝐠 The reverse process: automatically converting a wrapper object back into a primitive. 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: Java Integer objectNum = 24; int primitiveNum = objectNum; // 𝐀𝐮𝐭𝐨𝐦𝐚𝐭𝐢𝐜𝐚𝐥𝐥𝐲 𝐜𝐨𝐧𝐯𝐞𝐫𝐭𝐬 𝐈𝐧𝐭𝐞𝐠𝐞𝐫 -> 𝐢𝐧𝐭 𝐅𝐢𝐧𝐚𝐥 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Wrapper classes are the "bridge" between the performance of procedural programming (primitives) and the power of Object-Oriented Programming (objects). Understanding when to use them is key to mastering Java's memory management and collection framework. A special Thank You to Syed Zabi Ulla Sir for beautifully explaining this core Java concept and making the logic so clear. #Java #Programming #CodingTips #BackendDevelopment #SoftwareEngineering #WrapperClasses #ObjectOrientedProgramming
To view or add a comment, sign in
-
💡 Java Basics Made Clear: `.equals()` vs `.hashCode()` (Plus a Spring Shortcut 🚀) This is one concept that looks simple—but can cause real bugs if misunderstood. 👉 What does `.equals()` do? It checks if two objects have the **same data (same content)**. 👉 What does `.hashCode()` do? It gives a **number (hash value)** that helps Java quickly find objects in collections like HashSet or HashMap. --- ⚠️ The Common Mistake: If you override `.equals()` but NOT `.hashCode()`, Java behaves unexpectedly. 👇 Example: ```java import java.util.*; class Person { String name; Person(String name) { this.name = name; } @Override public boolean equals(Object o) { return ((Person) o).name.equals(this.name); } } public class Test { public static void main(String[] args) { Set<Person> set = new HashSet<>(); set.add(new Person("Kartik")); set.add(new Person("Kartik")); System.out.println(set.size()); // ❌ Output: 2 (Should be 1) } } ``` 🤔 Why? * `.equals()` says both objects are SAME ✅ * But `.hashCode()` is different ❌ * So Java treats them as different objects --- ✅ The Fix: ```java @Override public int hashCode() { return name.hashCode(); } ``` ✔ Now output → `1` (Correct) --- 🚀 Spring / Lombok Shortcut (Best Practice) Instead of manually writing both methods, you can use Lombok: ```java import lombok.*; @Data class Person { private String name; } ``` 👉 `@Data` automatically generates: * `.equals()` * `.hashCode()` * getters, setters, and more You can also use: ```java @EqualsAndHashCode ``` 📌 This avoids human error and keeps code clean. --- 📌 Simple Rule: If two objects are equal using `.equals()` ➡️ They MUST have the same `.hashCode()` --- 🚀 Final Takeaway: * `.equals()` → checks equality * `.hashCode()` → helps in fast lookup * Always override BOTH or use Lombok annotations --- #Java #SpringBoot #Lombok #BackendDevelopment #CodingBestPractices #Developers
To view or add a comment, sign in
-
🚀 Understanding Generics in Java – Write Flexible & Type-Safe Code If you’ve ever worked with collections like List or Map, you’ve already used Generics — one of the most powerful features in Java. 🔹 What are Generics? Generics allow you to write classes, interfaces, and methods with a placeholder for the data type. This means you can reuse the same code for different data types while maintaining type safety. 🔹 Why use Generics? ✔️ Eliminates type casting ✔️ Provides compile-time type safety ✔️ Improves code reusability ✔️ Makes code cleaner and more readable 🔹 Simple Example: List<String> names = new ArrayList<>(); names.add("Sneha"); // names.add(10); ❌ Compile-time error 🔹 Generic Class Example: class Box<T> { private T value; public void set(T value) { this.value = value; } public T get() { return value; } } 🔹 🔥 Advanced Concepts Explained 🔸 1. Bounded Types (Restricting Types) You can limit what type can be passed: class NumberBox<T extends Number> { T value; } 👉 Only Integer, Double, etc. are allowed (not String) 🔸 2. Wildcards (?) – Flexibility in Collections ✔️ Unbounded Wildcard List<?> list; 👉 Can hold any type, but limited operations ✔️ Upper Bounded (? extends) List<? extends Number> list; 👉 Accepts Number and its subclasses 👉 Used when reading data ✔️ Lower Bounded (? super) List<? super Integer> list; 👉 Accepts Integer and its parent types 👉 Used when writing data 💡 Rule: PECS → Producer Extends, Consumer Super 🔸 3. Generic Methods public <T> void print(T data) { System.out.println(data); } 👉 Works independently of class-level generics 🔸 4. Type Erasure (Important for Interviews) Java removes generic type info at runtime: List<String> → List 👉 No runtime type checking 👉 Only compile-time safety 🔸 5. Multiple Bounds <T extends Number & Comparable<T>> 👉 A type must satisfy multiple conditions 🔸 6. Restrictions of Generics ❌ Cannot use primitives (int, double) → use wrappers ❌ Cannot create generic arrays ❌ Cannot use instanceof with generics 💡 Final Insight: Generics are not just a feature—they are a design tool that helps build scalable, reusable, and maintainable applications. Mastering advanced concepts like wildcards and type erasure can set you apart as a strong Java developer. #Java #Generics #AdvancedJava #Programming #JavaDeveloper #Coding #TechInterview
To view or add a comment, sign in
-
Java 26 just dropped! But most developers have not even adopted Java 21 features yet. Here are 5 modern Java features you should be using every single day. —— 1. Switch Expressions: clean and exhaustive (Java 14+) // Before: verbose, fall-through prone String label; switch (status) { case ACTIVE: label = "Active"; break; case PENDING: label = "Pending"; break; default: label = "Unknown"; } // After: String label = switch (status) { case ACTIVE -> "Active"; case PENDING -> "Pending"; default -> "Unknown"; }; No fall-through bugs. Compiler ensures all cases are handled. —— 2. Text Blocks: readable multiline strings (Java 15+) // Before: String json = "{\n \"name\": \"Alice\",\n \"role\": \"admin\"\n}"; // After: String json = """ { "name": "Alice", "role": "admin" } """; Clean SQL, JSON, HTML — no escape characters. Just readable strings. —— 3. Optional: use it properly (Java 8+, daily practice) // Bad: Optional user = userRepo.findById(id); if (user.isPresent()) { return user.get(); } return null; // Good: return userRepo.findById(id) .orElseThrow(() -> new UserNotFoundException("User not found: " + id)); Optional exists to eliminate null checks — not to wrap them. Never use .get() alone. Always orElseThrow() or orElse(). —— 4. Pattern Matching for Switch: Java 21 flagship (Java 21) // Before: fragile instanceof chain if (obj instanceof Integer i) return "int: " + i; if (obj instanceof String s) return "str: " + s; // After: clean, compiler-verified return switch (obj) { case Integer i -> "int: " + i; case String s -> "str: " + s; default -> "unknown"; }; // Even better with guards: return switch (order) { case Order o when o.isPaid() -> "Paid"; case Order o when o.isPending() -> "Pending"; default -> "Unknown"; }; Replaces entire if-instanceof chains. Safe, readable, exhaustive. —— 5. New String methods: small but mighty (Java 11–17) input.strip(); // Unicode-aware trim() input.isBlank(); // true if empty or whitespace input.repeat(3); // repeats string N times "line1\nline2".lines(); // Stream by line "hello %s".formatted("world"); // cleaner than String.format() No libraries needed. Used constantly. Zero excuses not to. ---------------------------------------------------------------- Java is not the verbose language it used to be. Pick one feature. Use it in your next PR. Then the next one. Java 26 post coming next. Stay tuned! Which one are you already using daily? Drop a number below.. #Java #Java17 #Java21 #BackendDevelopment #SpringBoot #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
🚀 Java Wrapper Classes: Hidden Behaviors That Trip Up Even Senior Developers Most developers know wrapper classes. Very few understand what happens under the hood — and that’s exactly where top companies separate candidates. Here’s a deep dive into the concepts that actually matter 1. Integer Caching Integer a = 4010; Integer b = 4010; System.out.println(a == b); // false Integer c = 127; Integer d = 127; System.out.println(c == d); // true Q.Why? Java caches Integer values in the range -128 to 127. Inside range → same object (cached) Outside range → new object (heap) 💡 Pro Insight: You can even extend this range using: -XX:AutoBoxCacheMax=<size> 2. == vs .equals() — Silent Bug Generator System.out.println(a == b); // false → reference comparison System.out.println(a.equals(b)); // true → value comparison Using == with wrapper objects is one of the most common production bugs. Rule: == → checks memory reference .equals() → checks actual value 3. hashCode() vs identityHashCode() System.out.println(a.hashCode()); System.out.println(System.identityHashCode(a)); Two objects can have: Same value → same hashCode() Different memory → different identityHashCode() 4. Silent Overflow in Primitive Conversion Integer a = 4010; byte k = a.byteValue(); // -86 What actually happens: byte range = -128 to 127 4010 % 256 = 170 170 interpreted as signed → -86 No error. No warning. This is how real-world bugs sneak into systems. 5. Powerful Utility Methods (Underrated) Integer.toBinaryString(4010); Integer.toHexString(4010); Integer.bitCount(4010); Integer.numberOfLeadingZeros(4010); Useful in: Bit manipulation Competitive programming Low-level optimization 6. Character & Boolean — Also Cached Boolean b1 = true; Boolean b2 = true; System.out.println(b1 == b2); // true Boolean → fully cached Character → cached in ASCII range 7. Character Utilities = Clean Code Character.isLetter('a'); Character.isDigit('3'); Character.isWhitespace('\t'); Character.toUpperCase('a'); The Big Picture Wrapper classes are NOT just primitives with methods. They reveal how Java handles: Memory optimization Object identity Autoboxing behavior Performance trade-offs A big thanks to my mentors Syed Zabi Ulla, peers, and the amazing developer community Oracle for continuously pushing me to go beyond basics and truly understand concepts at a deeper level. #Java #JVM #CoreJava #CodingInterview #FAANG #SoftwareEngineering #BackendDevelopment #ProgrammingTips
To view or add a comment, sign in
-
-
🚀 Today I dived deep into Exception Handling in Java! Have you ever seen a "software not responding" popup or had an app suddenly crash?,. That is often because of an unhandled exception. What is an Exception? In Java, an exception is an unusual event that occurs during the runtime (execution) of a program,,. It is usually triggered by faulty user input—like trying to divide a number by zero or providing a string when a number is expected,,. If these aren't handled, they lead to abrupt termination, which ruins the user experience and can cause significant losses for a company,. How it works behind the scenes: When a problem occurs, the JVM automatically creates an Exception Object,. This object contains the "What" (type of error), "Where" (line number), and "Why" (the reason),. If we don't catch it, the Default Exception Handler prints the error and stops the program immediately,. The Solution: Try-Catch Blocks To ensure normal termination, we follow three simple steps: 1.Identify risky lines of code where a problem might occur,. 2.Place that code inside a try block,. 3.Write a catch block to intercept the exception object and handle it gracefully,. Pro Tip: The Order of Catch Blocks Matters! ⚠️ You can have multiple catch blocks for different errors (like ArithmeticException or ArrayIndexOutOfBoundsException),. However, you must always put specific exceptions first and the general Exception class last,. If you put the general one first, the specific ones become unreachable code because the general class has the capability to catch everything. Code Example: import java.util.Scanner; public class ExceptionDemo { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Connection established."); try { // Step 1 & 2: Identify and wrap risky code, System.out.print("Enter numerator: "); int a = scan.nextInt(); System.out.print("Enter denominator: "); int b = scan.nextInt(); int result = a / b; // Risky line: ArithmeticException if b=0 System.out.println("Result: " + result); } catch (ArithmeticException e) { // Step 3: Handle specific exception, System.out.println("Error: Please enter a non-zero denominator."); } catch (Exception e) { // General catch-all for other unexpected issues System.out.println("Some technical problem occurred."); } System.out.println("Connection terminated.");, } } Looking forward to exploring rethrowing and ducking exceptions tomorrow!. #Java #Coding #BackendDevelopment #ExceptionHandling #LearningJourney #SoftwareEngineering #TapAcademy
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