Java Interview Tip: s1 == s2 vs s1.equals(s2) Many Java developers get confused between == and .equals() when comparing strings. Here’s the simple difference 🔹 s1 == s2 Checks reference equality. It verifies whether both variables point to the same object in memory. String s1 = new String("Hello"); String s2 = new String("Hello"); System.out.println(s1 == s2); // false Even though the values look the same, Java created two different objects. 🔹 s1.equals(s2) Checks value equality. It compares the actual content of the strings. System.out.println(s1.equals(s2)); // true A small concept, but a very common Java interview question. What will be the output? String str1 = "Java"; String str2 = "Ja" + "va"; System.out.println(str1 == str2); 📊 Your answer? A️. true B️. false C️. Compilation error D️. Depends on JVM Let’s see who gets it right! #Java #Programming #JavaDeveloper #CodingInterview #SoftwareDevelopment
Java String Comparison: == vs equals()
More Relevant Posts
-
💡 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 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
-
A simple Java interview question 👇 class Main { public static void main(String[] args) { String name = "Hello"; String b = new String("Hello"); String c = name; String d = b; System.out.println(name == b); System.out.println(name == c); } } I was asked this in an interview and it’s a perfect example of how fundamentals matter more than complexity. Most people expect both outputs to be true. But the actual result is: false true 💡 Why? Because in Java: 🔹 "Hello" is stored in the String Pool (optimized memory) 🔹 new String("Hello") creates a new object in Heap 🔹 c = name → same reference 🔹 d = b → same reference ⚡ The key insight: == compares memory reference, not content 👉 name == b → false (different objects) 👉 name == c → true (same object) If you actually want to compare values: name.equals(b); // true 📌 What this question really tests: Not syntax. Not memorization. But your understanding of how Java handles memory. #Java #CodingInterview #SoftwareEngineering #Programming #Developers #TechCareers
To view or add a comment, sign in
-
🚨 Java Interview Trick: Why 127 == 127 is TRUE but 200 == 200 is FALSE? 🤯 Today I explored an interesting behavior in Java related to Integer caching and object comparison. Consider this code: Integer a = 127; Integer b = 127; Integer x = 200; Integer y = 200; if(a == b) System.out.println(a + " And " + b + " are equal"); if(x == y) System.out.println(x + " And " + y + " are equal"); else System.out.println(x + " And " + y + " are not equal"); 🔍 Output 127 And 127 are equal 200 And 200 are not equal 💡 Why does this happen? Java internally maintains an Integer Cache for values between -128 to 127. ✔ When we write: Integer a = 127; Integer b = 127; Both variables point to the same cached object, so a == b returns true. ❌ But when we write: Integer x = 200; Integer y = 200; Java creates two separate objects in the heap, so x == y returns false. ⚠ Important Interview Tip == compares object references, not values. To compare values correctly, always use: x.equals(y) 📚 Key Takeaway Understanding Integer caching, object references, and equality comparison is crucial for mastering Java fundamentals and solving tricky interview questions. #Java #JavaDeveloper #JavaConcepts #Programming #CodingInterview #SoftwareEngineering #LearnJava
To view or add a comment, sign in
-
-
A simple Java interview question… that isn’t so simple 👇 class Main { public static void main(String[] args) { String name = "Srishti"; String b = new String("Srishti"); String c = name; String d = b; System.out.println(name == b); System.out.println(name == c); } } I was asked this in an interview and it’s a perfect example of how fundamentals matter more than complexity. Most people expect both outputs to be true. But the actual result is: false true 💡 Why? Because in Java: 🔹 "Srishti" is stored in the String Pool (optimized memory) 🔹 new String("Srishti") creates a new object in Heap 🔹 c = name → same reference 🔹 d = b → same reference ⚡ The key insight: == compares memory reference, not content 👉 name == b → false (different objects) 👉 name == c → true (same object) If you actually want to compare values: name.equals(b); // true 📌 What this question really tests: Not syntax. Not memorization. But your understanding of how Java handles memory. #Java #CodingInterview #SoftwareEngineering #Programming #Developers #TechCareers
To view or add a comment, sign in
-
🚀 30 Days of Java Interview Questions – Day 14 💡 Question: What is the Java Collections Framework? 🔹 What is Java Collections Framework? Java Collections Framework (JCF) is a set of classes and interfaces used to store and manipulate groups of data efficiently. 🔹 Main Interfaces List • Allows duplicates • Maintains insertion order • Examples: ArrayList, LinkedList Set • No duplicates allowed • Unordered (HashSet) / Ordered (TreeSet) Queue • Follows FIFO (First In First Out) • Used in scheduling and buffering Map • Stores key-value pairs • Keys are unique • Examples: HashMap, TreeMap 🔹 Example ```java id="f8k2la" import java.util.*; public class Test { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); System.out.println(list); } } ``` Output: [Apple, Banana] ⚡ Quick Summary • List → ordered, allows duplicates • Set → no duplicates • Queue → FIFO structure • Map → key-value storage 📌 Interview Tip Always choose the right collection based on: • Performance • Ordering requirement • Duplicate handling Follow this series for 30 Days of Java Interview Questions. Tomorrow: Day 15 #java #javadeveloper #codinginterview #backenddeveloper #softwareengineer #programming #developers #tech
To view or add a comment, sign in
-
-
In a recent Java backend interview, I was asked something simple… but interesting. "Where does the String Constant Pool live in memory?" And that question led to a deeper discussion around several Java fundamentals. Some of the questions that came up were: 1️⃣ What exactly does @ComponentScan do in Spring? When we use Spring Boot, the container scans packages to automatically detect beans like: @Service @Repository @Component @Controller This is how Spring’s IoC container discovers and manages objects. 2️⃣ What is a Functional Interface in Java 8? A functional interface is an interface with exactly one abstract method. Example: @FunctionalInterface interface Calculator { int add(int a, int b); } This allows usage with Lambda expressions. 3️⃣ Why were default and static methods added to interfaces? Before Java 8, adding a new method to an interface would break all implementations. Default methods allow backward compatibility by providing a default implementation. 4️⃣ When we call list.stream(), what exactly is happening? The stream() method converts a collection into a Stream pipeline that allows functional-style operations like: filter map reduce It enables more readable and parallelizable data processing. 5️⃣ Where does the String Constant Pool reside? String literals are stored in the **String Constant Pool**, which is located inside the **Heap memory** in modern JVMs. This helps reuse immutable strings and reduce memory usage. Sometimes interviews remind us that strong fundamentals matter more than frameworks. What’s one Java concept that confused you early in your career? #Java #SpringBoot #BackendDevelopment #JavaInterview #SoftwareEngineering #JVM #BhargavKancherla #javainterview #interview
To view or add a comment, sign in
-
-
🚀 Java Streams Interview Gem: Find Duplicate Numbers in a List Working with collections is common, but identifying duplicates efficiently is a must-have skill for any Java developer 💡 Here’s how you can find duplicate numbers using Java Streams 👇 🔹 Approach: We use a Set to track elements and filter duplicates while streaming the list. 🔹 Code: import java.util.*; import java.util.stream.*; public class FindDuplicates { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 2, 5, 6, 3, 7, 1); Set<Integer> seen = new HashSet<>(); Set<Integer> duplicates = numbers.stream() .filter(n -> !seen.add(n)) .collect(Collectors.toSet()); System.out.println("Duplicate Numbers: " + duplicates); } } 🔹 Output: Duplicate Numbers: [1, 2, 3] 🔹 How it works? ✔ seen.add(n) returns false if the element is already present ✔ We filter those elements → duplicates ✔ Collect them into a Set to avoid repeated duplicates 💥 Alternative (Using Grouping): 🔥 Mastering Streams = Cleaner + More Functional Code #Java #JavaStreams #CodingInterview #Developers #Programming #Tech #100DaysOfCode
To view or add a comment, sign in
-
If you're preparing for Java interviews, this is a must-know concept! 🔒 What is an Immutable Class in Java? Why & How to Create One? In Java, an Immutable Class is a class whose objects cannot be modified once they are created. 👉 The best example is the String class — once a string is created, its value cannot be changed. --- 💡 Why do we need Immutable Classes? ✔️ Thread-safe (no synchronization needed) ✔️ Secure (data cannot be changed accidentally) ✔️ Easy to cache and reuse ✔️ Predictable behavior (no side effects) --- 🛠️ How to Create an Immutable Class? Follow these 5 rules: 1. Make the class `final` (cannot be extended) 2. Make all fields `private final` 3. Do NOT provide setter methods 4. Initialize all fields through constructor 5. Return copies of mutable objects (defensive copying) --- 💻 Example: ``` final class Employee { private final String name; private final int age; public Employee(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge(){ return age; } // "Wither" pattern — returns a NEW object instead of mutating public Employee withAge(int newAge) { return new Employee(this.name, newAge); } } ``` --- 🚀 Key Takeaway: Immutable objects are simple, safe, and powerful — especially in multi-threaded applications. #Java #SpringBoot #Programming #SoftwareDevelopment #Coding #JavaDeveloper #InterviewPreparation
To view or add a comment, sign in
-
-
☕ Java Interview Question 📌 Why can’t we create a generic array in Java? In Java, generic arrays are restricted because arrays and generics handle type information differently. 🔹 Key Reason: ✔ Arrays are Reified • Arrays store and check their element type at runtime ✔ Generics use Type Erasure • Generic type information is removed during compilation ✔ Type Safety Conflict • Runtime cannot verify the actual generic type inside an array 🔹 What Problem Can Occur? • It may allow invalid assignments at runtime • Can lead to ArrayStoreException or unsafe behavior 🔹 Example: • new T[10] is not allowed because T is unknown at runtime 💡 In Short: Java prevents generic array creation to maintain type safety between compile-time generics and runtime array checks. 👉For Java Course Details Visit : https://lnkd.in/gwBnvJPR . #Java #JavaInterview #Generics #TypeErasure #Programming #InterviewPreparation #CoreJava#ashokit
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
In Java, string literals are stored in the String Pool. "Java" is placed in the string pool. "Ja" + "va" is a compile-time constant expression. The compiler optimizes it during compilation and converts it to "Java". So effectively the code becomes: String str1 = "Java"; String str2 = "Java"; Both str1 and str2 point to the same object in the String Pool. Therefore: str1 == str2 → true == compares memory references, not string content. Since both references point to the same pooled object, it returns true