🔥 final vs finally vs finalize() — Don’t mix them up! These 3 Java terms look similar but serve completely different purposes. Let’s break it down 👇 --- 🟢 1. final (Keyword) ✔ Used for constants & immutability ✔ Prevents modification / overriding 💡 Examples: final int MAX_VALUE = 100; // constant final void show() {} // cannot override final class A {} // cannot extend 👉 Think: Restriction / Protection --- 🔵 2. finally (Block) ✔ Used in exception handling ✔ Always executes (even if exception occurs) 💡 Example: try { int x = 10 / 0; } catch (Exception e) { System.out.println("Error"); } finally { System.out.println("Always runs"); } 👉 Think: Cleanup (DB, files, connections) --- 🔴 3. finalize() (Method) ⚠️ ✔ Called by Garbage Collector before object destruction ❌ Deprecated since Java 9 💡 Example: @Override protected void finalize() throws Throwable { System.out.println("Cleanup"); } 👉 Not reliable ❌ 👉 Use try-with-resources instead ✅ --- ⚡ Key Differences Feature final finally finalize() Type Keyword Block Method Purpose Restrict changes Cleanup in exceptions Cleanup before GC Usage Variables, methods, classes try-catch Object lifecycle Status ✅ Active ✅ Active ❌ Deprecated --- 🎯 Quick Trick to Remember 👉 final = no change allowed 👉 finally = always executes 👉 finalize() = forgotten (deprecated) 😄 --- 💬 Which one confused you the most earlier? Let me know 👇 #Java #SpringBoot #BackendDevelopment #Programming #JavaConcepts #InterviewPrep 🚀
Java final vs finally vs finalize() - Key differences and usage
More Relevant Posts
-
🚀 Day 8 – final vs finally vs finalize (Clearing the Confusion) These three look similar but serve completely different purposes in Java. 👉 final (keyword) Used to restrict modification final int x = 10; // cannot be changed ✔ Variables → constant ✔ Methods → cannot be overridden ✔ Classes → cannot be extended --- 👉 finally (block) Used in exception handling try { // code } finally { // always executes } ✔ Runs whether exception occurs or not ✔ Commonly used for cleanup (closing resources) --- 👉 finalize() (method) @Override protected void finalize() throws Throwable { // cleanup code } ✔ Called by Garbage Collector before object destruction ⚠️ Important insight: "finalize()" is deprecated and unreliable — not recommended in modern Java. --- 💡 Quick takeaway: - "final" → restriction - "finally" → execution guarantee - "finalize()" → outdated cleanup mechanism Understanding these avoids confusion in both interviews and real projects. #Java #BackendDevelopment #JavaBasics #ExceptionHandling #LearningInPublic
To view or add a comment, sign in
-
⏳ Day 16 – 1 Minute Java Clarity – final Keyword in Java What if something should NEVER change? Use final! 🔒 📌 What is final? The final keyword restricts modification. 👉 It can be applied to variables, methods and classes. 📌 1️⃣ Final Variable: final int SPEED_LIMIT = 120; SPEED_LIMIT = 150; // ❌ Compilation Error! 👉 Once assigned, value can NEVER be changed. ✔ By convention, final variables are written in UPPER_CASE. 📌 2️⃣ Final Method: class Vehicle { final void start() { System.out.println("Engine started!"); } } 👉 Child class CANNOT override this method. ✔ Used when core behavior must stay consistent. 📌 3️⃣ Final Class: final class PaymentGateway { // Cannot be extended } 👉 No class can inherit from a final class. ✔ Example from Java itself → String class is final! 💡 Real-time Example: Think of a traffic system 🚦 Speed limit on a highway = 120 km/h No one can change that rule → that's your final variable! PI value in Math = 3.14159… It never changes → Math.PI is declared final in Java ✅ ⚠️ Interview Trap: final vs finally vs finalize — all different! 👉 final → restricts change 👉 finally → block in exception handling 👉 finalize → called by GC before object is destroyed 💡 Quick Summary ✔ final variable → value can't change ✔ final method → can't be overridden ✔ final class → can't be inherited ✔ String is a final class in Java! 🔹 Next Topic → Access Modifiers in Java Did you know String is a final class? Drop 💡 if this was new! hashtag #Java #JavaProgramming #FinalKeyword #CoreJava #JavaDeveloper #BackendDeveloper #Coding #Programming #SoftwareEngineering #LearningInPublic #100DaysOfCode #ProgrammingTips #1MinuteJavaClarity
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 17 Feature: Record Classes What is a Record Class? A record class is mainly used to create DTOs (Data Transfer Objects) in a simple and clean way. Why DTOs? DTOs are used to transfer data: • Between services • From backend to frontend Key Features of Record Classes: Immutable by default (data cannot be changed after creation) Less code (no need to write getters, constructors, etc.) When you create a record, Java automatically provides: Private final fields All-arguments constructor Getter methods (accessor methods) toString(), equals(), hashCode() Example: public record Customer(int customerId, String customerName, long phone) {} Usage: Customer customer = new Customer(1011, "John", 9890080012L); System.out.println(customer.customerId()); Important Points: Record class is implicitly final Cannot extend other classes Internally extends java.lang.Record Can implement interfaces (normal or sealed) Can have static methods and instance methods Cannot have extra instance variables With Sealed Interface: public sealed interface UserActivity permits CreateUser, DeleteUser { boolean confirm(); } public record CreateUser() implements UserActivity { public boolean confirm() { return true; } } Before Java 17: We used Lombok to reduce boilerplate code. After Java 17: Record classes make code: Cleaner Shorter Easier to maintain #Java #Java17 #BackendDevelopment #FullStackDeveloper #Programming #SoftwareEngineering
To view or add a comment, sign in
-
Most Java mistakes I see in code reviews come from the same 20 misunderstandings. After reviewing thousands of pull requests, these patterns keep showing up, especially from developers in their first 2 years. Here is what trips people up the most: → Using == instead of .equals() for String comparison → Mutating Date objects when LocalDate exists → Throwing checked exceptions for programming errors → Using raw types instead of generics → Concatenating Strings in loops instead of StringBuilder → Writing nested null checks instead of using Optional → Defaulting to arrays when ArrayList gives you flexibility → Wrapping everything in synchronized when ConcurrentHashMap exists → Catching Exception instead of the specific type you expect → Making utility methods static when they should be instance methods → Using new String("hello") instead of string literals → Using Integer when int would suffice → Repeating type args instead of using the diamond operator → Manual close() in finally instead of try-with-resources → Using static final int constants instead of enums → Writing verbose for-if-add loops instead of streams → Using Arrays.asList when List.of gives true immutability → Spelling out full types when var keeps code clean → Writing boilerplate classes when records do the job → Concatenating strings with \n instead of using text blocks None of these are hard to fix once you see the pattern. The real problem is that nobody points them out early enough. Save this for your next code review. #Java #SoftwareDevelopment #Programming #CleanCode #CodingTips
To view or add a comment, sign in
-
🚀 Java String vs StringBuffer vs StringBuilder — Explained Simply Understanding how Java handles memory, mutability, and performance can completely change how you write efficient code. Here’s the quick breakdown 👇 🔒 String Immutable (once created, cannot change) Stored in String Constant Pool (SCP) Memory efficient but costly in loops 🔐 StringBuffer Mutable + Thread-safe Slower due to synchronization Safe for multi-threaded environments ⚡ StringBuilder Mutable + Fast Not thread-safe Best choice for performance-heavy operations 🧠 Real Insight (Important for Interviews): 👉 "java" literals share the same memory (SCP) 👉 new String("java") creates a separate object 👉 s = s + "dev" creates a NEW object every time 👉 StringBuilder.append() modifies the SAME object 🔥 Golden Rule: Constant data → String Multi-threading → StringBuffer Performance / loops → StringBuilder ⚠️ Common Mistake: Using String inside loops 👇 Leads to multiple object creation → memory + performance issues 💬 Let’s Discuss (Drop your answers): Why is String immutable in Java? What happens when you use + inside loops? StringBuilder vs StringBuffer — what do you use by default? Difference between == and .equals()? Can StringBuilder break in multi-threading? 👇 I’d love to hear your thoughts! #Java #JavaDeveloper #Programming #Coding #SoftwareEngineering #InterviewPreparation #TechLearning #BackendDevelopment #PerformanceOptimization #Developers #JavaTips #LearnToCode #CleanCode
To view or add a comment, sign in
-
-
🚀 I created a complete guide for Java Collections (Beginner → Advanced) After spending a lot of time understanding Java Collections deeply, I decided to put everything into one clean, structured HTML file. 📂 And I’m sharing it here. 💡 What’s inside? ✔️ Collection Framework basics ✔️ Complete hierarchy (List, Set, Queue, Map) ✔️ ArrayList vs LinkedList (with performance breakdown) ✔️ Set & Map deep concepts (HashSet, TreeSet, HashMap, etc.) ✔️ All important methods (cheatsheet style) ✔️ Iterator vs ListIterator ✔️ Comparable vs Comparator ✔️ Thread safety explained ✔️ Interview Q&A (very important) ✔️ Coding patterns + real use cases (SDET focused)
To view or add a comment, sign in
-
Day 12 Today’s Java practice was about solving the Leader Element problem. Instead of using nested loops, I used a single traversal from right to left, which made the solution clean and efficient. A leader element is one that is greater than all the elements to its right. Example: Input: {16,17,5,3,4,2} Leaders: 17, 5, 4, 2 🧠 Approach I used: ->Start traversing from the rightmost element ->Keep track of the maximum element seen so far ->If the current element is greater than the maximum, it becomes a leader ->This is an efficient approach with O(n) time complexity and no extra space. ================================================= // Online Java Compiler // Use this editor to write, compile and run your Java code online class Main { public static void main(String[] args) { int a [] ={16,17,5,3,4,2}; int length=a.length; int maxRight=a[length-1]; System.out.print("Leader elements are :"+maxRight+" "); for(int i=a[length-2];i>=0;i--) { if(a[i]>maxRight) { maxRight=a[i]; System.out.print(maxRight+" "); } } } } Output:Leader elements are :2 4 5 17 #AutomationTestEngineer #Selenium #Java #DeveloperJourney #Arrays
To view or add a comment, sign in
-
-
🚀 Day 2 of my Java journey — Deep dive into Strings! Today I went beyond basic Strings and learned 3 powerful concepts: 📦 Arrays ✅ What is an array — storing multiple values in one variable ✅ How to declare and initialize an array ✅ Accessing elements using index (starts from 0!) ✅ Looping through arrays 🔤 String Constant Pool ✅ Java stores String literals in a special memory area called the String Constant Pool ✅ If two variables have the same value, they share ONE object — saves memory! ✅ String a = "Subodh" and String b = "Subodh" → both point to the same object ✅ Using new String() creates a separate object — avoid it! 🔨 StringBuilder ✅ Strings in Java are immutable — once created they cannot change ✅ Every time you do s = s + "text", a new object is created — wasteful! ✅ StringBuilder solves this — it modifies the SAME object ✅ Use it when you are building/changing strings frequently ✅ Fast and efficient for single-threaded programs 🔒 StringBuffer ✅ Same as StringBuilder but thread-safe ✅ Use when multiple threads are accessing the same string ✅ Slightly slower than StringBuilder but safer 💡 One line summary: String = immutable | StringBuilder = fast + mutable | StringBuffer = safe + mutable Every concept I learn makes me more confident as a developer. This is Day 2 of many! 💪 If you are learning Java too, let us connect and grow together! 🙏 #Java #JavaDeveloper #Strings #StringBuilder #StringBuffer #100DaysOfCode #LearningToCode #Programming #BackendDevelopment #TechCareer
To view or add a comment, sign in
-
⏳ Day 13 – 1 Minute Java Clarity – String Immutability in Java Strings look simple… but there’s something powerful happening behind the scenes 📌 What is String Immutability? In Java, once a String object is created, it cannot be changed. 👉 Instead of modifying the existing string, Java creates a new object. 📌 Example: String str = "Hello"; str.concat(" World"); System.out.println(str); 👉 Output: Hello ❌ (not "Hello World") 💡 Why? Because concat() creates a new object, but we didn’t store it. ✔ Correct way: str = str.concat(" World"); System.out.println(str); // Hello World ✅ 💡 Real-time Example: Think of a username in a system: String username = "user123"; username.toUpperCase(); Even after calling toUpperCase(), the original value stays "user123" unless reassigned. 📌 Why Strings are Immutable? ✔ Security (used in passwords, URLs) ✔ Thread-safe (no synchronization issues) ✔ Performance optimization using String Pool ⚠️ Important: Too many string modifications? Use StringBuilder instead. 💡 Quick Summary ✔ Strings cannot be modified after creation ✔ Operations create new objects ✔ Always reassign if you want changes 🔹 Next Topic → Type casting in Java Have you ever faced issues because of String immutability? 👇 #Java #JavaProgramming #Strings #CoreJava #JavaDeveloper #BackendDeveloper #Coding #Programming #SoftwareEngineering #LearningInPublic #100DaysOfCode #ProgrammingTips #1MinuteJavaClarity
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