🔥 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
Akshay Kumar Muthyala’s Post
More Relevant Posts
-
🧠 Java Interview Question 👉 How to find duplicate characters in a String? Example: Input: "programming" Output: g, r, m Simple approach using HashMap: import java.util.HashMap; public class DuplicateCharacter { public static void main(String[] args) { String str = "programming"; HashMap<Character, Integer> map = new HashMap<>(); for (char c : str.toCharArray()) { map.put(c, map.getOrDefault(c, 0) + 1); } for (char c : map.keySet()) { if (map.get(c) > 1) { System.out.println(c); } } } } 💡 Logic: Count frequency of each character and print duplicates. 👉 Have you solved this in a different way? #Java #SpringBoot #Coding #InterviewQuestions #BackendDeveloper
To view or add a comment, sign in
-
🚀 Java Basic That Many Ignore: What is String[] args in main()? 🤔 We write this every day: public static void main(String[] args) { System.out.println("Hello"); } 👉 But what exactly is args? 💡 args = Command Line Arguments It is an array of Strings passed when running your program 👉 Example: public class Test { public static void main(String[] args) { System.out.println(args[0]); } } Run this: java Test Hello 👉 Output: Hello 🤯 Important Points: args is just a variable name (you can change it) It is always an array of String It can be empty (no arguments passed) 🔥 Fun Fact: public static void main(String[] xyz) 👉 This also works! 😄 ⚠️ Be careful: System.out.println(args[0]); ❌ If no argument → ArrayIndexOutOfBoundsException 💡 Safe way: if (args.length > 0) { System.out.println(args[0]); } Small concept… but important for interviews & real-world usage 💪 #Java #Programming #Coding #JavaDeveloper #InterviewPrep #Developers
To view or add a comment, sign in
-
Interview Question: What happens inside the JVM when you create a String in Java? When a String is created in Java, the JVM handles memory allocation and storage differently depending on how the String is defined. 🔹 Case 1: Using String Literal String s1 = "Hello"; String s2 = "Hello"; 👉 Here’s what happens: JVM checks the String Constant Pool If "Hello" already exists → it reuses the same object No new object is created for s2 👉 Both s1 and s2 point to the same memory location 🔹 Case 2: Using new Keyword String s3 = new String("Hello"); 👉 Here’s what happens: JVM creates a new object in heap memory It also ensures "Hello" exists in the String Pool So now there are two objects: One in Heap One in String Pool 🔹 Case 3: Using intern() String s4 = new String("Hello").intern(); 👉 What happens: JVM returns the reference from the String Pool Avoids duplicate objects Main Points To Remember: String literals are stored in the String Constant Pool new String() always creates a new object in heap The String Pool optimizes memory by reusing values intern() ensures reference from the pool #Java #JVM #InterviewQuestions #Programming #BackendDevelopment
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
-
🚀 Can you find the first non-repeating character in a string? Here’s a simple Java approach 👇 String str = "aabbcd"; for(int i = 0; i < str.length(); i++) { boolean unique = true; for(int j = 0; j < str.length(); j++) { if(i != j && str.charAt(i) == str.charAt(j)) { unique = false; break; } } if(unique) { System.out.println(str.charAt(i)); break; } } 💡 Output: c 🔍 How it works: For each character, we check if it appears anywhere else in the string If it appears → not unique ❌ If it does NOT appear → first non-repeating character ✅ 👉 Time Complexity: O(n²) 💭 Interview Insight: This question is commonly asked to test your understanding of: ✔ Strings ✔ Nested loops ✔ Logic building 📌 Bonus: Can you optimize this to O(n) using HashMap? 👀 Drop your approach in comments 👇 #Java #Coding #DSA #InterviewPrep #Developers #100DaysOfCode
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
-
☕ Java Interview Question 📌 When is ArrayStoreException thrown? ArrayStoreException occurs when you try to store an incompatible data type in an array. 🔹 Why it happens: ✔ Arrays in Java are type-safe at runtime ✔ Storing a different object type than the array’s actual type triggers this exception 🔹 Example Scenario: ✔ Assigning an Integer into an array declared as Double[] ✔ The compiler may allow it (due to polymorphism), but it fails at runtime 🔹 Key Insight: ✔ Happens during runtime, not compile time ✔ Common in cases involving inheritance and object arrays 💡 In Short: ArrayStoreException ensures type safety by preventing invalid object assignments in arrays 🚀 👉For Java Course Details Visit : https://lnkd.in/gwBnvJPR . #Java #CoreJava #ExceptionHandling #Programming #InterviewPreparation #TechLearning #AshokIT
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
-
🚀 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
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
Explore related topics
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