Exception handling became much clearer when I actually understood how try-catch works 👇 Earlier, I just used it to “stop crashes” without really knowing what was happening 🔹 Basic idea 👉 "try" → code that might fail 👉 "catch" → handle the error 🔹 Simple example try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } ✔ Instead of crashing, the error is handled 🔹 Multiple catch blocks You can handle different exceptions differently: try { int[] arr = new int[5]; arr[5] = 10; } catch (ArithmeticException e) { System.out.println("Math error"); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Index out of bounds"); } catch (Exception e) { System.out.println("General error"); } 👉 More specific exceptions should come first 🔹 finally block Runs no matter what (exception or not): try { // risky code } catch (Exception e) { // handle } finally { System.out.println("Always runs"); } ✔ Used for cleanup (closing files, DB connections, etc.) 🔹 Important things I learned ❌ Don’t use empty catch blocks ❌ Don’t catch Exception blindly every time ❌ Don’t hide errors — log or handle properly 🧠 Simple way I remember it 👉 try → risky code 👉 catch → handle problem 👉 finally → cleanup Still learning, but understanding this properly made my code more stable and easier to debug 💡 If you’re learning Java, what confused you most about try-catch? 👇 #Java #ExceptionHandling #Developers #Programming #LearningInPublic
Understanding Try-Catch Blocks in Java Exception Handling
More Relevant Posts
-
⏳ Day 20 – 1 Minute Java Clarity – Method Overloading vs Overriding Same name… totally different behaviour! 🤯 📌 What is Method Overloading? Same method name — different parameters — in the SAME class. 👉 Decided at Compile Time → Static Polymorphism. 📌 Example: class Calculator { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } int add(int a, int b, int c) { return a + b + c; } } 👉 Java picks the right method based on arguments you pass ✅ 📌 What is Method Overriding? Child class provides its OWN implementation of a parent class method. 👉 Decided at Runtime → Dynamic Polymorphism. 📌 Example: class Animal { void sound() { System.out.println("Some sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Dog barks!"); } } Animal a = new Dog(); a.sound(); // Output: Dog barks! ✅ 💡 Real-time Example: Overloading → Same coffee machine ☕ Small cup button → 100ml Large cup button → 300ml Same button name, different output based on input! Overriding → Company policy 📋 Head office says "work 9 to 5" Branch office overrides → "work 8 to 4" Same rule name, child changes the behaviour! ⚠️ Interview Trap: Can we override a static method? 👉 No! Static methods belong to the class — not the object. 👉 It's called Method Hiding, not Overriding! 💡 Quick Summary: | Feature | Overloading | Overriding | | Class | Same | Parent & Child | | Parameters | Different | Same | | Time | Compile time | Runtime | | Keyword | None | @Override | 🔹 Next Topic → Polymorphism in Java Which one confuses you more — overloading or overriding? Drop 👇 #Java #JavaProgramming #MethodOverloading #MethodOverriding #OOPs #CoreJava #JavaDeveloper #BackendDeveloper #Coding #Programming #SoftwareEngineering #LearningInPublic #100DaysOfCode #ProgrammingTips #1MinuteJavaClarity
To view or add a comment, sign in
-
-
what is serialization and deserialization ? Serialization is the process of converting an in-memory object (like a class instance in your backend code) into a format that can be easily stored or transmitted, such as: JSON XML Protocol Buffers Example: You have a user object in code: { "id": 1, "name": "Aman" } When you send this over an API, it gets serialized into JSON so it can travel over HTTP. What is Deserialization? Deserialization is the reverse process — converting the transmitted data (like JSON from an API request/response) back into an in-memory object your program can use. Example: You receive this JSON from a request: { "id": 1, "name": "Aman" } Your backend converts it into a language-specific object (e.g., a class instance in Java, Python, Node.js, etc.). Serialization = Packing your object into a suitcase (JSON) to travel Deserialization = Unpacking it back into usable form at the destination
To view or add a comment, sign in
-
𝗠𝗮𝘀𝘁𝗲𝗿𝗶𝗻𝗴 𝗝𝗮𝘃𝗮’𝘀 𝘃𝗮𝗿 Recently, I explored how Java introduced Local Variable Type Inference (var) in Java 10 and how it transformed the way developers write cleaner and more expressive code. Java has traditionally been known for its verbosity. With the introduction of var through Project Amber, the language took a major step toward modern programming practices—balancing conciseness with strong static typing. 𝗪𝗵𝗮𝘁 𝗜 𝗹𝗲𝗮𝗿𝗻𝗲𝗱: • var allows the compiler to infer types from initializers, reducing boilerplate without losing type safety. • It is not a keyword, but a reserved type name, ensuring backward compatibility. • Works only for local variables, not for fields, method parameters, or return types. • The inferred type is always static and compile-time resolved—no runtime overhead. • Powerful in handling non-denotable types, including anonymous classes and intersection types. Must be used carefully: • Avoid when the type is unclear from the initializer • Prefer when the initializer clearly reveals the type (e.g., constructors or factory methods) • Enhances readability only when the initializer clearly conveys the type. 𝗞𝗲𝘆 𝘁𝗮𝗸𝗲𝗮𝘄𝗮𝘆: var is not just about writing less code—it’s about writing clearer, more maintainable code when used correctly. The real skill lies in knowing when to use it and when not to. A special thanks to Syed Zabi Ulla sir at PW Institute of Innovation for their clear explanations and continuous guidance throughout this topic. #Java #Programming #SoftwareDevelopment #CleanCode #Java10 #Developers #LearningJourney
To view or add a comment, sign in
-
⏳ Day 21 – 1 Minute Java Clarity – Polymorphism Explained Simply 🎭 Same action… different behaviour! 🔥 📌 What is Polymorphism? 👉 “Poly” = Many 👉 “Morphism” = Forms ✔ One method behaves differently based on the object 👉 It is the core of OOP and makes code flexible & reusable 📌 Types of Polymorphism 1️⃣ Compile-Time Polymorphism 👉 Achieved using Method Overloading class Calculator { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } } ✔ Same method → different parameters ✔ Decided at compile time 2️⃣ Runtime Polymorphism 👉 Achieved using Method Overriding class Animal { void sound() { System.out.println("Some sound"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks!"); } } Animal a = new Dog(); a.sound(); // Dog barks! ✔ Parent reference → child object ✔ Decided at runtime 💡 Real-time Example 🎮 Game Character Same action → "attack()" Warrior → uses sword ⚔️ Archer → uses bow 🏹 Mage → casts spell 🔮 👉 Same method → different behaviour ⚠️ Interview Trap 👉 Can we achieve polymorphism without inheritance? ✔ YES (Using Method Overloading) ❌ NO (for Runtime polymorphism – needs inheritance) 💡 Quick Summary TypeMethodTimeExampleCompile-TimeOverloadingCompile Timeadd()RuntimeOverridingRuntimesound() 🔹 Why Polymorphism matters? ✔ Cleaner code ✔ Easy to extend ✔ Reduces duplication ✔ Helps in real-world system design 🔹 Next Topic → Encapsulation in Java 🔐 Which type do you find tricky — Compile-time or Runtime? Drop 👇 #Java #JavaProgramming #Polymorphism #OOPs #CoreJava #JavaDeveloper #BackendDeveloper #Coding #Programming #SoftwareEngineering #LearningInPublic #100DaysOfCode #ProgrammingTips #1MinuteJavaClarity
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟯: 𝗣𝗶𝘃𝗼𝘁𝗶𝗻𝗴 𝘄𝗵𝗲𝗻 𝘁𝗵𝗲 𝘀𝗶𝗺𝗽𝗹𝗲 𝗮𝗽𝗽𝗿𝗼𝗮𝗰𝗵 𝗳𝗮𝗶𝗹𝘀. 🧠 The screenshot doesn’t show the struggle, It just shows the final Accepted code. ✅𝗙𝗼𝗿 𝗗𝗮𝘆 𝟯, I tackled this LeetCode problem: "𝟮𝟴𝟯𝟵. 𝗖𝗵𝗲𝗰𝗸 𝗶𝗳 𝗦𝘁𝗿𝗶𝗻𝗴𝘀 𝗖𝗮𝗻 𝗯𝗲 𝗠𝗮𝗱𝗲 𝗘𝗾𝘂𝗮𝗹 𝗪𝗶𝘁𝗵 𝗢𝗽𝗲𝗿𝗮𝘁𝗶𝗼𝗻𝘀 𝗜." My goal was simple: just get that Java solution 𝗔𝗰𝗰𝗲𝗽𝘁𝗲𝗱. 𝗧𝗵𝗲 𝗙𝗶𝗿𝘀𝘁 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: I initially started with a classic iterative method, trying to loop through and swap indices to check equality. But I kept hitting unexpected logic errors that were overcomplicating a simple problem. I realized the "obvious" way wasn't the "correct" way. 𝗧𝗵𝗲 𝗣𝗶𝘃𝗼𝘁: Instead of getting stuck on the iteration, I looked at the core constraint. The operation only allows swaps between characters exactly 2 indices apart (e.g., indices 0 and 2, 1 and 3). 𝗧𝗵𝗲 𝗕𝗿𝗲𝗮𝗸𝘁𝗵𝗿𝗼𝘂𝗴𝗵: I realized that if strings are length 4, characters at even indices (0, 2) can only ever interact with each other. The same applies to odd indices (1, 3). So, instead of looping, I just needed to compare those two specific pairs directly. ✅𝗧𝗵𝗲 𝗿𝗲𝘀𝘂𝗹𝘁: I simplified the code into two simple comparison blocks and hit Submit. That final 𝟭𝗺𝘀 𝗥𝘂𝗻𝘁𝗶𝗺𝗲 (𝗕𝗲𝗮𝘁𝗶𝗻𝗴 𝟵𝟵.𝟲𝟲%) was the perfect confirmation that the pivot was the right choice. Sometimes the best engineering decision is to tear down what isn't working and start with a cleaner logic. #Java #JavaDeveloper #DSA #Strings #BuildInPublic #EngineeringStudent #DAY3
To view or add a comment, sign in
-
-
𝗝𝗮𝘃𝗮’𝘀 𝗠𝗼𝘀𝘁 𝗔𝗻𝗻𝗼𝘆𝗶𝗻𝗴 𝗢𝘃𝗲𝗿𝗹𝗼𝗮𝗱: List.remove(index) 𝘃𝘀 remove(value) ⚠️ 𝗦𝗮𝗺𝗲 𝗺𝗲𝘁𝗵𝗼𝗱 - 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝘁 𝗺𝗲𝗮𝗻𝗶𝗻𝗴 🤯 remove(int index) vs remove(Object o) Tiny type change - different behavior. 𝗪𝗵𝗲𝗿𝗲 𝗶𝘁 𝗯𝗿𝗲𝗮𝗸𝘀 🔥 List<Integer> list = new ArrayList<>(List.of(10,20,30)); list.remove(1); // index -> removes 20 Integer i = 1; list.remove(i); // object -> tries to remove 1 𝗦𝗮𝗺𝗲 𝗻𝘂𝗺𝗯𝗲𝗿. 𝗗𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝘁 𝗿𝗲𝘀𝘂𝗹𝘁 💥 You think index. Java sees object. 𝗡𝗼𝘁 𝗼𝗻𝗹𝘆 𝗹𝗼𝗴𝗶𝗰 - 𝗮𝗹𝘀𝗼 𝗰𝗼𝘀𝘁 🐢 remove(index) - no search remove(value) - extra O(n) lookup 𝗪𝗵𝘆 𝗶𝘁 𝗵𝘂𝗿𝘁𝘀 😤 silent bug same-looking code wrong element or nothing removed 𝗔𝗱𝘃𝗶𝗰𝗲 ✅ Make intent explicit: remove((int) i) or remove(Integer.valueOf(x)) Never rely on overloads in critical paths. #java #backend #softwareengineering #coding #programming #javatips #cleancode #bug #performance
To view or add a comment, sign in
-
-
Coding agents are innovating fast, but they're also getting bloated. To actually understand what they’re doing, you have to go back to the basics. A good way to learn is to get into it. Adding LSP support to the 260 line nanocode agent in #Java https://lnkd.in/ec5j8QpJ
To view or add a comment, sign in
-
🚀 Day 8 – final vs finally vs finalize (Clearing the Confusion) These three look similar but serve completely different purposes in Java. 👉 final (keyword) Used to restrict modification final int x = 10; // cannot be changed ✔ Variables → constant ✔ Methods → cannot be overridden ✔ Classes → cannot be extended --- 👉 finally (block) Used in exception handling try { // code } finally { // always executes } ✔ Runs whether exception occurs or not ✔ Commonly used for cleanup (closing resources) --- 👉 finalize() (method) @Override protected void finalize() throws Throwable { // cleanup code } ✔ Called by Garbage Collector before object destruction ⚠️ Important insight: "finalize()" is deprecated and unreliable — not recommended in modern Java. --- 💡 Quick takeaway: - "final" → restriction - "finally" → execution guarantee - "finalize()" → outdated cleanup mechanism Understanding these avoids confusion in both interviews and real projects. #Java #BackendDevelopment #JavaBasics #ExceptionHandling #LearningInPublic
To view or add a comment, sign in
-
Understanding Dependency Injection in Java (Why Constructor Injection is Preferred) While learning Spring Boot, I was confused about one simple question: 👉 Why not just use @Autowired? Why constructor injection? After breaking it down from first principles, here’s what I understood. Step 1: The Real Problem — Tight Coupling Consider this simple code: class Car { private Engine engine = new Engine(); } Here, Car creates its own Engine. Problem: Car is tightly coupled to Engine Cannot replace Engine easily Hard to test Not flexible Step 2: Introducing Dependency Injection class Car { private Engine engine; public Car(Engine engine) { this.engine = engine; } } Now: Car does NOT create Engine It receives Engine from outside This is Dependency Injection. Step 3: Field Injection (@Autowired) class Car { @Autowired private Engine engine; } At first glance, this looks simple. But it introduces hidden problems: ❌ Dependency is not obvious ❌ Object can exist in invalid state (engine = null) ❌ Hard to test (requires Spring context) ❌ Mutable (can be changed anytime) Step 4: Constructor Injection (Recommended) class Car { private final Engine engine; public Car(Engine engine) { this.engine = engine; } } Benefits: ✔ Dependency is explicit ✔ Object is always in valid state ✔ Easy to test (can pass mock objects) ✔ Immutable design (final) Key Insight The real shift is: From: “How do I create objects?” To: “How do I manage dependencies between objects?” Final Thought Constructor Injection isn’t just a syntax choice — it’s about writing clean, maintainable, and scalable code. #Java #SpringBoot #DependencyInjection #CleanCode #BackendDevelopment #Learning
To view or add a comment, sign in
-
Day 62 of Sharing What I’ve Learned🚀 Iterator in Java — Safe and Efficient Traversal After understanding how collections store and organize data, I revisited an important concept — how to safely traverse them using Iterator. 👉 Accessing data is easy… but doing it correctly and safely matters more. 🔹 What is an Iterator? Iterator is an interface in Java used to traverse elements of a collection one by one. 👉 It provides a standard way to loop through: ArrayList HashSet LinkedList And more… 🔹 Why not just use a for loop? Using a normal loop works… but it has limitations: ❌ Not safe when modifying collection ❌ Can lead to ConcurrentModificationException ❌ Not universal for all collection types 👉 That’s where Iterator comes in ✔ 🔹 Key Methods of Iterator hasNext() → checks if next element exists next() → returns the next element remove() → removes the current element safely 🔹 Example import java.util.*; public class Main { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Java"); list.add("Python"); list.add("C++"); Iterator<String> it = list.iterator(); while(it.hasNext()) { String lang = it.next(); System.out.println(lang); } } } 🔹 Real Advantage 💡 👉 Removing elements while iterating: Iterator<String> it = list.iterator(); while(it.hasNext()) { if(it.next().equals("Python")) { it.remove(); // Safe removal } } ✔ No errors ✔ Clean logic ✔ Interview-friendly concept 🔹 Day 62 Realization Traversing data is not just about loops — it’s about doing it safely and efficiently. 👉 Iterator provides better control and prevents runtime issues 👉 Essential when working with dynamic collections #Java #Collections #DataStructures #CollectionsFramework #Iterator #Programming #DeveloperJourney #100DaysOfCode #Day61 Grateful for guidance from, TAP Academy Sharath R kshitij kenganavar
To view or add a comment, sign in
-
Explore related topics
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