This confused me when I started working with exceptions public void test() throws Exception { throw new Exception("Error"); } Now see this: public static void main(String[] args) { test(); ❌ } 👉 This won’t compile! 💥 Error: Unhandled exception: Exception 👉 Why? Because test() is throwing a checked exception So Java forces you to handle it. ✅ Option 1: try { test(); } catch (Exception e) { e.printStackTrace(); } ✅ Option 2: public static void main(String[] args) throws Exception { test(); } 💡 Lesson: Checked exceptions must be handled either where they occur or where they are called. Did this confuse you earlier? 👇 #Java #CoreJava #ExceptionHandling #Programming #BackendDeveloper #Coding
Java Checked Exceptions Must Be Handled
More Relevant Posts
-
🚀 Beats 100% of all Java solutions on LeetCode! Just solved LeetCode #290 — Word Pattern in Java with 0ms runtime, outperforming every submission. Here's how I approached it 👇 🧩 Problem: Given a pattern (like "abba") and a string of words, check if the words follow the exact same pattern — a full bijection. e.g. pattern = "abba", s = "dog cat cat dog" → true ✅ 💡 My approach: Used a single HashMap<Character, String> to map each pattern character to its corresponding word. The key insight: also check containsValue() to prevent two different characters from mapping to the same word — ensuring true one-to-one bijection. 📊 Results: Runtime: 0 ms — Beats 100.00% 🌿 Memory: 42.65 MB — Beats 80.14% 🔑 Key takeaway: Always verify bijection in both directions — a one-way map is not enough for pattern matching problems. One extra containsValue() check is all it takes! All 44 test cases passed ✅ — Clean, simple, and blazing fast. #LeetCode #Java #DSA #CodingChallenge #ProblemSolving #100Percent #Programming #SoftwareEngineering #CompetitiveProgramming #HashMap
To view or add a comment, sign in
-
-
🚀 **Day 4/30 – LeetCode Java Challenge** Today’s problem pushed me to think beyond basic comparisons and focus on **pattern-based validation**. Worked on a string problem where the key insight was separating characters based on **even and odd indices**, then comparing frequency distributions instead of direct string matching. 📊 **Result:** ✔️ Accepted (752/752 test cases) ⚡ Runtime: 5 ms (Beats 93.81%) 💾 Memory: Efficient (Beats 86.60%) 💡 **What actually mattered today:** * Brute force thinking won’t scale — pattern recognition does * Breaking a problem into smaller logical groups simplifies everything * Frequency arrays can outperform more complex data structures when used correctly Let’s be real: This wasn’t a hard problem, but the approach matters. If you miss the pattern, you overcomplicate it. If you see it early, the solution becomes clean and efficient. Day 4 done. Still building consistency, still sharpening fundamentals. Archana J E Bavani k Deepika Kannan Divya Suresh Hari priya B Devipriya R Harini B Bhavya B Kezia H Vaishnavi Janaki #LeetCode #Java #DSA #ProblemSolving #Consistency #30DaysOfCode
To view or add a comment, sign in
-
-
Let’s break the code step by step: int x = 4; int y = 11; x += y >> 1; System.out.println(x); 🔹 Step 1 — Understand the operator precedence In Java, the right-shift operator >> has higher precedence than the compound assignment +=. So this line: x += y >> 1; is evaluated as: x = x + (y >> 1); 🔹 Step 2 — Evaluate the shift operation y >> 1 Right shift means: divide by 2 (for positive integers). 11 in binary = 00001011 Right shift 1 = 00000101 That equals 5. 🔹 Step 3 — Add to x Copy code x = 4 + 5 x = 9 🔹 Step 4 — Print System.out.println(x); // 9 🧠 ✅ Correct Answer: B) 9 #Java #SpringBoot #FullStackDeveloper
To view or add a comment, sign in
-
-
Your Java Thread Model is Broken (Here's the Fix) Watch Full Video : https://lnkd.in/e_Usi8qA Website Link : https://systemdrd.com/ Full Course Link : https://lnkd.in/eM5jJyaQ OS threads cost 1MB each and cap you at ~2,000 connections. Java's virtual threads via Project Loom handle 1,000,000+ — with simpler code. Stop writing reactive chains. #JavaDeveloper #ProjectLoom #VirtualThreads #BackendEngineering #JavaTips #CodingShorts #SoftwareEngineering #Java2026
To view or add a comment, sign in
-
Day 21/100: String Compression & Memory 📦 Today I tackled String Compression in Java (e.g., "aaabb" -> "a3b2"). The Goal: Compress a string by counting repeated characters. Example:"aaabbc" becomes "a3b2c1". If the compressed string isn't actually shorter, return the original. Key Learning: StringBuilder vs. String In Java, strings are immutable. If you add to a string in a loop, Java creates a new object every single time. To fix this, I used **StringBuilder**, which is much faster and memory-efficient for building long strings. The Strategy: 1️⃣ Iterate through the string once. 2️⃣ Keep a running count of identical consecutive characters. 3️⃣ Append the character and count to the builder. Simple logic, big performance difference. 🚀 #100DaysOfCode #Java #DSA #Strings #Optimization #Unit2 #CodingJourney #LearnInPublic
To view or add a comment, sign in
-
-
Checked vs Unchecked Exceptions - Know the Difference ⚠️ 🔹 Checked Exceptions ▸ Checked at compile time ▸ Must be handled (try-catch or throws) ▸ Not handled → code won’t compile ▸ Examples: IOException, SQLException, FileNotFoundException 🔹 Unchecked Exceptions ▸ Occur at runtime ▸ No need to handle (but recommended) ▸ Extend RuntimeException ▸ Examples: NullPointerException, ArrayIndexOutOfBoundsException 💡 Simple Way to Remember → Checked = Compiler forces handling → Unchecked = Runtime errors 🚀 Best Practice ▸ Use Checked → for recoverable scenarios (e.g., file not found → retry) ▸ Use Unchecked → for programming bugs (e.g., null → fix the code) #Java #SpringBoot #ExceptionHandling #JavaDeveloper #BackendDeveloper
To view or add a comment, sign in
-
-
🚨 This small Java mistake can give wrong comparisons I used to write this: if (price == 0.1 + 0.2) { // logic } Looks correct… but it may fail ❌ --- 👉 Why? Floating-point calculations are not always exact in Java. 👉 0.1 + 0.2 = 0.30000000000000004 So comparison with "==" can fail. --- ✅ Better way: if (Math.abs(price - (0.1 + 0.2)) < 0.0001) { // logic } --- 💡 Lesson: Never use "==" for floating-point comparison. Small detail… but critical in real applications. Have you faced this before? 👇 #Java #CoreJava #Programming #BackendDeveloper #Coding #TechLearning
To view or add a comment, sign in
-
💡 𝗝𝗮𝘃𝗮/𝐒𝐩𝐫𝐢𝐧𝐠 𝐁𝐨𝐨𝐭 𝗧𝗶𝗽 - 𝗦𝘄𝗶𝘁𝗰𝗵 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻 💎 🕯 𝗧𝗿𝗮𝗱𝗶𝘁𝗶𝗼𝗻𝗮𝗹 𝗦𝘄𝗶𝘁𝗰𝗵 𝗦𝘁𝗮𝘁𝗲𝗺𝗲𝗻𝘁 The traditional switch statement has been part of Java since the beginning. It requires explicit break statements to prevent fall-through, which can lead to bugs if forgotten. Each case must contain statements that execute sequentially, making the code verbose and error-prone. 💡 𝗠𝗼𝗱𝗲𝗿𝗻 𝗦𝘄𝗶𝘁𝗰𝗵 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻 Switch expressions were introduced in Java 14 as a more concise and safe alternative. Using the -> syntax, you eliminate the need for break statements and can directly return values. Multiple cases can be grouped with commas, and the compiler enforces exhaustiveness for better safety. ✅ 𝗞𝗲𝘆 𝗕𝗲𝗻𝗲𝗳𝗶𝘁𝘀 ◾ No break statements, safer and cleaner code. ◾ Direct value assignment, treat switch as an expression. ◾ Multiple labels with comma separation. ◾ Compiler exhaustiveness checks, fewer runtime errors. 🤔 Which one do you prefer? #java #springboot #programming #softwareengineering #softwaredevelopment
To view or add a comment, sign in
-
-
Checked Exceptions and Unchecked Exceptions may sound similar… but they behave very differently. 👀 Checked Exception is like that strict teacher: > “Handle me first, otherwise your code will not even compile.” Examples: IOException, SQLException Unchecked Exception is more dangerous: > It stays quiet… lets your program run… and then suddenly crashes everything at runtime. 💀 Examples: `NullPointerException`, `ArithmeticException` Simple rule: ✔ Checked Exception = compile-time problem ✔ Unchecked Exception = runtime surprise That’s why Java developers fear the silent ones more 😅 Which one has troubled you more? NullPointerException or IOException? #Java #CoreJava #Exceptions #CheckedException #UncheckedException #NullPointerException #JavaDeveloper #Programming #BackendDevelopment #CodingHumor
To view or add a comment, sign in
-
-
When you write new MyClass(), the JVM doesn’t just create an object. It: - loads the class - verifies and links it - initializes static state All of this happens lazily - on first active use. Behind the scenes, class loaders follow a parent-first delegation model, ensuring that core Java classes cannot be overridden. 👉 This is fundamental for understanding classpath issues and runtime errors. Here's an article I wrote down on this process: https://lnkd.in/d8fr6pEH
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