🧠 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
Find Duplicate Characters in Java String
More Relevant Posts
-
🔥 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 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
-
☕ 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
-
-
💡 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
-
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 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
-
-
🚀 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 🔹 👉 Why is 100% abstraction possible using an Interface but not with an Abstract Class? 📖 Answer: 👉 Interface: An interface contains only method declarations (no implementation). It defines what to do, not how to do it. ✔ Therefore, it provides 100% abstraction (conceptually). 👉 Abstract Class: An abstract class can contain: ✔ Abstract methods (without body) ✔ Concrete methods (with implementation) Because it includes some implementation, it provides only partial abstraction, not 100%. 🔧 Example: interface A { void show(); // no implementation } abstract class B { abstract void display(); // abstract method void print() { // implemented method System.out.println("Hello"); } } 🎯 Conclusion: ✔ Interface → Only method declarations → 100% abstraction ✔ Abstract Class → Declarations + implementation → Partial abstraction 💡 Note: From Java 8 onwards, interfaces can have default and static methods. So technically, they are not purely 100% abstract, but conceptually they are still used to achieve abstraction. #Java #OOP #InterviewPreparation #Programming #AutomationTesting #Learning
To view or add a comment, sign in
-
-
Interview Question: What is Autoboxing and Unboxing in Java? Autoboxing and Unboxing are concepts in Java that handle the conversion between primitive data types and their corresponding wrapper classes. Autoboxing is the automatic conversion of a primitive type into its wrapper object. Unboxing is the reverse process, where a wrapper object is converted back into a primitive type. Example: int a = 10; // Autoboxing Integer obj = a; // Unboxing int b = obj; System.out.println(a + " " + obj + " " + b); 👉 Here, Java automatically converts: int → Integer (Autoboxing) Integer → int (Unboxing) Usage in Collections: import java.util.ArrayList; ArrayList<Integer> list = new ArrayList<>(); list.add(10); // Autoboxing int value = list.get(0); // Unboxing 👉 Collections store objects, so autoboxing makes it seamless to use primitives. ⚠️ Important Edge Case: Integer obj = null; int x = obj; // Throws NullPointerException 👉 During unboxing, if the wrapper object is null, it results in a runtime error. #Java #InterviewQuestions #Programming #BackendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
☕ Java Interview Question 📌 What is the difference between Checked Exception and Unchecked Exception? 🔹 Checked Exception ✔ Checked at compile time ✔ Must be handled using try-catch or declared with throws ✔ Usually occurs due to external conditions beyond program control Examples: • IOException • SQLException • InterruptedException 🔹 Unchecked Exception ✔ Occurs at runtime ✔ Not mandatory to handle at compile time ✔ Usually caused by programming mistakes or invalid logic Examples: • NullPointerException • ArrayIndexOutOfBoundsException • ArithmeticException 💡 In Short: Checked exceptions are verified by the compiler, while unchecked exceptions occur during program execution ⚡ 👉For Java Course Details Visit : https://lnkd.in/gwBnvJPR . #Java #CoreJava #Exceptions #CheckedException #UncheckedException #InterviewPreparation #JavaDeveloper #TechLearning #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