💡 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
Java Immutable Strings and Reassignment
More Relevant Posts
-
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 question on Memory Leaks — here's everything you need to know! Had a great technical interview recently where Memory Leaks came up as a deep-dive topic. Here's a concise breakdown that I think every Java developer should know 🔍 What is a Memory Leak in Java? A memory leak happens when objects are no longer needed by the application, but the Garbage Collector (GC) cannot reclaim them — because references still exist. The JVM keeps them in heap, and over time, this causes OutOfMemoryError. ⚠️ Common Causes 1. Static fields holding object references 2. Unclosed resources (streams, connections, sessions) 3. Listeners / callbacks never removed 4. Inner classes holding implicit reference to outer class 5. ThreadLocal variables not cleaned up 6. Caches without eviction policies 🛠️ How to Detect It 1. JVisualVM / JConsole — monitor heap usage over time 2. Eclipse MAT (Memory Analyzer Tool) — analyze heap dumps 3. YourKit / JProfiler — commercial profilers, powerful for production 4. verbose:gc JVM flag — observe GC behavior 5. Heap dumps with jmap -dump:live,format=b,file=heap.hprof <pid> ✅ How to Fix / Prevent It 1. Use WeakReference / SoftReference for caches 2. Always close resources with try-with-resources 3. Remove listeners when done 4. Avoid unnecessary static references 5. Use tools like Caffeine / Guava Cache with TTL/max-size 6. Review ThreadLocal.remove() usage in thread pools Memory leaks are silent killers in production. If you're preparing for Java interviews — bookmark this. Drop a comment if you've faced memory leak issues in production. Let's learn together! 🙌 #Java #JavaDeveloper #MemoryLeak #JVM #PerformanceTuning #JavaInterview #SoftwareEngineering #Programming #TechInterview #BackendDevelopment #ProductionIssue #Interview #MemoryLeaks #Spring
To view or add a comment, sign in
-
Interesting Java Interview Question Recently, an interviewer asked a very logical question: Why does Hashtable not allow null key or null value in Java? At first it sounds simple, but the logic behind it is interesting. In Hashtable, when we retrieve a value using get(key), the method returns null in two situations: 1. The key does not exist in the table 2. The key exists but its value is null If Hashtable allowed null values, the system would not be able to distinguish between these two cases. This ambiguity could create logical issues, especially since Hashtable is a synchronized (thread safe) collection. To avoid this confusion, the designers of Java decided that Hashtable will not allow null keys or null values. Example: import java.util.Hashtable; public class Demo { public static void main(String[] args) { Hashtable<String,String> table = new Hashtable<>(); table.put("A","Java"); // valid table.put("B",null); // throws NullPointerException } } In contrast, HashMap allows one null key and multiple null values, because it handles key existence checks differently. Interview questions like this really test how deeply we understand Java Collections internally, not just how to use them. #Java #JavaInterview #JavaCollections #Hashtable #HashMap #Learning #javaJob
To view or add a comment, sign in
-
🔥 Day 8: equals() vs == in Java (Very Important Interview Topic) This is one of the most commonly asked Java interview questions — and also one of the most misunderstood! 👇 🔹 == (Double Equals) Compares memory/reference location Checks if two objects point to the same memory String a = new String("Java"); String b = new String("Java"); System.out.println(a == b); // false ❌ 🔹 equals() Method Compares actual content (values) Defined inside Object class (can be overridden) String a = new String("Java"); String b = new String("Java"); System.out.println(a.equals(b)); // true ✅ 🔹 String Special Case (String Pool) String x = "Hello"; String y = "Hello"; System.out.println(x == y); // true ✅ 👉 Because both refer to same object in String Pool 💡 Pro Tip: Always use equals() for comparing object values — especially Strings! 📌 Final Thought: "== checks if objects are the same, equals() checks if values are the same." #Java #Programming #Coding #JavaDeveloper #InterviewPrep #Tech #Learning #Day8 #JavaBasics
To view or add a comment, sign in
-
-
💡 Java Interview Question - String Immutability What will be the output? String s = "hello"; s.concat(" world"); System.out.println(s); Output: hello Why? Strings in Java are immutable. The concat() method creates a new String object instead of modifying the existing one. In this case, the result of concat() is not assigned back, so the original value remains unchanged. Correct approach: s = s.concat(" world"); Takeaway: If you don’t assign the result of a String operation, the change is lost. #Java #InterviewPrep #Programming
To view or add a comment, sign in
-
🚀 Java Interview Trap: Why "finally" Can Hide Exceptions 🤯 This is a dangerous one that many developers miss Example: public class Test { public static void main(String[] args) { try { throw new RuntimeException("Error in try"); } finally { throw new RuntimeException("Error in finally"); } } } 👉 Output: Exception in thread "main" java.lang.RuntimeException: Error in finally 🤔Where did the original exception go? 💡 What’s happening? - Exception thrown in try ❌ - finally block executes - New exception in finally overrides the original 👉 Original exception is LOST 😱 🔥 Why this is dangerous? - You lose actual root cause - Debugging becomes very hard - Production issues become confusing ✅ Better Approach: try { throw new RuntimeException("Error in try"); } catch (Exception e) { throw e; // preserve original } finally { System.out.println("Cleanup done"); } ⚠️ Interview Twist: try { return 10; } finally { throw new RuntimeException("Oops"); } 👉 Method will NOT return 10 ❌ 👉 Exception will be thrown instead 😳 💥 Golden Rule: ❌ Never throw exceptions from finally ❌ Avoid return in finally ✅ Use it only for cleanup 🎯 Pro Tip: Use try-with-resources instead of complex finally blocks #Java #JavaInterview #CodingInterview #Developers #Programming #TechTips
To view or add a comment, sign in
-
💡 Java Interview Question How do you find the common elements from three lists in Java? Here’s a simple example: ✅ Two approaches: Using retainAll() with Set Using Java 8 Streams public class CommonElementFrom3List { public static void main(String[] args){ List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5); List<Integer> list2 = Arrays.asList(3, 4, 5, 6, 7); List<Integer> list3 = Arrays.asList(5, 6, 7, 8, 3); Set<Integer> common = new HashSet<>(list1); common.retainAll(list2); common.retainAll(list3); System.out.println(common); List<Integer> list = list1.stream() .filter(list2::contains) .filter(list3::contains) .distinct() .collect(Collectors.toList()); System.out.println(list); } } 📌 Output: [3, 5] ❓ Question for you: Which approach would you prefer in a real-world scenario and why? Also, how would you handle duplicate elements efficiently? #Java #CodingInterview #JavaDeveloper #Programming #TechLearning
To view or add a comment, sign in
-
🚀 Most Asked Core Java Interview Questions (Part 2) Continuing from Part 1 — more frequently asked questions 👇 🔹 Multithreading Questions Thread vs Process What happens if you call run() instead of start()? What if you don’t override run()? Thread lifecycle Class level lock vs Object level lock Race condition (with example) Deadlock (with example) Runnable vs Callable ThreadLocal wait vs sleep notify vs notifyAll yield, join Why wait/notify/notifyAll present in Object class? 🔹 Concurrency & Advanced Synchronization ReentrantLock Semaphore CyclicBarrier CompletableFuture vs Future ThreadPoolExecutor (internal working) FixedThreadPool vs CachedThreadPool BlockingQueue 🔹 Coding Questions (Threads) Print even/odd using two threads Producer-Consumer problem Print numbers (0–N) using 3 threads (mod 3) Print ABCABC using 3 threads 🔹 Collections ArrayList vs LinkedList HashMap internal working HashSet vs LinkedHashSet ConcurrentHashMap vs HashMap ConcurrentHashMap vs Hashtable TreeMap vs TreeSet Comparable vs Comparator Iterator vs ListIterator vs Enumeration ConcurrentModificationException Default size of ArrayList 🔹 Advanced Collections Immutable Map WeakHashMap vs IdentityHashMap HashSet internal working If a class has ArrayList, how to make it immutable 🔹 Design Singleton class Double locking How to break Singleton 💡 Save this for revision — these are highly repeated interview questions 🔥 #Java #CoreJava #Multithreading #Collections #InterviewPreparation
To view or add a comment, sign in
-
🔥 Top Java Multithreading Interview Questions 🔥 (This topic decides backend selection) 1️⃣ What is a Thread in Java? A thread is a lightweight unit of execution inside a process. 👉 Multiple threads allow concurrent tasks. 2️⃣ Difference between Process and Thread Process → heavy, separate memory Thread → lightweight, shared memory 👉 Common starter question. 3️⃣ How do you create a thread in Java? By extending Thread class OR Implementing Runnable interface 👉 Runnable is preferred. 4️⃣ What is synchronization? It controls access to shared resources. 👉 Prevents data inconsistency in multithreaded apps. 5️⃣ What is a deadlock? When two or more threads wait forever for each other. 👉 Interviewers love real-life examples here. 6️⃣ What is volatile keyword? Ensures visibility of variable changes across threads. 👉 Does not guarantee atomicity. 7️⃣ What is Thread Pool? A group of reusable threads. 👉 Improves performance and resource management. 8️⃣ Difference between wait() and sleep() wait() releases lock sleep() does not release lock 👉 Very common trap question. 9️⃣ What is Callable vs Runnable? Callable returns result and can throw exception. Runnable cannot return value. 🔟 Why use Executor Framework? Manages thread creation and execution efficiently. 👉 Better than creating threads manually. 💡 Multithreading questions test concurrency thinking, not syntax. 💪 One goal – SELECTION 👉 Tap ❤️ for more
To view or add a comment, sign in
-
This Java code looks fine… but crashes 👇 List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); for (String s : list) { if (s.equals("A")) { list.remove(s); } } 💥 Throws: "ConcurrentModificationException" Why? You can't modify a list while iterating using a for-each loop. ✅ Fix: Use "Iterator" Iterator<String> it = list.iterator(); while (it.hasNext()) { if (it.next().equals("A")) { it.remove(); } } Classic interview question 🔥 #Java #Collections #BugFix
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