🚀 Java Trap: Why "finally" Doesn’t Change the Returned Value 👇 👉 Primitive vs Object Behavior in "finally" 🤔 Looks tricky… but very important to understand. --- 👉 Example 1 (Primitive): public static int test() { int x = 10; try { return x; } finally { x = 20; } } 👉 Output: 10 😲 Why not 20? 💡 Java stores return value before executing "finally" - "x = 10" stored - "finally" runs → changes "x" to 20 - But already stored value (10) is returned --- 👉 Example 2 (Object): public static StringBuilder test() { StringBuilder sb = new StringBuilder("Hello"); try { return sb; } finally { sb.append(" World"); } } 👉 Output: Hello World 😲 Why changed here? 💡 Object reference is returned - Same object is modified in "finally" - So changes are visible --- 🔥 Rule to remember: - Primitive → value copied → no change - Object → reference returned → changes visible --- 💭 Subtle concept… very common interview question. #Java #Programming #Coding #Developers #JavaTips #InterviewPrep 🚀
Java finally Block Behavior with Primitives and Objects
More Relevant Posts
-
Primitives vs. Objects in Java Why does some Java code turn purple in your IDE while other code stays black? It's not random—it's telling you something important. Primitive types like int, char, long, and double turn purple because they're baked directly into Java. They're the building blocks, the simplest forms of data the language recognizes. Objects like String don't get that color treatment because they're more complex structures. Here's the practical difference that matters: Objects give you access to the dot (.) operator—a key that unlocks built-in methods. With a String, you can call .toUpperCase(), .toLowerCase(), .length(), and dozens of other methods that manipulate your data. Primitives? They just hold a value. No dot, no methods, no extras. Once you understand this distinction, you'll start reading your IDE's color coding like a second language. Did you know this difference when you started? Drop a 🟣 if this clicked something for you. #java
To view or add a comment, sign in
-
Java Puzzle for Today What will be the output of this program? String a = "Java"; String b = "Java"; String c = new String("Java"); System.out.println(a == b); System.out.println(a == c); System.out.println(a.equals(c)); Take a moment and guess before scrolling. Most beginners think the output will be: true true true But the actual output is: true false true Why does this happen? Because Java stores string literals in a special memory area called the String Pool. So when we write: String a = "Java"; String b = "Java"; Both variables point to the same object in the String Pool. But when we write: String c = new String("Java"); Java creates a new object in heap memory, even if the value is the same. That’s why: - "a == b" → true (same object) - "a == c" → false (different objects) - "a.equals(c)" → true (same value) Lesson: Use "equals()" to compare values, not "==". Small Java details like this can save you from real bugs in production. #Java #Programming #JavaPuzzle #Coding #SoftwareDevelopment
To view or add a comment, sign in
-
🔥 Day 14: Immutable Class (How String is Immutable in Java) One of the most important concepts in Java — especially for interviews 👇 🔹 What is an Immutable Class? 👉 Definition: An immutable class is a class whose objects cannot be changed once created. 🔹 Example: String String s = "Hello"; s.concat(" World"); System.out.println(s); // Hello (not changed) 👉 Why Because String is immutable 🔹 How String Becomes Immutable? ✔ String class is final (cannot be extended) ✔ Internal data is private & final ✔ No methods modify the original object ✔ Any change creates a new object 🔹 Behind the Scenes String s1 = "Hello"; String s2 = s1.concat(" World"); System.out.println(s1); // Hello System.out.println(s2); // Hello World 👉 s1 remains unchanged 👉 s2 is a new object 🔹 Why Immutability is Important? ✔ Thread-safe (no synchronization needed) ✔ Security (safe for sharing data) ✔ Caching (String Pool optimization) ✔ Reliable & predictable behavior 🔹 How to Create Your Own Immutable Class? ✔ Make class final ✔ Make fields private final ✔ No setters ✔ Initialize via constructor only ✔ Return copies of mutable objects 🔹 Real-Life Analogy 📦 Like a sealed box — once created, you cannot change what’s inside. 💡 Pro Tip: Use immutable objects for better performance and safety in multi-threaded applications. 📌 Final Thought: "Immutability = Safety + Simplicity + Performance" #Java #Immutable #String #Programming #JavaDeveloper #Coding #InterviewPrep #Day14
To view or add a comment, sign in
-
-
Java Devs, let's talk about a core concept that makes our code cleaner and more flexible: "Method Overloading"! Ever wanted to perform similar operations with different inputs without creating a bunch of uniquely named methods? That's where Method Overloading shines! It's a fantastic example of compile-time polymorphism (aka static polymorphism or early binding) that allows a class to have multiple methods with the "same name", as long as their parameter lists are different. Key takeaways: * Same method name, different parameters = ✅ * Cannot overload by return type alone (parameters *must* differ) ⚠️ * The compiler is smart! It picks the most specific match. 🧠 Check out this quick example: ```java class Product { public int multiply(int a, int b) { // Multiplies two numbers return a * b; } public int multiply(int a, int b, int c) { // Multiplies three numbers return a * b * c; } } // Output: // Product of the two integer value: 2 // Product of the three integer value: 6 ``` See how elegant that is? One `multiply` method, multiple functionalities! What are your favorite use cases for Method Overloading in your Java projects? Share in the comments! 👇 #Java #JavaDevelopment #Programming #SoftwareDevelopment #BeginnerProgramming
To view or add a comment, sign in
-
-
Generic Classes in Java – Clean Explanation with Examples 🚀 Generics in Java are a compile-time type-safety mechanism that allows you to write parameterized classes, methods, and interfaces. Instead of hardcoding a type, you define a type placeholder (like T) that gets replaced with an actual type during usage. 🔹Before Generics (Problem): class Box { Object value; } Box box = new Box(); box.value = "Hello"; Integer x = (Integer) box.value; // Runtime error ❌ Issues: • No type safety • Manual casting required • Errors occur at runtime 🔹With Generics (Solution): class Box<T> { private T value; public void set(T value) { this.value = value; } public T get() { return value; } } 🔹Usage: public class Main { public static void main(String[] args) { Box<Integer> intBox = new Box<>(); intBox.set(10); int num = intBox.get(); // ✅ No casting Box<String> strBox = new Box<>(); strBox.set("Hello"); String text = strBox.get(); } } 🔹Bounded Generics: 1.Upper Bound (extends) → Read Only: Restricts type to a subclass List<? extends Number> list; ✔ Allowed: Integer, Double ❌ Not Allowed: String 👉 Why Read Only? You can safely read values as Number, but you cannot add specific types because the exact subtype is unknown at compile time. 2.Lower Bound (super) → Write Only: Restricts type to a superclass List<? super Integer> list; ✔ Allowed: Integer, Number, Object ❌ Not Allowed: Double, String 👉 Why Write Only? You can safely add Integer (or its subclasses), but when reading, you only get Object since the exact type is unknown. 🔹Key Takeaway: Generics = Type Safety + No Casting + Compile-Time Errors Clean code, fewer bugs, and better maintainability - that’s the power of Generics 💡 #Java #Generics #Programming #SoftwareEngineering #Coding
To view or add a comment, sign in
-
Day14 Java Practice: Maximum Product of Three Elements in an Array While practicing Java, I solved an interesting array problem: 👉 Find the maximum product that can be formed using any three elements from the array. Example: Input: {10, 3, 5, 6, -20} At first, it looks like we just need the three largest numbers. But the twist is: negative numbers can change the result! 🧠 Key Idea: The product of two negative numbers becomes positive So we must compare: Product of the three largest numbers Product of two smallest (most negative) numbers and the largest number ================================================= // Online Java Compiler // Use this editor to write, compile and run your Java code online import java.util.*; class Main { public static void main(String[] args) { int a [] ={10,3,5,6,-20}; Arrays.sort(a); int n=a.length; System.out.println(Arrays.toString(a)); int result1=a[n-1]*a[n-2]*a[n-3]; int result2=a[0]*a[1]*a[n-1]; int result =Math.max(result1,result2); System.out.println(result); } } Output:[-20, 3, 5, 6, 10] 300 #JavaDeveloper #Arrays #CodingPractice #QualityEngineering #TechLearning
To view or add a comment, sign in
-
-
⚡ Few powerful Java methods every developer should know Some Java methods look small… but they unlock powerful behavior under the hood. Here are a few that are worth understanding 👇 🔹 Class.forName() Loads a class dynamically at runtime 👉 Commonly used when the class name is not known at compile time (e.g., drivers, plugins) 🔹 Thread.yield() Hints the scheduler to pause the current thread 👉 Gives other threads a chance to execute (not guaranteed, just a suggestion) 🔹 String.intern() Moves a String to the String Pool (if not already present) 👉 Helps save memory by reusing identical string values 🔹 map.entrySet() Returns a set of key-value pairs from a Map 👉 Most efficient way to iterate both key and value together 🔹 Object.wait() Makes a thread wait until another thread notifies it 👉 Used for inter-thread communication (must be inside synchronized block) 🔹 Thread.join() Pauses current thread until another thread finishes 👉 Useful when execution order matters 🔹 stream().flatMap() Flattens nested data structures into a single stream 👉 Perfect for transforming lists of lists into a single list 💡 Why these matter? These methods touch core areas of Java: • Concurrency • Memory optimization • Collections • Functional programming Understanding them helps you write cleaner, more efficient code. 📌 Which one do you use most often? #Java #Programming #SoftwareDevelopment #Coding #BackendDevelopment #Tech
To view or add a comment, sign in
-
💻 String vs StringBuffer vs StringBuilder in Java – Know the Difference! In Java, handling text data is very common. Let’s understand the three important classes: 🔹 1. String ✔ Immutable (cannot be changed once created) ✔ Any modification creates a new object ✔ Safe and widely used Example: "String s = "Hello";" "s = s + " World"; // creates new object" --- 🔹 2. StringBuffer ✔ Mutable (can be changed) ✔ Thread-safe (synchronized) ✔ Slightly slower due to synchronization Example: "StringBuffer sb = new StringBuffer("Hello");" "sb.append(" World");" --- 🔹 3. StringBuilder ✔ Mutable (can be changed) ✔ Not thread-safe ✔ Faster than StringBuffer Example: "StringBuilder sb = new StringBuilder("Hello");" "sb.append(" World");" --- 💡 Key Difference: String = Immutable StringBuffer = Mutable + Thread-safe StringBuilder = Mutable + Faster 🚀 Use String for simple tasks, StringBuffer for multi-threading, and StringBuilder for better performance in single-threaded applications. #FortuneCloudTechnology #Java #Programming #String #JavaBasics #Coding #Developers #Learning
To view or add a comment, sign in
-
Q. Can an Interface Extend a Class in Java? This is a common confusion among developers and even I revisited this concept deeply today. - The answer is NO, an interface cannot extend a class. - It can only extend another interface. But there is something interesting: - Even though an interface doesn’t extend Object, all public methods of the Object class are implicitly available inside every interface. Methods like: • toString() • hashCode() • equals() These are treated as abstractly redeclared in every interface. ⚡ Why does Java do this? - To support upcasting and polymorphism, ensuring that any object referenced via an interface can still access these fundamental methods. ❗ Important Rule: While you can declare these methods in an interface, you cannot provide default implementations for them. interface Alpha { default String toString() { // ❌ Compile time error return "Hello"; } } Reason? Because these methods already have implementations in the Object class. Since every class implicitly extends Object, allowing default implementations of these methods in interfaces would create ambiguity during method resolution. Therefore, Java does not allow interfaces to provide default implementations for Object methods. 📌 Interfaces don’t extend Object, but its public methods are implicitly available. However, default implementations for them are not allowed. #Java #OOP #InterviewPreparation #Programming #Developers #Learning #SoftwareEngineering
To view or add a comment, sign in
-
Java Concept Check — Answer Explained 💡 Yesterday I posted a question: Which combination of Java keywords cannot be used together while declaring a class? Options were: A) public static B) final abstract C) public final D) abstract class ✅ Correct Answer: B) final abstract Why? In Java: 🔹 abstract class - Cannot be instantiated (no direct object creation) - Must be extended by another class Example: abstract class A { } 🔹 final class - Cannot be extended by any other class - Object creation is allowed Example: final class B { } The contradiction If we combine them: final abstract class A { } We create a conflict: - "abstract" → class must be inherited - "final" → class cannot be inherited Because these two rules contradict each other, Java does not allow this combination, resulting in a compile-time error. Thanks to everyone who participated in the poll 👇 Did you get the correct answer? #Java #BackendDevelopment #JavaDeveloper #Programming
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
Tricky