Simple code. Subtle behavior. Easy to misjudge. Two similar Java methods. Two completely different outputs. Case 1-> public static int tricky1() { int x = 10; try { return x; } finally { x = 50; } } Output: 10 Explanation: When return x executes, Java evaluates and stores the value (10) first. After that, the finally block runs. Even though x becomes 50 inside finally, it does not change the already prepared return value. Case 2-> public static int tricky2() { try { return 10; } finally { return 30; } } Output: 30 Explanation: If finally contains a return statement, it overrides any previous return from try or catch. This is why returning from finally is considered bad practice — it can override results and even hide exceptions. #Java #CoreJava
Java Return Statement Behavior in Try-Finally Blocks
More Relevant Posts
-
✅ Java Features – Step 21: Pattern Matching for instanceof (Java 17) ⚡ Before Java 17, using instanceof required an extra cast. Example (old style): if (obj instanceof String) { String s = (String) obj; System.out.println(s.length()); } Java 17 simplifies this with pattern matching. if (obj instanceof String s) { System.out.println(s.length()); } Now the variable s is automatically created after the type check. Why this matters Less boilerplate code Safer type checking Improved readability Fewer casting mistakes Example Object value = "Java"; if (value instanceof String str) { System.out.println(str.toUpperCase()); } Key takeaway Pattern matching reduces repetitive casting and makes type-checking logic cleaner. This is part of Java’s effort to modernize the language. Next up: Recap – Key Features from Java 8 → Java 17 🚀
To view or add a comment, sign in
-
📄 On paper this looks like a small syntax tweak, ✨ but in real projects it feels like a relief. 🔧 DTO mapping, 📝 logging, or ⚙️ handling different event types in a backend system — we used to write instanceof checks followed by repetitive casts everywhere. ❌ It wasn’t just ugly, it was error‑prone. ✅ Now the flow is natural: if (event instanceof PaymentEvent pe) { auditLogger.log(pe.getTransactionId()); } 💡 This isn’t just saving a line of code. 👉 It’s about intent. 👥 When a teammate reads this, they immediately see what’s happening without being distracted by boilerplate. 🚀 In practice, these “small” changes: 🔓 reduce friction 👶 make onboarding easier for juniors 🎯 help teams focus on business logic instead of ceremony 📌 My takeaway: Code is not only for machines to run, but for humans to read, share, and maintain. Readability = productivity. This way your repost feels more personal, visually appealing, and relatable to everyday coding practice.
✅ Java Features – Step 21: Pattern Matching for instanceof (Java 17) ⚡ Before Java 17, using instanceof required an extra cast. Example (old style): if (obj instanceof String) { String s = (String) obj; System.out.println(s.length()); } Java 17 simplifies this with pattern matching. if (obj instanceof String s) { System.out.println(s.length()); } Now the variable s is automatically created after the type check. Why this matters Less boilerplate code Safer type checking Improved readability Fewer casting mistakes Example Object value = "Java"; if (value instanceof String str) { System.out.println(str.toUpperCase()); } Key takeaway Pattern matching reduces repetitive casting and makes type-checking logic cleaner. This is part of Java’s effort to modernize the language. Next up: Recap – Key Features from Java 8 → Java 17 🚀
To view or add a comment, sign in
-
✅ Java Features – Step 7: Built-in Functional Interfaces ☕ Java 8 introduced several built-in functional interfaces that power Streams and lambdas. The most common ones: Predicate<T> → returns boolean Function<T, R> → transforms a value Consumer<T> → takes a value, returns nothing Supplier<T> → provides a value Example: Predicate<Integer> isEven = n -> n % 2 == 0; Function<String, String> toUpper = s -> s.toUpperCase(); Consumer<String> print = s -> System.out.println(s); Supplier<Double> randomValue = () -> Math.random(); These interfaces make code more expressive and reduce boilerplate. They are the foundation behind the Streams API. Next up: Java 8 Stream Intermediate vs Terminal Operations 🔍
To view or add a comment, sign in
-
Most developers believe that a Java program can only have one "main()" method, but this isn't entirely accurate. A Java class can indeed contain multiple "main()" methods through method overloading, provided their parameter lists differ. However, the Java Virtual Machine (JVM) will only initiate execution from this specific method signature: "public static void main(String[] args)". Any additional "main()" methods will not execute automatically; they must be invoked manually from the original "main()" method. For example: public class Test { public static void main(String[] args) { System.out.println("Original main method"); main(10); } public static void main(int a) { System.out.println("Overloaded main method: " + a); } } In conclusion, while multiple "main()" methods are permissible, the JVM recognizes only one entry point. #Java #Programming #JavaDeveloper #JavaInterview #BackendDevelopment
To view or add a comment, sign in
-
-
Cool site to show myriad improvements of Java source code (before and now as JDK improvements are released) across dozens of features. #java https://lnkd.in/e-ecncAB
To view or add a comment, sign in
-
How Does "ConcurrentHashMap" Achieve Thread Safety in Java? In multithreaded applications, using a normal "HashMap" can lead to race conditions and inconsistent data. While "Hashtable" provides thread safety, it locks the entire map, which can reduce performance. This is where "ConcurrentHashMap" comes in. It provides high performance and thread safety by allowing multiple threads to read and write simultaneously. 🔹 How it Works 1️⃣ Segment / Bucket Level Locking (Java 7) Instead of locking the entire map, "ConcurrentHashMap" divides the map into segments. Each segment can be locked independently, allowing multiple threads to work on different segments. This significantly improves concurrency. 2️⃣ Fine-Grained Locking (Java 8+) In Java 8, the implementation was improved further. Instead of segments, it uses: ✔ CAS (Compare-And-Swap) operations ✔ Node-level synchronization when needed This allows better performance and scalability. 🔹 Example import java.util.concurrent.ConcurrentHashMap; public class Example { public static void main(String[] args) { ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>(); map.put(1, "Java"); map.put(2, "Spring"); map.put(3, "Kafka"); map.forEach((k,v) -> System.out.println(k + " : " + v)); } } Multiple threads can safely read and update the map without blocking the entire structure. 🔹 Key Benefits ✔ Thread-safe operations ✔ Better performance than "Hashtable" ✔ Allows concurrent reads and writes ✔ Highly scalable in multithreaded environments In simple terms: "HashMap" → Not thread safe "Hashtable" → Thread safe but slow "ConcurrentHashMap" → Thread safe and optimized for concurrency. #Java #ConcurrentHashMap #Multithreading #JavaDeveloper #Concurrency #Programming
To view or add a comment, sign in
-
✅ Java Features – Step 18: Text Blocks (Java 15) 🧾 Before Java 15, writing multi-line strings required lots of concatenation. Example: String query = "SELECT * FROM users\n" + "WHERE age > 25\n" + "ORDER BY name"; Java 15 introduced Text Blocks, which allow clean multi-line strings. String query = """ SELECT * FROM users WHERE age > 25 ORDER BY name """; Why this matters Cleaner multi-line strings Great for SQL queries, JSON, HTML, and XML Less escaping and string concatenation Much more readable code Example with JSON String json = """ { "name": "Mariya", "role": "Developer" } """; Key takeaway Text blocks make working with structured text much easier and improve code readability. Next up: Java Records (Java 16) 🚀
To view or add a comment, sign in
-
✅ Java Features – Step 15: New String Methods (Java 11) ☕ Java 11 introduced useful additions to the String class that simplify everyday tasks. 1️⃣ isBlank() Checks if a string is empty or contains only whitespace. String s = " "; System.out.println(s.isBlank()); // true 2️⃣ strip(), stripLeading(), stripTrailing() Better Unicode-aware alternatives to trim(). String name = " Mariya "; System.out.println(name.strip()); // "Mariya" 3️⃣ repeat(int count) Repeat a string multiple times. System.out.println("Hi ".repeat(3)); // Hi Hi Hi 4️⃣ lines() Splits a string into a Stream of lines. String text = "Java\nSpring\nDocker"; text.lines().forEach(System.out::println); Why This Matters: Cleaner code Less manual string handling More expressive APIs Useful in backend data processing Small improvements, but they reduce boilerplate significantly. Next up: Java 11 – HttpClient API 🌐
To view or add a comment, sign in
-
Text Block simple example In this post under Java Core, I will introduce you to newly added "Text Block" feature. This feature was added as part of Java 15. Pre Java 15, if we have to declare a multiline string we used to declare it as shown below String result = "Since Java 15, text blocks are \n" + "available as a standard feature.\n" + "With Java 13 and 14, \n" + "we needed to enable it as a preview feature.";...
To view or add a comment, sign in
-
Every Java developer has a file in their codebase with a class that does nothing but hold two values — and somehow runs to 40 lines. Records are the fix nobody told you about. 💡 https://lnkd.in/gmpX2F6G
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