☕ #ThinkingInJava — Post No. 5 💡 Tricky Java Question What will be the output? class Test { public static int m1() { int i = 10; try { return i; } finally { i = 20; System.out.println("finally block executed"); } } public static void main(String[] args) { System.out.println(m1()); } } ✅ Output finally block executed 10 🤔 Why not 20? When return i executes, Java first saves the return value internally. temp = i // temp = 10 Then the "finally" block runs, changing i to 20. But the method returns the saved value (10). 🎯 Key Concept 👉 The return value is evaluated before the `finally'. #Java #TestAutomationSpecialist #AutomationMeetsFuture
Java Tricky Question: Finally Block Execution and Return Value
More Relevant Posts
-
Understanding Bubble Sort vs Selection Sort (Java) Today, I revised two classic sorting algorithms and noted some key differences while implementing them in Java. 🔹 Bubble Sort 1. Time Complexity: O(n²) (Best case O(n) with early stop) 2. Space Complexity: O(1) 3. Multiple swaps can happen in a single pass 4. Large elements move to the end in each pass 5. Optimized using a swap flag to stop early if the array is already sorted 🔹 Selection Sort 1. Time Complexity: O(n²) (Best, Average, Worst) 2. Space Complexity: O(1) 3. Only one swap per pass 4. Smallest element moves to the front in each pass 5. No early termination, even if the array is already sorted Even if the smallest is already at correct position, swap still executes (with same index).
To view or add a comment, sign in
-
-
☕ #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
To view or add a comment, sign in
-
Woooow. Got me there! In Java, the statement 0.0f > Float.MIN_VALUE is false. Unlike integer types where MIN_VALUE is the most negative number, for floating-point types, MIN_VALUE represents the smallest positive nonzero value. Good thing I write unit tests! Trust but verify! even yourself!
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
-
💡 Strings in Java — Small Concept, Big Impact At first, I thought Strings were simple… But in real projects, I learned: ➡️ Strings are immutable ➡️ Memory is optimized using String Pool ➡️ Wrong usage can impact performance Example mistake I made: String result = ""; for (int i = 0; i < 1000; i++) { result += i; // ❌ creates multiple objects } ✅ Better approach: StringBuilder sb = new StringBuilder(); for (int i = 0; i < 1000; i++) { sb.append(i); } ✨ What I learned: ✔ Use StringBuilder for heavy operations ✔ Understand equals() vs == ✔ Be mindful of memory Sometimes the simplest concepts teach the biggest lessons. #Java #Strings #CleanCode #SoftwareEngineering #BackendDevelopment #LearningJourney
To view or add a comment, sign in
-
-
The Java Collections Framework is a hierarchical structure of interfaces and classes used to store and manipulate groups of objects efficiently. At the top, we have the Collection interface, which is the root for all collection types like List, Set, and Queue. List → Ordered collection, allows duplicates (ArrayList, LinkedList, Vector, Stack) Set → Unordered collection, no duplicates (HashSet, LinkedHashSet, TreeSet) Queue → Follows FIFO order (PriorityQueue, ArrayDeque, LinkedList)
To view or add a comment, sign in
-
-
📌 Command Design Pattern Explained (with Java example) The Command Pattern is a behavioral design pattern that encapsulates a request as an object, helping decouple the sender from the receiver. It is commonly used for: • Undo/redo functionality • Task queues • Logging and command history I wrote a short article explaining the concept with a simple and practical Java example. 📖 Read it here: https://lnkd.in/g4-XS8Dh #Java #DesignPatterns #SystemDesign #BackendDevelopment
To view or add a comment, sign in
-
🧠 Java Streams Puzzle: Can You Guess the Output? Java Streams are powerful, but they can sometimes behave in unexpected ways. Here's a quick puzzle for all Java enthusiasts: 🤔 Question: What will be the output of this code? List<Integer> numbers = new ArrayList<>(List.of(5, 7,)); long count = numbers.stream() .peek(System.out::println) .count(); System.out.println(count);
To view or add a comment, sign in
-
Day 40 – Advanced Java Strings & Input Handling ☕ Today I revised advanced concepts related to Strings and input handling in Java. Topics covered: 🔹 Inbuilt String methods 🔹 Converting String to character array 🔹 Mutable vs Immutable Strings 🔹 Difference between StringBuilder and StringBuffer 🔹 Handling input using nextLine() with integers and strings 🔹 Understanding buffer issues in input handling 🔹 Converting mutable to immutable and vice versa 🔹 Difference between split() and StringTokenizer Revisiting these concepts helped me better understand how Java handles strings internally and how input operations can sometimes lead to unexpected issues if not handled properly. Strengthening core concepts step by step 🚀 #Day40 #JavaJourney #Strings #CoreJava #ProgrammingFundamentals
To view or add a comment, sign in
-
🚀 Java Tip: Prefer Enhanced For Loop for Better Readability When working with arrays or collections in Java, using an enhanced for loop (for-each loop) can make your code cleaner and easier to understand compared to traditional loops. Instead of managing indexes manually, you can directly iterate over elements. Less clutter, fewer mistakes, better readability. 💡 Why use an enhanced for loop? ✔ No index management ✔ Cleaner and more readable code ✔ Reduces chances of off-by-one errors ✔ Perfect for simple iterations 🔍 Pro Tip: Use enhanced loops when you don’t need the index. If you need position-based logic, then a traditional loop still makes sense. Good code isn’t just about making it work; it’s about making it easy to read, maintain, and scale. #Java #AutomationTesting #CleanCode #SDET #SoftwareEngineering
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