📌 Difference Between == and .equals() in Java If you're preparing for a Java interview, this question will definitely come: It sounds basic. But many developers still get it wrong. 🔎 == Operator == compares references (memory addresses) when used with objects. Example: String s1 = new String("Java"); String s2 = new String("Java"); System.out.println(s1 == s2); 👉 Output: false Because: - Two different objects in heap - Different memory locations 🔎 .equals() Method .equals() compares content (value), not memory address. System.out.println(s1.equals(s2)); 👉 Output: true Because: Both contain the same text "Java" ⚠️ Important Clarification For primitive types: int a = 10; int b = 10; System.out.println(a == b); int a = 10; int b = 10; System.out.println(a == b); Here == compares actual values → true .equals() is not used for primitives. 🔥 Real-World Impact - Using == instead of .equals() can cause: - Subtle bugs - Wrong business logic - Failed comparisons in collections #Java #InterviewPreparation #SoftwareEngineering #JavaDeveloper #Programming
Java == vs equals() Method
More Relevant Posts
-
📌 Java Collection Framework – Complete Interview Revision Notes This document provides concise and structured notes covering the Java Collection Framework, core interfaces, implementations, internal working, performance, and real-time usage scenarios. What this document covers: • Collection Framework Overview Core interfaces: List, Set, Map java.util package structure Collection hierarchy fundamentals • List Implementations ArrayList (Dynamic array, O(1) access, 50% growth) LinkedList (Doubly linked list, fast insert/delete) Stack (LIFO, extends Vector, synchronized) ArrayList vs LinkedList vs Vector comparisons • Set Implementations HashSet (HashMap-based, O(1), no order) LinkedHashSet (Maintains insertion order) TreeSet (Sorted, Red-Black Tree, O(log n)) Internal working using hashCode() and equals() • Queue & Deque Queue (FIFO, add/poll/peek methods) PriorityQueue (Min-Heap, O(log n), Comparator support) ArrayDeque (Faster than Stack & LinkedList for queue/stack ops) ArrayDeque vs LinkedList comparison • Map Interface Key-value structure (unique keys) HashMap, LinkedHashMap, TreeMap, Hashtable, ConcurrentHashMap Important methods: put(), get(), remove(), entrySet() Map.Entry usage for iteration • Performance & Complexity O(1) vs O(log n) vs O(n) operations Internal structures: Dynamic Array, Doubly Linked List, HashMap, TreeMap (Red-Black Tree), Binary Heap I’ll continue sharing high-value interview and reference content. 🔗 Follow me: https://lnkd.in/gAJ9-6w3 — Aravind Kumar Bysani #Java #JavaCollections #DataStructures #HashMap #ArrayList #LinkedList #TreeSet #PriorityQueue #CoreJava #InterviewPreparation
To view or add a comment, sign in
-
💡 Java Interview Question – Immutable Strings Trap What will be the output? String s = "Java"; s.replace("J", "K"); System.out.println(s); 🤔 Options: A) Kava B) Java C) Compilation Error D) Runtime Exception --- ✅ Correct Answer: B) Java --- 🔍 Explanation: In Java, String is immutable. That means once a String object is created, it cannot be modified. 👉 The "replace()" method does not change the original string, it returns a new modified string. But here’s the catch 👇 s.replace("J", "K"); We are not assigning the result back to "s", so the original value remains unchanged. --- 💡 Correct way to modify: s = s.replace("J", "K"); System.out.println(s); // Output: Kava --- 🚀 Key Takeaway: Always remember: 👉 Strings in Java are immutable → Reassignment is required for changes --- #Java #JavaInterview #Coding #BackendDevelopment #Programming #InterviewPrep
To view or add a comment, sign in
-
🚨 Java Mystery That Breaks Your Brain 🧠💥 What will be the output of this code? public class Mystery { public static void main(String[] args) { Integer a = 100; Integer b = 100; Integer c = 200; Integer d = 200; System.out.println(a == b); System.out.println(c == d); } } Think carefully… it’s not as simple as it looks 👀 👇 👇 👇 Output: true false Wait… what? Same values but different results😵💫? Here’s the catch 👇 Java caches Integer values only in the range -128 to 127. So when you write: Integer a = 100; Integer b = 100; Both variables actually point to the same object in memory → that’s why it returns true. But when you write: Integer c = 200; Integer d = 200; These values are outside the cache range, so Java creates two different objects → that’s why it returns false. The real trap here is: 👉 == compares references (memory location) 👉 .equals() compares actual values This small difference can easily confuse you in interviews or even in real projects. Pro tip: Avoid using == with wrapper classes unless you clearly understand what’s happening behind the scenes. Did you get it right? Be honest 👇 And share this with someone preparing for Java interviews 😉 #Java #CodingChallenge #InterviewPrep #Developers #Programming #Tech
To view or add a comment, sign in
-
-
🚨 Java Interview Trap Can the 'main()' method be "overloaded" in Java? Most developers quickly answer No. The `main()` method is just another static method, so Java allows method overloading. Example: public class Test { public static void main(String[] args) { System.out.println("Original main"); main(10); } public static void main(int x) { System.out.println("Overloaded main with int: " + x); } } Output: Original main Overloaded main with int: 10 However, there is an important rule. The JVM only looks for one specific entry point: public static void main(String[] args) Or public static void main(String... args) So even though main() can be overloaded, the JVM will only start execution from the standard signature. Any other overloaded main() must be called manually from inside the program. Sometimes the most basic Java method still hides the best interview traps. #Java #JavaInterview #JVM #SoftwareEngineering #Developers #Programming
To view or add a comment, sign in
-
📌 150+ Java Interview Questions – Complete Core Java Revision This post provides structured, interview-focused coverage of Core Java concepts including OOPS, JVM architecture, collections, exceptions, strings, keywords, and real-time coding scenarios. Some of the most commonly asked… What this document covers: • Java Basics What is Java? JDK vs JRE vs JVM Features of Java Java vs JavaScript • OOPS Concepts Class vs Object Inheritance & super keyword Polymorphism Encapsulation Abstraction (Abstract class & Interface) Method Overloading vs Overriding • Constructors & Keywords Default vs Parameterized constructor static, final, finally, finalize this & super usage instanceof operator • Access Modifiers public, private, protected, default Purpose & scope control • Collections & Data Structures Array vs ArrayList HashMap, HashSet put(), get(), remove(), entrySet() Iterator interface • Exception Handling try, catch, finally throw vs throws Checked vs Unchecked exceptions try-with-resources • Strings & Memory String immutability String vs StringBuilder vs StringBuffer equals(), hashCode(), toString() I’ll continue sharing high-value interview and reference content. 🔗 Follow me: https://lnkd.in/gAJ9-6w3 — Aravind Kumar Bysani #Java #CoreJava #JavaInterview #OOPS #Collections #ExceptionHandling #JVM #InterviewPreparation #JavaDeveloper
To view or add a comment, sign in
-
🚨 Java Interview Trap 2 Why is "Vector" rarely used in modern Java? Many developers quickly answer: “Because it’s outdated.” But the real reason is more interesting 👇 Vector was introduced in JDK 1.0, even before the Collections Framework existed. It behaves like a dynamic array and internally stores elements using an array. Some key facts: • Default capacity = 10 • Capacity usually doubles when full • All methods are synchronized • This makes Vector thread-safe by default Example: import java.util.Vector; public class Test { public static void main(String[] args) { Vector<Integer> numbers = new Vector<>(); numbers.add(10); numbers.add(20); numbers.add(30); System.out.println(numbers); } } Because every method is synchronized, multiple threads can safely modify a Vector. But there is a trade-off. Synchronization introduces performance overhead, especially in single-threaded applications. That’s why most modern Java applications prefer: • ArrayList • Collections.synchronizedList() • CopyOnWriteArrayList But here is the real interview question 👇 When the internal array inside a Vector becomes full, Java creates a new array with double the size and copies all elements into it. What do you think happens to the old array? 1️⃣ It stays in memory 2️⃣ It gets reused 3️⃣ It becomes eligible for GC Drop the correct answer in the comments 👇 Sometimes the oldest Java classes still hide the best interview traps. #Java #JavaInterview #Collections #JVM #SoftwareEngineering #Developers #Programming
To view or add a comment, sign in
-
Interview Question: What is the Diamond Problem in Java? The Diamond Problem arises in languages that support multiple inheritance, where a class inherits from two classes that both derive from a common superclass. This creates ambiguity when both parent classes define the same method. The question becomes: which method should be used? Java avoids this issue by not supporting multiple inheritance with classes. However, with interfaces and default methods, a similar situation can occur. Example: interface A { default void show() { System.out.println("A"); } } interface B { default void show() { System.out.println("B"); } } class Test implements A, B { public static void main(String[] args){ Test t = new Test(); t.show(); // Compilation error! } } Since both interfaces provide the same method, Java forces the class to override it explicitly. Solution with Specific Interface Call: class Test implements A, B { public void show() { A.super.show(); // calling method from interface A B.super.show(); // calling method from interface B } } 👉 This way, we can explicitly choose or combine behavior from both interfaces. #Java #OOP #InterviewQuestions #BackendDevelopment #Programming
To view or add a comment, sign in
-
-
📌 If You're Preparing for a Java Interview, This Question Will Definitely Come What is the internal working of HashMap? Almost every Java developer has used HashMap. But surprisingly, many developers use it daily without understanding how it actually works internally. Let’s break it down simply. 🧠 What is HashMap? HashMap stores data in key-value pairs. Example: Map<String, Integer> map = new HashMap<>(); map.put("Java", 1); map.put("Python", 2); But the real magic happens behind the scenes. ⚙️ How HashMap Works Internally When you insert a key-value pair: map.put(key, value); Java performs these steps: 1️⃣ Hash Code Calculation The key’s hashCode() method is called. hash = key.hashCode() This hash determines where the data should be stored. 2️⃣ Bucket Index Calculation The hash is converted to an array index (bucket) index = hash % capacity This decides which bucket the entry will go to. 3️⃣ Collision Handling Two keys can produce the same bucket index. This is called a hash collision. HashMap handles this using: - Linked List (before Java 8) - Red-Black Tree (Java 8+) when entries exceed threshold This improves performance significantly. 4️⃣ Retrieval When you call: map.get(key); Java again: - Calculates the hash - Finds the correct bucket - Traverses the list/tree to find the key ⚡ Time Complexity Average case:O(1) Worst case:O(log n) (after Java 8 tree conversion) #Java #HashMap #SoftwareEngineering #JavaDeveloper #InterviewPreparation
To view or add a comment, sign in
-
-
Abstraction Java for Newbies#11 Post is live:- 💼 Crack the Interview — Abstraction 1. What is abstraction in Java? Abstraction is the process of exposing only essential behavior while hiding implementation details. 2. Why is abstraction important? It manages complexity and allows systems to evolve safely. 3. How is abstraction achieved in Java? Using interfaces and abstract classes. 4. What is the difference between abstraction and encapsulation? Encapsulation protects data; abstraction controls what behavior is visible. 5. Give a real-world Java example of abstraction. The List interface — users rely on its contract without knowing internal implementations. Strong Interview Line: Abstraction lets us depend on guarantees, not on algorithms. Read the complete post here https://lnkd.in/g5ezvder 📩 Subscribe me :- nitinsingh717.substack.com ♻ Repost to help others in their learning journey. 👤 Follow me here for more. — Nitin Singh
To view or add a comment, sign in
-
-
Many Java developers don't know this simple trick in Java 8. Find the first non-repeated character in a String using Streams. Example String: "aabbcddeff" Solution in Java 8: String result = str.chars() .mapToObj(c -> (char) c) .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting())) .entrySet() .stream() .filter(e -> e.getValue() == 1) .map(Map.Entry::getKey) .findFirst() .orElse(null); Output → c Java 8 Streams can make complex logic very clean and readable. If you are preparing for Java interviews, this question is asked very often. Follow for more Java and Spring Boot interview content #java #springboot #javadeveloper #backenddeveloper #softwareengineer
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
👉 Use == for primitives 👉 Use .equals() for objects And always understand what you're comparing — reference or value.