❌ == is NOT the same as equals() in java They look similar, but they answer two different questions. 🔸== operator Checks reference equality ➡️ Do both variables point to the same object? 🔸equals() method Checks logical equality ➡️ Do both the objects have same value/content? ☘️ Example String a = new String("Java"); String b = new String("Java"); System.out.println(a == b); // false (different objects) System.out.println(a.equals(b)); // true (same content) Even though the text is the same, a and b are stored at different memory locations. 💡Thumb Rule 🔸Use == for primitive types (int, double, boolean) 🔸Use equals for objects (String, custom classes) Getting this wrong can cause subtle bugs, especially when comparing Strings. #Java #SoftwareEngineering #Cleancode #Programming
Java == vs equals() Method: Understanding Reference vs Logical Equality
More Relevant Posts
-
In Part 4 of Magnus Smith’s Functional Optics for Modern Java series, he explores traversals and pattern rewrites. Learn how the Focus DSL’s TraversalPath makes navigating and composing collections in Java more readable, fluent, and powerful. 🔗 Read more: https://buff.ly/DszWTCN #Java #FunctionalProgramming #DSL #SoftwareEngineering #CodeOptimisation #TechInsights
To view or add a comment, sign in
-
📌 synchronized Keyword in Java The synchronized keyword is used to control access to shared resources in a multithreaded environment. 1️⃣ What synchronized Does • Allows only one thread at a time • Protects critical sections of code • Prevents race conditions 2️⃣ Synchronized Methods When a method is synchronized: • The thread acquires the object’s lock • Other threads must wait Example: synchronized void update() { // critical section } 3️⃣ Synchronized Blocks Provides finer control by locking only a specific section of code. Example: synchronized (this) { // critical section } 4️⃣ Object-Level Lock • Each object has one intrinsic lock • Only one thread can hold it at a time • Applies to instance-level synchronization 5️⃣ Class-Level Lock • Achieved using synchronized static methods • Lock is held on the Class object 6️⃣ Performance Consideration • Synchronization adds overhead • Overuse can reduce concurrency • Use only where necessary 🧠 Key Takeaway synchronized ensures thread safety by enforcing mutual exclusion. Use it carefully to balance correctness and performance. #Java #Multithreading #Concurrency #ThreadSafety #CoreJava
To view or add a comment, sign in
-
A stream in java is a sequence of objects, its just a way to get data out of a collection. Collection interface in java has the stream method so all collections support stream. Arrays dont have a stream method we can make a stream out of an array by using Arrays util class's stream static method. Stream is used to process data from a collection in a declarative way much like we do chaining of array methods in JS/TS. We can have finite or infinite streams. #Java #Backend #SoftwareEngineering
To view or add a comment, sign in
-
𝗦𝘁𝗿𝗶𝗻𝗴𝗕𝘂𝗶𝗹𝗱𝗲𝗿 𝘃𝘀 𝗦𝘁𝗿𝗶𝗻𝗴𝗕𝘂𝗳𝗳𝗲𝗿 𝗶𝗻 𝗝𝗮𝘃𝗮 — 𝗪𝗵𝗮𝘁’𝘀 𝘁𝗵𝗲 𝗗𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲? When working with strings in Java, performance and thread safety matter. That’s where StringBuilder and StringBuffer come in. ✅ StringBuilder - Faster performance - Not thread-safe - Best for single-threaded environments ✅ StringBuffer - Thread-safe (synchronized) - Slightly slower due to synchronization - Best for multi-threaded applications 💡 Both are mutable, unlike String — which means they can modify content without creating new objects, making them memory-efficient for heavy string operations. 👉 Use StringBuilder for speed, and StringBuffer when thread safety is required. #Java #StringBuilder #StringBuffer #JavaProgramming #CoreJava #ProgrammingConcepts #JavaInterview #DeveloperTips #Coding #SoftwareDevelopment
To view or add a comment, sign in
-
#Coding10 👉 Q: Remove Duplicates from a Sorted Array (Two Pointer Technique – Java). Example: int[] arr = {1, 1, 2, 2, 3, 4, 4}; Output → {1, 2, 3, 4} Count → 4 ✅ Two Pointer Technique (Optimal – O(n), O(1)) static int removeDuplicates(int[] arr) { if(arr.length == 0) return 0; int j = 1; // pointer for next unique position for(int i = 1; i < arr.length; i++) { if(arr[i] != arr[i - 1]) { arr[j] = arr[i]; j++; } } return j; // number of unique elements } How It Works Since the array is already sorted, duplicates are adjacent i scans the array j tracks the position to place the next unique element When a new element is found → place it at index j Complexity Analysis • Time Complexity → O(n) • Space Complexity → O(1) (In-place solution) Two-pointer pattern is extremely powerful for array problems. #DSA #Java #Arrays #TwoPointers #ProblemSolving #InterviewPrep #LearningInPublic #LinkedInDSA
To view or add a comment, sign in
-
In Java, Strings are immutable, meaning once a String object is created, its value cannot be changed. This design choice brings multiple benefits 👇 🔐 Security Strings store sensitive data like passwords, file paths, and URLs. Immutability prevents accidental or malicious modification. 🔁 Thread Safety Since Strings don’t change, they can be shared across multiple threads without synchronization issues. 🚀 Performance & Memory Efficiency Java uses the String Constant Pool to reuse String objects. Immutability allows safe sharing, reducing memory usage. 🗂 Reliable HashMap Keys Strings are commonly used as keys in HashMap. Their immutability ensures a consistent hashcode and faster lookups. 🧩 Predictable & Reliable Code No unexpected changes mean easier debugging, maintenance, and more stable applications. ✨ That’s why String immutability is a smart and powerful design decision in Java. #Java #CoreJava #JavaDeveloper #Programming #SoftwareEngineering #LearnJava
To view or add a comment, sign in
-
-
Java☕ — Garbage Collection♻️ Earlier, I thought GC was magic. Objects disappear… somehow. Then I learned the basics of how JVM actually cleans memory. Key idea that clicked for me 👇 GC removes objects that are no longer reachable. 📝JVM divides heap into: ✅Young Generation (Eden, Survivor) ✅Old Generation New objects → Young Gen Long-living objects → Old Gen #Java_Code User u = new User(); u = null; // eligible for GC 📝Important realization: You don’t control GC — you design code to help it. 📝Good GC behavior comes from: ✅Fewer unnecessary objects ✅Short object lifetimes ✅Clearing references when done Java isn’t leaking memory. Bad references are. #Java #GarbageCollection #JVM #MemoryManagement
To view or add a comment, sign in
-
-
💻 Memory Leak in Java – A Silent Performance Killer Memory leaks in Java don’t happen because GC fails — they happen because objects are still strongly referenced and never become eligible for garbage collection. 🔎 What happens? Heap memory keeps increasing → Full GC runs → Memory doesn’t drop → Eventually leads to OutOfMemoryError. ⚠️ Common Causes: ✔ Static collections holding objects ✔ Unclosed DB connections / streams ✔ ThreadLocal not removed ✔ Unbounded caches ✔ Listeners not deregistered 🛠 How to Identify: ✅ Monitor heap using JConsole / VisualVM ✅ Take heap dump using jmap ✅ Analyze in Eclipse MAT → Check Dominator Tree & GC Roots 💡 Remember: Garbage Collector removes unused objects — But it cannot remove objects you are still referencing. Performance is not just about writing code. It’s about writing memory-efficient code. #Java #MemoryLeak #GarbageCollection #JavaDeveloper #BackendDevelopment #InterviewPreparation 🚀
To view or add a comment, sign in
-
-
🚀 Container With Most Water | Java | Two Pointer Approach I solved the “Container With Most Water” problem using an optimized Two Pointer technique in Java. The goal is to find two lines that together with the x-axis form a container, such that the container holds the maximum amount of water. 🧠 Approach: Start with two pointers at both ends of the array. Calculate the width between them. The height is determined by the smaller of the two values. Update the maximum area. Move the pointer pointing to the smaller height inward. This greedy strategy works because the area depends on both width and minimum height, and moving the smaller height gives a chance to find a larger area. ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) Practicing DSA problems daily to improve logical thinking and optimization skills. #Java #DSA #TwoPointer #ProblemSolving #CodingJourney #LeetCode #DataStructures
To view or add a comment, sign in
-
-
📝 Day 16/30 – LeetCode #15 (3Sum) | Java This problem extends the two-sum pattern and introduces duplicate handling as the main challenge. A brute-force approach would require checking all triplets, resulting in O(n³) time complexity. By sorting the array and fixing one element, I applied a two-pointer approach on the remaining part of the array. Careful duplicate skipping ensured unique triplets while maintaining efficiency. This optimized the solution to O(n²) time. This problem reinforced how sorting combined with pointer logic can drastically reduce complexity. #LeetCode #Java #DSA #TwoPointers #Arrays #ProblemSolving #Consistency #LearningInPublic
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