Hi Friends 👋 Sharing a small but tricky Java concept that often confuses developers in real projects 😅 finally block vs return — who actually wins? public class Test { public static void main(String[] args) { System.out.println(getValue()); } static int getValue() { try { return 10; } finally { return 20; } } } 👉 What would you expect? Most people say: 10 👉 But the actual output is: 20 😳 --- Why does this happen? - The try block tries to return 10 - But before the method exits, the finally block always runs - If finally also has a return, it overrides the previous return 👉 So the final result becomes 20 --- Common mistakes: - Assuming the try return is final - Writing return inside finally for cleanup or logging --- Real-world impact: - Expected vs actual result mismatch - Hard-to-debug issues - Confusing behavior in production --- Best Practice: - Never use return inside a finally block ❌ - Use finally only for cleanup (like closing resources) --- Final Thought: In Java, small concepts can create big bugs. Understanding execution flow is what makes a real developer 🚀 Did you know this before? 🤔 #Java #BackendDevelopment #CodingMistakes #Learning #Developers
Java finally block vs return: What you need to know
More Relevant Posts
-
🚀 Day 19/100: The Grammar of Java – Writing Clean & Readable Code 🏷️✨ Today’s focus was on something often underestimated but critically important in software development—writing code that humans can understand. In a professional environment, code is not just for the compiler; it’s for collaboration. Here’s what I worked on: 🔍 1. Identifiers – Naming with Purpose Identifiers are the names we assign to variables, methods, classes, interfaces, packages, and constants. Good naming is not just syntax—it’s communication. 📏 2. The 5 Golden Rules for Identifiers To ensure correctness and avoid compilation errors, I reinforced these rules: Use only letters, digits, underscores (_), and dollar signs ($) Do not start with digits Java is case-sensitive (Salary ≠ salary) Reserved keywords cannot be used as identifiers No spaces allowed in names 🏗️ 3. Professional Naming Conventions This is where code quality truly improves. I practiced industry-standard naming styles: PascalCase → Classes & Interfaces (EmployeeDetails, PaymentGateway) camelCase → Variables & Methods (calculateSalary(), userAge) lowercase → Packages (com.project.backend) UPPER_CASE → Constants (MIN_BALANCE, GST_RATE) 💡 Key Takeaway: Clean and consistent naming transforms code from functional to professional and maintainable. Well-written identifiers reduce confusion, improve collaboration, and make debugging easier. 📈 Moving forward, my focus is not just on writing code that works—but code that is clear, scalable, and team-friendly. #Day19 #100DaysOfCode #Java #CleanCode #JavaDeveloper #NamingConventions #SoftwareEngineering #CodingJourney #LearningInPublic #JavaFullStack#10000coders
To view or add a comment, sign in
-
💡 Java Interfaces Made Easy: Functional, Marker & Nested Let’s understand 3 important types of interfaces in a simple way 👇 --- 📌 Functional Interface An interface that has only one abstract method. It is mainly used with lambda expressions to write clean and short code. 👉 Example use: "(a, b) -> a + b" --- 📌 Marker Interface An empty interface (no methods) used to mark a class. It acts like a flag 🚩, telling Java to apply special behavior. 👉 Example: "Serializable", "Cloneable" --- 📌 Nested Interface An interface that is declared inside another class or interface. It is used to organize related code and keep things structured. --- 🧠 Quick Comparison: ✔️ Functional → One method → Used in lambda ✔️ Marker → No methods → Used as flag ✔️ Nested → Inside another → Better structure --- 🚀 Why it matters? Understanding these helps in writing clean, scalable, and modern Java code. --- #Java #Programming #Coding #Developers #LearnJava #InterviewPrep #SoftwareDevelopment
To view or add a comment, sign in
-
-
💡 A Java habit that makes your code more flexible and less error-prone Instead of writing: if (status == 1) { // active } else if (status == 2) { // inactive } Use an enum: enum Status { ACTIVE, INACTIVE } if (status == Status.ACTIVE) { // logic } 🔍 Why this matters? Using “magic numbers” (like 1, 2, 3…) makes code: - Hard to understand - Easy to misuse - Difficult to maintain Enums give meaning to your values. ⚡ Clear code > Clever code This habit: ✔ Improves readability ✔ Prevents invalid values ✔ Makes refactoring easier 🚀 Bonus Tip: Enums can also have fields and methods: enum Status { ACTIVE("A"), INACTIVE("I"); private String code; Status(String code) { this.code = code; } } Write code that explains itself. #Java #CleanCode #CodingTips #JavaDeveloper #BestPractices
To view or add a comment, sign in
-
You have written this line hundreds of times. But do you actually understand what each part does? Every Java developer has written this line countless times, but do you really understand what each keyword means? Here is a breakdown of the Java main method: public - Access modifier that makes the class and method accessible from outside the package. This allows the JVM to call the main method from anywhere. class - Keyword used to declare a class. Classes are blueprints used to represent anything in software and in the real world. MainClass - The name of your class. This is where your program logic lives. static - Method belongs to the class itself rather than an instance. This means the JVM can call the main method without creating an object of the class first. void - Return type indicating that the method does not return any value. The main method executes the program but does not return anything. main - Java's entry point where the program starts executing. When you run a Java program, the JVM looks for this method first. String[ ] args - Command-line arguments to the program when it is executed. This allows you to pass input to your program at runtime. System.out.println - Prints the string "Hello, World!" followed by a newline to the console. Why This Matters: Understanding these fundamentals helps you write better code and debug issues faster. When you know why each keyword exists, you can make better architectural decisions. What Java fundamental concepts do you think every developer should master? Share your thoughts below! #Java #Programming #SoftwareDevelopment #BackendDevelopment #LearningInPublic #Coding
To view or add a comment, sign in
-
-
You have written this line hundreds of times. But do you actually understand what each part does? Every Java developer has written this line countless times, but do you really understand what each keyword means? Here is a breakdown of the Java main method: public - Access modifier that makes the class and method accessible from outside the package. This allows the JVM to call the main method from anywhere. class - Keyword used to declare a class. Classes are blueprints used to represent anything in software and in the real world. MainClass - The name of your class. This is where your program logic lives. static - Method belongs to the class itself rather than an instance. This means the JVM can call the main method without creating an object of the class first. void - Return type indicating that the method does not return any value. The main method executes the program but does not return anything. main - Java's entry point where the program starts executing. When you run a Java program, the JVM looks for this method first. String[ ] args - Command-line arguments to the program when it is executed. This allows you to pass input to your program at runtime. System.out.println - Prints the string "Hello, World!" followed by a newline to the console. Why This Matters: Understanding these fundamentals helps you write better code and debug issues faster. When you know why each keyword exists, you can make better architectural decisions. What Java fundamental concepts do you think every developer should master? Share your thoughts below! #Java #Programming #SoftwareDevelopment #BackendDevelopment #LearningInPublic #Coding
To view or add a comment, sign in
-
-
💡 Java Tip: One Method to Remember for Type Conversion We used to rely on: Integer.parseInt(), Long.parseLong(), Double.parseDouble() → for converting String to primitives String.valueOf() → for converting values to String It works—but it can get confusing when switching between primitives, wrapper classes, and even char ↔ String conversions. 🔑 Simple takeaway: You can simplify most conversions by remembering just one method: 👉 WrapperClass.valueOf() ✅ Converts String → Wrapper (Integer, Long, Double, etc.) ✅ Works well with primitives (via autoboxing/unboxing) ✅ Keeps your code more consistent and readable Example: Integer i = Integer.valueOf("10"); Double d = Double.valueOf("10.5"); String s = String.valueOf(100); 🧠 Personal learning: Instead of memorizing multiple parsing methods, focusing on valueOf() makes type conversion easier to reason about and reduces cognitive load while coding. #Java #CleanCode #ProgrammingTips #BackendDevelopment #SoftwareEngineering #Learning
To view or add a comment, sign in
-
🚦🧊 JAVA IMMUTABILITY: THE WORDS MOST DEVS MIX UP: Unmodifiable, Immutable, Shallowly/ Deeply immutable, final 🔸 TL;DR In Java, unmodifiable does not mean immutable. And final does not mean the object can’t change either. If you confuse terms like mutable, unmodifiable view, immutable, shallowly immutable, and deeply immutable, you can easily design APIs that look safe but still leak state and bugs. 👉 I put together a carousel cheat sheet to make this crystal clear. Swipe through it. 🔸 TAKEAWAYS ▪️ Mutable = state can change after creation ▪️ Unmodifiable = this reference blocks mutation, but backing data may still change ▪️ Immutable = state cannot change after construction ▪️ Shallowly immutable = outer object is fixed, inner objects may still mutate ▪️ Deeply immutable = the full reachable state is frozen ▪️ Collections.unmodifiableList(...) is not the same as List.copyOf(...) ▪️ final freezes the reference, not the object ▪️ Records are concise, but they are not automatically deeply immutable 🔸 WHY IT MATTERS A lot of Java codebases say “immutable” when they really mean “harder to mutate accidentally.” That shortcut creates confusion in code reviews, APIs, concurrency discussions, and interviews. Precise vocabulary = better design. And better design = fewer side effects, safer models, cleaner code. ☕ 🔸 SWIPE THE CAROUSEL I turned the whole taxonomy into a simple PPT carousel with: ▪️ one term per slide ▪️ code snippets ▪️ short explanations ▪️ the distinctions that actually matter in real projects 👉 Swipe the carousel and tell me: Which term do you think developers misuse the most: unmodifiable or immutable? #Java #JavaProgramming #SoftwareEngineering #CleanCode #BackendDevelopment #Programming #Developers #Architecture #CodeQuality #JavaDeveloper #TechEducation #CodingTips
To view or add a comment, sign in
-
I almost ended up writing 15+ lines of code… for something Java could handle in 2. Recently at work, I had to deal with a region-specific date format. My first instinct was to write custom logic to handle it. But the more I thought about it, the more complicated it started to look. That’s when I paused and checked if Java already had a way to handle this. Turns out, using Locale and built-in date handling made it much simpler. Just a few lines - and it handled the format cleanly. No extra logic. No mess. This was a small reminder for me: - Not every problem needs a custom solution - Writing less code can actually mean writing better code - Knowing your tools properly makes a big difference Before jumping into implementation, it’s worth asking, “Is there already a better way to do this?” #Java #BackendDevelopment #SpringBoot #FullStackDeveloper #LearningInPublic #SoftwareEngineering
To view or add a comment, sign in
-
-
💡 What I Learned About Java Interfaces (OOP Concept) I explored Interfaces in Java, and realized that they are not just about rules — they play a key role in achieving abstraction, flexibility, and clean design in applications. 🔹 Interfaces & Inheritance Interfaces are closely related to inheritance, where classes implement interfaces to follow a common structure. 🔹 Abstraction Interfaces enable abstraction. Before Java 8, they supported 100% abstraction, but now they can also include additional method types. 🔹 Polymorphism & Loose Coupling Interface references can point to different objects → making code more flexible, scalable, and maintainable. 🔹 Multiple Inheritance Java supports multiple inheritance through interfaces, allowing a class to implement multiple interfaces. 🔹 Functional Interface A functional interface contains only one abstract method. It can be implemented using: 1️⃣ Regular class 2️⃣ Inner class 3️⃣ Anonymous class 4️⃣ Lambda expression 🔹 Java 8 Enhancements Interfaces became more powerful with: ✔️ default methods (with implementation) ✔️ static methods ✔️ private methods ✔️ private static methods 🔹 Variables in Interface All variables are implicitly public static final (constants). 🔹 No Object Creation Interfaces cannot be instantiated, but reference variables can be created. 🚀 Conclusion: Interfaces are a core part of Java OOP that help build scalable, maintainable, and loosely coupled systems. #Java #OOPS #Interfaces #Programming #Learning #Java8 #Coding
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