🛑 𝗙𝗶𝗻𝗮𝗹 𝘃𝘀. 𝗙𝗶𝗻𝗮𝗹𝗹𝘆 𝘃𝘀. 𝗙𝗶𝗻𝗮𝗹𝗶𝘇𝗲: 𝗖𝗹𝗲𝗮𝗿𝗶𝗻𝗴 𝘁𝗵𝗲 𝗖𝗼𝗻𝗳𝘂𝘀𝗶𝗼𝗻 In the Java world, these three keywords sound almost identical, but they serve completely different purposes. If you're just cleaning up your code, here is the breakdown you need. 1. 𝗙𝗶𝗻𝗮𝗹 (𝗧𝗵𝗲 𝗞𝗲𝘆𝘄𝗼𝗿𝗱) Used to define 𝗶𝗺𝗺𝘂𝘁𝗮𝗯𝗶𝗹𝗶𝘁𝘆 or restrictions. Think of it as "the last version" of something: • 𝗩𝗮𝗿𝗶𝗮𝗯𝗹𝗲𝘀: Makes them constants (cannot be reassigned). • 𝗠𝗲𝘁𝗵𝗼𝗱𝘀: Prevents them from being overridden by subclasses. • 𝗖𝗹𝗮𝘀𝘀𝗲𝘀: Prevents inheritance (e.g., the String class is final). 2. 𝗙𝗶𝗻𝗮𝗹𝗹𝘆 (𝗧𝗵𝗲 𝗕𝗹𝗼𝗰𝗸) Used in 𝗲𝘅𝗰𝗲𝗽𝘁𝗶𝗼𝗻 𝗵𝗮𝗻𝗱𝗹𝗶𝗻𝗴 (try-catch-finally). It represents "guaranteed execution": • The code inside a finally block runs 𝗻𝗼 𝗺𝗮𝘁𝘁𝗲𝗿 𝘄𝗵𝗮𝘁—whether an exception was thrown or not. • 𝗕𝗲𝘀𝘁 𝗨𝘀𝗲: Closing file streams, database connections, or releasing resources to prevent memory leaks. 3. 𝗙𝗶𝗻𝗮𝗹𝗶𝘇𝗲 (𝗧𝗵𝗲 𝗠𝗲𝘁𝗵𝗼𝗱) A protected method inherited from the Object class: • It is invoked by the 𝗚𝗮𝗿𝗯𝗮𝗴𝗲 𝗖𝗼𝗹𝗹𝗲𝗰𝘁𝗼𝗿 just before an object is destroyed. • 𝗦𝘁𝗮𝘁𝘂𝘀: 𝗗𝗲𝗽𝗿𝗲𝗰𝗮𝘁𝗲𝗱 since Java 9. • 𝗪𝗵𝘆? It is unpredictable, unreliable, and can cause significant performance issues. Modern Java favors try-with-resources for cleanup. #Java #Programming #Backend #CodingTips #SoftwareDevelopment
Java Final, Finally, Finalize: Understanding the Confusion
More Relevant Posts
-
Stop writing boilerplate. Let the compiler do the heavy lifting. In modern Java, you can replace a verbose data class with a single line: public record Car(String name) {} Behind the scenes, Java automatically generates: ✅ Private final fields (Immutability by default). ✅ Canonical constructor (State initialization). ✅ Accessor methods (e.g., car.name()). ✅ equals() and hashCode() (Value-based equality). ✅ toString() (Readable output). // What the JVM actually sees: public final class Car extends java.lang.Record { privatefinal String name; public Car(String name) { this.name = name; } public String name() { returnthis.name; } @Overridepublic boolean equals(Object o) { ... } @Overridepublic int hashCode() { ... } @Overridepublic String toString() { ... } } The Result? Cleaner code, fewer bugs, and zero "boilerplate fatigue." Are you still using traditional POJOs, or have you switched to Records? 👇 #Java #CleanCode #SoftwareEngineering #ProgrammingTips #ModernJava
To view or add a comment, sign in
-
𝐎𝐮𝐭 𝐰𝐢𝐭𝐡 𝐭𝐡𝐞 𝐎𝐥𝐝, 𝐈𝐧 𝐰𝐢𝐭𝐡 𝐭𝐡𝐞 𝐍𝐞𝐰 Java has evolved, and with it, a simpler, more modern approach to writing immutable data types records. In previous versions of Java, creating simple value objects required a significant amount of boilerplate code. 𝐓𝐡𝐞 𝐎𝐥𝐝 𝐖𝐚𝐲 public class Point { private final int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } @Override public boolean equals(Object obj) { ... } @Override public int hashCode() { ... } @Override public String toString() { ... } } 𝐓𝐡𝐞 𝐍𝐞𝐰 𝐖𝐚𝐲 Now, with records, all that boilerplate is handled for you. A record automatically generates A constructor equals(), hashCode(), and toString() methods public record Point(int x, int y) {} When you have simple value objects with immutable data. When you don’t need additional logic like setters, mutable fields, or complex methods. #Java #JavaRecords #Programming #Coding #ImmutableData #BoilerplateCode #CleanCode #Java14 #ModernJava #SoftwareDevelopment #CodeSimplification #ObjectOrientedProgramming #JavaBestPractices #JavaTips #JavaDeveloper #TechTrends #DeveloperLife #JavaSyntax #JavaProgramming #RecordClass #TechInnovation #CodingTips #JavaCommunity
To view or add a comment, sign in
-
𝐓𝐡𝐢𝐬 𝐜𝐨𝐝𝐞 𝐬𝐧𝐢𝐩𝐩𝐞𝐭 𝐢𝐬 𝐞𝐧𝐨𝐮𝐠𝐡 𝐭𝐨 𝐜𝐨𝐧𝐟𝐮𝐬𝐞 𝐬𝐨𝐦𝐞𝐨𝐧𝐞 𝐰𝐢𝐭𝐡 𝐉𝐚𝐯𝐚. 😁 Let me introduce you to the concept of wrapper classes and autoboxing first. 𝐖𝐑𝐀𝐏𝐏𝐄𝐑 𝐂𝐋𝐀𝐒𝐒𝐄𝐒: These are classes used to wrap primitive values so we can treat them like objects. This is essential for the Collection framework (like ArrayList), which only works with objects. 𝐀𝐔𝐓𝐎𝐁𝐎𝐗𝐈𝐍𝐆: The process of converting primitive values to wrapper objects is implicit. We don't need the new keyword. Now let's discuss the code: 𝐂𝐎𝐃𝐄 1: 𝘪𝘯𝘵 𝘢 = 100; 𝘪𝘯𝘵 𝘣 = 100; These are primitive values. For primitives, the == operator compares the actual values. Since both are 100, the output is 𝐭𝐫𝐮𝐞. 𝐂𝐎𝐃𝐄 2: Integer wrapper classes have an Integer Cache. By default, Java caches all Integer objects in the range of -128 to 127. 𝘐𝘯𝘵𝘦𝘨𝘦𝘳 𝘱 = 100; 𝘐𝘯𝘵𝘦𝘨𝘦𝘳 𝘲 = 100; Since 100 is in the cache, Java points both variables to the same object memory location. The output is 𝐭𝐫𝐮𝐞. 𝐂𝐎𝐃𝐄 3: 𝘐𝘯𝘵𝘦𝘨𝘦𝘳 𝘺 = 128; 𝘐𝘯𝘵𝘦𝘨𝘦𝘳 𝘻 = 128; Because 128 is outside the cache range, Java creates two distinct objects in memory. Since == compares memory references for objects, the output is 𝐟𝐚𝐥𝐬𝐞. ~Anuprash Gautam 🍵 𝘒𝘦𝘦𝘱 𝘭𝘦𝘢𝘳𝘯𝘪𝘯𝘨 𝘢𝘯𝘥 𝘣𝘳𝘦𝘸𝘪𝘯𝘨 𝘤𝘰𝘧𝘧𝘦𝘦.😊 #Java #programming #autoboxing #oops
To view or add a comment, sign in
-
-
🧠 var Keyword in Java — Type Inference Explained #️⃣ var keyword in Java Introduced in Java 10, var allows local variable type inference. 👉 The compiler automatically determines the variable type. 🔹 What is var? var lets Java infer the type from the assigned value. Instead of writing: String name = "Vijay"; You can write: var name = "Vijay"; The compiler still treats it as String. 👉 var is NOT dynamic typing 👉 Type is decided at compile-time 🔹 Why was var introduced? Before var: ⚠ Long generic types ⚠ Repeated type declarations ⚠ Verbose code ⚠ Reduced readability Example: Map<String, List<Integer>> data = new HashMap<>(); With var: var data = new HashMap<String, List<Integer>>(); Cleaner and easier to read. 🔹 Rules of using var ✔ Must initialize immediately ✔ Only for local variables ✔ Cannot use without value ✔ Cannot use for fields or method parameters ✔ Type cannot change after assignment Invalid: var x; // ❌ compile error 🔹 Where should we use var? Use var when: ✔ Type is obvious from right side ✔ Long generic types ✔ Stream operations ✔ Loop variables ✔ Temporary variables Avoid when: ❌ It reduces readability ❌ Type becomes unclear 🧩 Real-world examples var list = List.of(1, 2, 3); var stream = list.stream(); var result = stream.map(x -> x * 2).toList(); Perfect for modern functional style. 🎯 Interview Tip If interviewer asks: Is var dynamically typed? Answer: 👉 No. Java is still statically typed. 👉 var only removes repetition. 👉 Type is fixed at compile-time. 🏁 Key Takeaways ✔ Introduced in Java 10 ✔ Local variable type inference ✔ Reduces boilerplate ✔ Improves readability ✔ Not dynamic typing ✔ Use wisely #Java #Java10 #VarKeyword #ModernJava #JavaFeatures #CleanCode #ProgrammingConcepts #BackendDevelopment #JavaDeepDive #TechWithVijay #VFN #vijayfullstacknews
To view or add a comment, sign in
-
-
🚀 𝗔𝗿𝗿𝗮𝘆𝗟𝗶𝘀𝘁 𝘃𝘀 𝗟𝗶𝗻𝗸𝗲𝗱𝗟𝗶𝘀𝘁 — 𝗪𝗵𝗶𝗰𝗵 𝗢𝗻𝗲 𝗦𝗵𝗼𝘂𝗹𝗱 𝗪𝗲 𝗨𝘀𝗲? While revising the Java Collection Framework, I realized something important. We often use ArrayList by default. But do we really understand when to use LinkedList instead? Both implement the List interface, but internally they are completely different. 🔹 𝗔𝗿𝗿𝗮𝘆𝗟𝗶𝘀𝘁 ArrayList is backed by a dynamic array. That means: • Accessing elements using index is very fast • But inserting or deleting in the middle requires shifting elements So it works best when: ✔ We mostly read data ✔ Random access is frequent 🔹 𝗟𝗶𝗻𝗸𝗲𝗱𝗟𝗶𝘀𝘁 LinkedList is backed by a doubly linked list. That means: • Insertion and deletion are faster • Accessing elements by index is slower So it works best when: ✔ We frequently add/remove elements ✔ We modify data often 𝗦𝗶𝗺𝗽𝗹𝗲 𝗖𝗼𝗱𝗲 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 ->List<Integer> list1 = new ArrayList<>(); ->List<Integer> list2 = new LinkedList<>(); Same interface. Different internal working. Different performance behavior. 💡 𝗪𝗵𝗮𝘁 𝗜 𝗟𝗲𝗮𝗿𝗻𝗲𝗱 Choosing the right data structure is not about syntax. It’s about understanding the use case. The more I revise Collections, the more I realize that fundamentals matter more than memorizing methods. #Java #CollectionFramework #ArrayList #LinkedList #Programming #DSA #LearningJourney
To view or add a comment, sign in
-
-
📄Java clone() 1️⃣ What clone means Shallow copy → copy the Object reference Deep copy → copy the Object reference+ copy their fields deeply 2️⃣ What Java actually does by default super.clone() ➡ Copies object structure ➡ Inner objects are shared So Java clone copies: ✔ primitives ❌ references (pointer copied, not object) 3️⃣ How we make it Deep Copy Manually clone inner objects: new Location(this.location) So: super.clone() + manual cloning = Deep Copy 4️⃣ Return Type Confusion Java forces method signature: Object clone() Compiler only sees Object So we cast: User copy = (User) original.clone(); 🧠 Casting does NOT create or convert objects It only changes how compiler views the reference 5️⃣ What actually happens internally clone() → memory duplication (no constructor called) Casting → only permission to access methods Object ref = userClone; ((User)ref).getName(); // allowed after cast No new object created here. 6️⃣ Important internal fact clone() in Object is a native method Real implementation exists inside JVM (C/C++), so IDE cannot open its source code. return (User) super.clone(); → works, but only shallow copy return new User(this); → works and can be deep copy GitHub Link: https://lnkd.in/g5Zj48m6 🔖Frontlines EduTech (FLM) #java #coreJava #BackendDevelopment #Programming #CleanCode #ResourceManagement #AustraliaJobs #SwitzerlandJobs #NewZealandJobs #USJobs #cloneMethod #deepCopy #shallowCopy
To view or add a comment, sign in
-
-
🚀 Day 8 — Restarting My Java Journey with Consistency Today’s topic looked familiar: 🔹 while loop 🔹 do-while loop 🔹 for loop 🔹 break & continue Most of this was already known to me. But revision with depth always reveals something new. 🔁 Loops — More Than Just Repetition We often write: for(int i = 0; i < n; i++) { // code } But today I revisited some important insights: ✔ All three parts in a for loop are optional ✔ Multiple variables can be initialized using comma separation ✔ Conditional statements rely completely on logical operators ✔ do-while is very useful in menu-driven programs (runs at least once) 🤯 Interesting Question Why don’t we usually use short instead of int in loops? Because in Java, due to type promotion, short gets promoted to int during arithmetic operations. So practically, using short in loops doesn’t provide any benefit. That’s not syntax knowledge. That’s understanding how Java works internally. 🆕 The New Concept I Learned — Labels in Java This was something I had never used before. outer: for(int i = 1; i <= 10; i++) { inner: for(int j = 1; j <= i; j++) { break outer; // breaks the outer loop directly } } 🔹 Labels allow us to control outer loops from inside inner loops 🔹 Useful in nested loop scenarios 🔹 Makes flow control very powerful (if used wisely) Learning daily with Coder Army and Aditya Tandon Bhaiya and Rohit Negi Bhaiya #Day8 #Java #Consistency #BackendDevelopment #LearningJourney #SoftwareEngineering #CoderArmy
To view or add a comment, sign in
-
-
Most Java performance problems weren't caused by bad algorithms. They were caused by objects no one thought twice about creating. Here's the hidden cost most developers overlook: Every object you create in Java lands on the heap. The Garbage Collector is responsible for cleaning it up. And that cleanup isn't free — it consumes CPU, and at worst, it pauses your entire application. Here's how it unfolds: → Every new object is born in Eden — a small, fast memory space → Fill it too quickly with throwaway objects and Java triggers a GC sweep → Most short-lived objects die there — that part is cheap and fast → But survivors get promoted deeper into memory (Old Generation) → When Old Generation fills up, Java runs a Full GC — and your app pauses That final pause isn't milliseconds. In heavy systems, it can be seconds. Users feel it. And the surprising part? Most of this pressure comes from innocent-looking code: ❌ new String("hello") instead of just "hello" ❌ String concatenation inside loops ❌ Autoboxing primitives (int → Integer) without thinking ❌ Calling Pattern.compile() inside a method that runs thousands of times ❌ Creating SimpleDateFormat repeatedly instead of using java.time None of these feel dangerous when you write them. But at scale, they add up to thousands of short-lived objects per second — and a GC that's constantly playing catch-up. The fix isn't complicated: ✅ Prefer primitives over wrapper types ✅ Use StringBuilder for string building in loops ✅ Cache reusable objects as static final constants ✅ Embrace immutable java.time classes — they're designed for reuse The best object, from a GC perspective, is the one you never created. I'm curious — what's the worst unnecessary allocation you've come across in a real codebase? And did it actually cause a production issue? Drop your story below 👇 Let's learn from each other. #Java #SoftwareEngineering #Performance #GarbageCollection #BackendDevelopment #CleanCode #CodeReview
To view or add a comment, sign in
-
𝐉𝐚𝐯𝐚 𝐢𝐬 𝐚𝐥𝐰𝐚𝐲𝐬 𝐏𝐚𝐬𝐬-𝐛𝐲-𝐕𝐚𝐥𝐮𝐞. 𝐒𝐨 𝐰𝐡𝐲 𝐝𝐢𝐝 𝐦𝐲 𝐚𝐫𝐫𝐚𝐲 𝐜𝐡𝐚𝐧𝐠𝐞? 🤔 I wrote a simple program to test how Java handles method arguments. [1] Declared an array 𝐚𝐫𝐫 in 𝐦𝐚𝐢𝐧. [2] Passed it to a 𝐜𝐡𝐚𝐧𝐠𝐞(𝐢𝐧𝐭[] 𝐧𝐮𝐦𝐬) method. [3] Modified 𝐧𝐮𝐦𝐬[𝟎] AND 𝐧𝐮𝐦𝐬[𝟏] inside the method. [4] The original 𝐚𝐫𝐫 was updated. 𝐓𝐡𝐞 𝐄𝐧𝐠𝐢𝐧𝐞𝐞𝐫𝐢𝐧𝐠 𝐄𝐱𝐩𝐥𝐚𝐧𝐚𝐭𝐢𝐨𝐧: Java is strictly Pass-by-Value. When I passed 𝐚𝐫𝐫, I didn't pass the object itself. I passed a copy of the reference variable. [A] Both the original 𝐚𝐫𝐫 and the method parameter 𝐧𝐮𝐦𝐬 hold the same memory address (pointing to the same array object in the Heap). [B] So, when 𝐧𝐮𝐦𝐬 modifies the data, it modifies the shared object. Understanding Stack (references) vs. Heap (objects) is crucial for avoiding bugs. #Java #MemoryManagement #SoftwareEngineering #CodingInterviews #LearningInPublic #BackendDevelopment #DataStructures #Coding #WeMakeDevs #100DaysOfCode #IntelliJ
To view or add a comment, sign in
-
-
🔥 Ever wondered what REALLY happens when you have return statements in try, catch, AND finally? I just published a comprehensive guide on Java's try-catch-finally blocks that covers every scenario you'll encounter in production code. ❌ A return in finally COMPLETELY SUPPRESSES exceptions from try/catch ❌ You can't share catch blocks between multiple try blocks ✅ Finally can modify objects but NOT primitives before they return ✅ Try-with-resources eliminates 90% of finally block headaches 💡 The article covers critical scenarios including: • Multiple try blocks (and why they can't share catch blocks) • Nested exception handling • The dangerous exception suppression pattern • Primitive vs Object behavior in finally blocks • Modern try-with-resources patterns One scenario that catches even senior developers: try { throw new Exception("Critical error!"); } finally { return 1; // The exception is LOST forever! 😱 } Golden rule I learned: Use finally for cleanup, NEVER for control flow. Perfect for: ✅ Java developers at any level ✅ Anyone preparing for technical interviews ✅ Developers debugging mysterious production issues 🔗 Read the full guide here: [https://lnkd.in/gSiBQHjx] What's the most surprising exception handling behavior you've encountered? #Java #Programming #SoftwareEngineering #CleanCode #BestPractices #TechBlog #CodingTips #JavaDevelopment #SoftwareDevelopment
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