🚀 Java Deep Dive: "try-with-resources" Closing Order (Real Example) 🔥 Most developers know it auto-closes resources… But the ORDER? That’s where interviews get tricky 😏 👉 Real-world example: import java.io.*; public class Main { public static void main(String[] args) throws Exception { try (FileInputStream fis = new FileInputStream("test.txt"); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr)) { System.out.println("Reading file..."); } } } 💡 Output: Reading file... (then resources close automatically) 👉 Actual closing order: BufferedReader InputStreamReader FileInputStream Why reverse order? Because Java follows LIFO (Last In, First Out) 👉 Last opened → First closed 🔥 Understand the chain: Open order: FileInputStream → InputStreamReader → BufferedReader Close order: BufferedReader → InputStreamReader → FileInputStream ⚠️ Interview Tip: Always remember dependency: - Outer resource depends on inner ones - So it must close FIRST 💬 One-liner to remember: “Resources open in sequence… but close in reverse.” #Java #JavaInterview #Coding #ExceptionHandling #IO #Programming #Developers #TechTips
Java try-with-resources Closing Order: LIFO and Dependency
More Relevant Posts
-
🚫 Most Common Java OOP Mistake (Even in Interviews) Many developers expect this to print 20: class Shape { int x = 10; void draw() { System.out.println("Shape draw"); } } class Circle extends Shape { int x = 20; void draw() { System.out.println("Circle draw"); } } public class Test { public static void main(String[] args) { Shape s = new Circle(); System.out.println(s.x); // ❌ prints 10 s.draw(); // ✅ prints "Circle draw" } } Why this happens? 👉 Java treats variables and methods differently: Methods → runtime (object decides) Variables → compile time (reference decides) So: s.draw() → uses Circle (object type) s.x → uses Shape (reference type) Golden Rule 👉 “Methods are polymorphic, variables are not.” This tiny concept is one of the most common sources of confusion in OOP—and a favorite interview trap. #Java #OOP #Programming #CodingInterview #SoftwareDevelopment
To view or add a comment, sign in
-
🚀 Do you really know the order in which Java executes your code? Most developers write code… But fewer truly understand how Java executes it behind the scenes. Let’s break one of the most asked (and misunderstood) concepts 👇 🧠 Java Execution Order (Class → Object) Whenever a class is used and an object is created, Java follows this strict order: 👉 Step 1: Static Phase (Runs only once) - Static variables - Static blocks ➡ Executed top to bottom 👉 Step 2: Instance Phase (Runs every time you create an object) - Instance variables - Instance blocks ➡ Executed top to bottom 👉 Step 3: Constructor - Finally, the constructor is executed --- 🔥 Final Order (Must Remember) ✔ Static Variables ✔ Static Blocks ✔ Instance Variables ✔ Instance Blocks ✔ Constructor --- 🧩 Example class Demo { static int a = print("Static A"); static { print("Static Block"); } int x = print("Instance X"); { print("Instance Block"); } Demo() { print("Constructor"); } static int print(String msg) { System.out.println(msg); return 0; } public static void main(String[] args) { new Demo(); } } 💡 Output: Static A Static Block Instance X Instance Block Constructor --- ⚠️ Pro Tips 🔹 Static runs only once per class 🔹 Instance logic runs for every object 🔹 In inheritance: - Parent → Child (Static) - Parent → Constructor → Child (Instance) --- 🎯 Why this matters? Understanding this helps you: ✔ Debug tricky initialization issues ✔ Write predictable code ✔ Perform better in interviews --- 💬 Next time you write a class, ask yourself: “What runs first?” #Java #JavaInternals #Programming #Developers #CodingInterview #TechLearning
To view or add a comment, sign in
-
-
𝗝𝗮𝘃𝗮 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗧𝗿𝗮𝗽: 𝗜𝗻𝘁𝗲𝗴𝗲𝗿 𝗖𝗮𝗰𝗵𝗶𝗻𝗴 & 𝗪𝗿𝗮𝗽𝗽𝗲𝗿 𝗚𝗼𝘁𝗰𝗵𝗮𝘀 𝗘𝘅𝗽𝗹𝗮𝗶𝗻𝗲𝗱! Consider this simple code: class Main { public static void main(String[] args) { Integer a = 128; Integer b = 128; System.out.println(a == b); // ? System.out.println(a.equals(b)); // ? } } 🔍 Output: false true 🤔 Why does this happen? Java internally caches Integer objects in the range -128 to 127. ✅ Within range → same object → == is true ❌ Outside range → new objects → == is false 👉 == compares references (memory address) 👉 .equals() compares actual values 🔥 What about other wrapper classes? ✔ Cached Wrappers: Integer → -128 to 127 Byte → all values cached Short → -128 to 127 Long → -128 to 127 Character → 0 to 127 Boolean → only true & false (always cached) 👉 Example: Integer x = 100; Integer y = 100; System.out.println(x == y); // true ✅ ❗ NOT Cached: Float Double 👉 Example: Float f1 = 10.0f; Float f2 = 10.0f; System.out.println(f1 == f2); // false ❌ Double d1 = 10.0; Double d2 = 10.0; System.out.println(d1 == d2); // false ❌ 💥 Why no caching for Float/Double? Extremely large range of values Precision & representation complexity Not memory-efficient to cache 📌 Golden Rule: 👉 Never use == for wrapper comparison 👉 Always use .equals() or unbox to primitive 🚀 Pro Tip: You can extend Integer cache using JVM option: -XX:AutoBoxCacheMax=<value> 🎯 Interview Insight: This is a classic trap to test: Java memory concepts Autoboxing & unboxing Object vs primitive understanding 💡 Bonus Tip: Be careful with null values when unboxing: Integer i = null; int j = i; // Throws NullPointerException ⚠️ #Java #Programming #InterviewPrep #JavaTips #Coding #Developers #TechCareers
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
-
-
Ever wondered what happens internally when a Java class gets loaded? 🤔 When a class is used for the first time, JVM follows a fixed sequence: 1️⃣ Static Variable Initialization 2️⃣ Static Block Execution 3️⃣ Class Becomes Ready And when an object is created: 4️⃣ Instance Variable Initialization 5️⃣ Instance Block Execution 6️⃣ Constructor Execution So the actual flow looks like this: Static Variable → Static Block → Instance Variable → Instance Block → Constructor Important points: Static blocks run only once when the class is loaded Constructors run every time an object is created Static methods can be called without creating an object Non-static methods require an object This is one of the most commonly asked concepts in Java interviews. #Java #JVM #JavaDeveloper #Programming #Coding #SoftwareEngineer #BackendDevelopment #JavaInterview #Developers
To view or add a comment, sign in
-
-
Think var in Java is just about saving keystrokes? Think again. When Java introduced var, it wasn’t just syntactic sugar — it was a shift toward cleaner, more readable code. So what is var? var allows the compiler to automatically infer the type of a local variable based on the assigned value. Instead of writing: String message = "Hello, Java!"; You can write: var message = "Hello, Java!"; The type is still strongly typed — it’s just inferred by the compiler. Why developers love var: Cleaner Code – Reduces redundancy and boilerplate Better Readability – Focus on what the variable represents, not its type Modern Java Practice – Aligns with newer coding standards But here’s the catch: Cannot be used without initialization Only for local variables (not fields, method params, etc.) Overuse can reduce readability if the type isn’t obvious Not “dynamic typing” — Java is still statically typed Pro Insight: Use var when the type is obvious from the right-hand side — avoid it when it makes the code ambiguous. Final Thought: Great developers don’t just write code — they write code that communicates clearly. var is a tool — use it wisely, and your code becomes not just shorter, but smarter. Special thanks to Syed Zabi Ulla and PW Institute of Innovation for continuous guidance and learning support. #Java #Programming
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
-
-
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
-
💻 Generics in Java — Write Flexible & Type-Safe Code 🚀 If you’ve ever faced ClassCastException or messy type casting… Generics are your solution 🔥 This visual breaks down Java Generics in a simple yet practical way 👇 🧠 What are Generics? Generics allow you to write type-safe and reusable code by using type parameters (<T>). 👉 Instead of hardcoding data types, you write code that works with any type 🔍 Why Generics? ✔ Eliminates explicit type casting ✔ Ensures compile-time type safety ✔ Improves code reusability ✔ Makes code cleaner and readable 🔄 Core Concepts: 🔹 Generic Class class Box<T> { T data; } 👉 Same class → works with String, Integer, etc. 🔹 Generic Method public <T> void printArray(T[] arr) 👉 Works for any data type 🔹 Bounded Types <T extends Number> 👉 Restrict types (only numbers allowed) 🔹 Wildcards (?) <?> → Any type <? extends T> → Upper bound <? super T> → Lower bound 🔹 Type Inference (Diamond Operator) List<String> list = new ArrayList<>(); 👉 Cleaner code, compiler infers type ⚡ Generics with Collections: List<String> names = new ArrayList<>(); 👉 Ensures only String values are stored 💡 Real impact: Without generics → Runtime errors ❌ With generics → Compile-time safety ✅ 🎯 Key takeaway: Generics are not just syntax — they are the foundation of writing robust, scalable, and reusable Java code. #Java #Generics #Programming #BackendDevelopment #SoftwareEngineering #Coding #100DaysOfCode #Learning
To view or add a comment, sign in
-
-
💻 Generics in Java — Write Flexible & Type-Safe Code 🚀 If you’ve ever faced ClassCastException or messy type casting… Generics are your solution 🔥 This visual breaks down Java Generics in a simple yet practical way 👇 🧠 What are Generics? Generics allow you to write type-safe and reusable code by using type parameters (<T>). 👉 Instead of hardcoding data types, you write code that works with any type 🔍 Why Generics? ✔ Eliminates explicit type casting ✔ Ensures compile-time type safety ✔ Improves code reusability ✔ Makes code cleaner and readable 🔄 Core Concepts: 🔹 Generic Class class Box<T> { T data; } 👉 Same class → works with String, Integer, etc. 🔹 Generic Method public <T> void printArray(T[] arr) 👉 Works for any data type 🔹 Bounded Types <T extends Number> 👉 Restrict types (only numbers allowed) 🔹 Wildcards (?) <?> → Any type <? extends T> → Upper bound <? super T> → Lower bound 🔹 Type Inference (Diamond Operator) List<String> list = new ArrayList<>(); 👉 Cleaner code, compiler infers type ⚡ Generics with Collections: List<String> names = new ArrayList<>(); 👉 Ensures only String values are stored 💡 Real impact: Without generics → Runtime errors ❌ With generics → Compile-time safety ✅ 🎯 Key takeaway: Generics are not just syntax — they are the foundation of writing robust, scalable, and reusable Java code. #Java #Generics #Programming #BackendDevelopment #SoftwareEngineering #Coding #100DaysOfCode #Learning
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
Right