📘 Follow me for daily Java, Spring Boot, SQL & System Design MCQs to crack MNC interviews 🚀 🧠 Java Interview MCQ — Day 6 Topic: Java Collections Q1. Output of List with duplicates List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("A"); System.out.println(list.size()); Answer: C) 3 Why: ArrayList allows duplicate elements and preserves insertion order. You added 3 items, so size is 3. Q2. Which collection does NOT allow duplicate elements? Answer: C) HashSet Why: HashSet follows Set rules. Set never allows duplicate values. Q3. Method used to sort a List in Java Answer: B) Collections.sort() Why: Collections.sort() sorts a List in natural order or using a Comparator. Q4. Default initial capacity of ArrayList Answer: C) 10 Why: When ArrayList resizes for the first time, it creates capacity of 10. Q5. Which interface is implemented by ArrayList? Answer: C) List Why: ArrayList implements the List interface. Q6. What happens if you add null into HashSet? Answer: B) Only one null allowed Why: HashSet allows a single null value because duplicates are not allowed. Q7. Which class maintains insertion order? Answer: C) LinkedHashSet Why: LinkedHashSet maintains insertion order using a linked list and hash table. Q8. Which of the following is NOT synchronized? Answer: C) ArrayList Why: ArrayList is not thread-safe. Vector, Hashtable, and Stack are synchronized. Q9. Which method removes an element by index in ArrayList? Answer: B) remove() Why: remove(int index) method removes element by index. Q10. Which collection is best for key–value pairs? Answer: C) Map Why: Map is designed for key and value mapping like HashMap, TreeMap, LinkedHashMap. ✅ Concept Summary List → allows duplicates, ordered Set → no duplicates Map → key/value pairs ArrayList → not synchronized, allows duplicates HashSet → one null, no duplicates LinkedHashSet → maintains insertion order #Java #SpringBoot #FullStackDeveloper
Java Collections MCQs for MNC Interviews
More Relevant Posts
-
🎯 Preparing for Java Interviews? Here’s a Must-Know Concept! 💡 Copy Constructor vs Cloneable in Java – Key Differences While working with object copying in Java, I explored two important approaches: Copy Constructors and the Cloneable interface. Here’s a quick breakdown 👇 🔹 Copy Constructor A copy constructor is a constructor that creates a new object using another object of the same class. ✅ Defined explicitly by the developer ✅ Offers full control over how objects are copied ✅ Can implement deep copy or shallow copy based on requirement ✅ Safer and more flexible approach Example: class Student { int id; String name; Student(Student s) { this.id = s.id; this.name = s.name; } } 🔹 Cloneable Interface Java provides the Cloneable interface along with the clone() method (from Object class) to create object copies. ⚠️ Requires implementing Cloneable and overriding clone() ⚠️ By default performs shallow copy ⚠️ Can throw CloneNotSupportedException ⚠️ Less control and considered somewhat outdated in modern Java Example: class Student implements Cloneable { int id; String name; public Object clone() throws CloneNotSupportedException { return super.clone(); } } 🔍 Key Differences ✔️ Copy Constructor → Manual, flexible, readable ✔️ Cloneable → Built-in, but less safe and harder to manage 🚀 Conclusion In modern Java development, copy constructors are generally preferred over cloning because they provide better control, clarity, and maintainability. #Java #Programming #OOP #InterviewPreparation #Developers #CodingInterview #SoftwareEngineering
To view or add a comment, sign in
-
MOST DEVELOPERS KNOW JAVA BASICS. BUT ADVANCED JAVA QUESTIONS ARE WHAT ACTUALLY DECIDE INTERVIEWS. Here are 25 advanced Java questions you should be ready for: 1) How does JVM memory model work (Heap vs Stack vs Metaspace)? 2) What happens internally during garbage collection? 3) How does G1 GC differ from other GC algorithms? 4) What is the difference between strong, weak, and soft references? 5) How does HashMap work internally in Java 8+? 6) What happens when hash collisions increase in HashMap? 7) Difference between ConcurrentHashMap and HashMap? 8) How does thread synchronization work internally? 9) What is the difference between synchronized and ReentrantLock? 10) What is thread starvation and how does it happen? 11) What is deadlock and how can you prevent it? 12) What is the Java Memory Model (JMM)? 13) What is the role of volatile keyword? 14) What is happens-before relationship? 15) How does ExecutorService work internally? 16) Difference between Runnable and Callable? 17) What is ForkJoinPool and when to use it? 18) How do parallel streams work internally? 19) What is classloader in Java and how does it work? 20) What is reflection and its use cases? 21) What is serialization and its drawbacks? 22) What are memory leaks in Java and how do they occur? 23) What is the difference between fail-fast and fail-safe iterators? 24) What is immutable object and why is it important? 25) How does Java handle exceptions internally? If you can explain these clearly, you’re already at a strong level for backend interviews. I’ll share the detailed PDF link with interested folks.
To view or add a comment, sign in
-
🚀 Java Interview Series – Day 8 Checked vs Unchecked Exceptions in Java? Exception handling is a critical part of writing robust applications. In Java, exceptions are broadly classified into two types: 🔹 Checked Exceptions (Compile-time) • Checked at compile time • Must be handled using try-catch or throws • Examples: IOException, SQLException 🔹 Unchecked Exceptions (Runtime) • Occur at runtime • Not mandatory to handle • Usually caused by programming errors • Examples: NullPointerException, ArrayIndexOutOfBoundsException Why does this matter? ✔ Helps build fault-tolerant applications ✔ Encourages proper error handling ✔ Improves system reliability 💡 Example: File handling → requires handling checked exceptions Accessing a null object → leads to unchecked exception ⚡ Key Insight: Checked exceptions force you to handle predictable issues (like IO failures), while unchecked exceptions highlight bugs that should be fixed in code. 💬 Interview Tip: Always mention: Compile-time vs Runtime Mandatory handling Real-world examples A good developer doesn’t just write code—they handle failures gracefully. Mastering exceptions is a big step toward writing production-ready Java applications. #Java #JavaDeveloper #ExceptionHandling #CheckedException #RuntimeException #SoftwareEngineering #BackendDevelopment #CodingInterview #TechInterview #CleanCode #Developers #LearningInPublic #CareerGrowth #IndiaJobs #USJobs #UKJobs #AustraliaJobs
To view or add a comment, sign in
-
-
🚀 Day 3 of Java Series 👉 Find common elements between two lists using Streams import java.util.*; import java.util.stream.*; public class CommonElementsExample { public static void main(String[] args) { List<Integer> list1 = List.of(10, 20, 30, 40, 50); List<Integer> list2 = List.of(30, 40, 60, 70); Set<Integer> set2 = new HashSet<>(list2); List<Integer> common = list1.stream() .filter(set2::contains) .toList(); System.out.println(common); // [30, 40] } } 💡 What’s happening here? ✔ Convert one list into a HashSet → O(1) lookup ✔ Stream through list1 ✔ Filter only elements present in list2 ✔ Collect result into a list ⚡ Key Insight: Using List.contains() leads to O(n²) complexity Using HashSet reduces it to O(n + m) 🧠 Interview Tip: Always optimize lookups using HashSet when dealing with search operations 📌 Output: [30, 40] ❓Can you think of a way to handle duplicates in both lists? #Java #Streams #CodingInterview #Developers #JavaDeveloper #Learning #Tech
To view or add a comment, sign in
-
🧠 Java MCQ – Answer Explanation Question Recap Java List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("A"); System.out.println(list.size()); Correct Answer: C) 3 ✅ Step-by-Step Explanation List in Java allows duplicate elements. ArrayList implements the List interface. When elements are added to an ArrayList, they are stored in insertion order. There is no restriction on adding the same value multiple times. ▶ Execution Flow list.add("A"); → List becomes: ["A"] list.add("B"); → List becomes: ["A", "B"] list.add("A"); → List becomes: ["A", "B", "A"] Even though "A" is added twice, it is accepted. 📌 Final Point list.size() returns the total number of elements present, including duplicates. So, total elements = 3 Output: 3 💡 Key Concept to Remember List → allows duplicates Set → does NOT allow duplicates ArrayList → preserves insertion order size() → counts all elements including duplicates #JavaMCQ #CodingMCQ #InterviewPreparation #MNCInterview #CodeAnalysis #ConceptClarity #JavaLearning #ServletJSP #JDBC #OracleDB #DeveloperMindset #PracticeCoding
To view or add a comment, sign in
-
-
☕ Java Interview Question 📌 Explain the LinkedList class in Java In Java, LinkedList is a collection class that stores elements using a doubly linked list structure. 🔹 Key Features ✔ Maintains insertion order ✔ Allows duplicate elements ✔ Non-synchronized by default 🔹 Implementation ✔ Implements List and Deque interfaces ✔ Can be used as a list, queue, or stack 🔹 Performance ✔ Fast insertion and deletion in the middle ✔ Slower random access compared to ArrayList 🔹 Syntax • LinkedList<Type> list = new LinkedList<>(); 💡 In Short: LinkedList is best when frequent insertions and deletions are needed instead of fast indexing 🚀☕ 👉For JAVA Course Details Visit : https://lnkd.in/gwBnvJPR . #Java #LinkedList #JavaInterview #Collections #Programming #InterviewPreparation #TechSkills
To view or add a comment, sign in
-
-
🚀 Java Interview Question of the Day! 💡 What is a Map Interface in Java? 🔹 The Map Interface in Java is part of the java.util package and is used to store data in key-value pairs. 👉 Each key is unique, and it maps to a specific value — making it perfect for fast data retrieval. ⚙️ Commonly used methods: ✔️ containsKey() – checks if a key exists ✔️ containsValue() – checks if a value exists 📌 Popular implementations of Map: 🔸 HashMap – Fast, no order guarantee 🔸 LinkedHashMap – Maintains insertion order 🔸 TreeMap – Sorted keys (natural ordering) 🔸 SortedMap – Interface for sorted maps 🎯 Understanding Map is essential for handling real-world data like caching, configurations, and database-like structures. 🔥 Master core Java concepts to crack your next interview! 💬 Which Map implementation do you use the most? Let’s discuss in the comments! 👉For Java Course Details Visit : https://lnkd.in/gwBnvJPR . #Java #JavaInterviewQuestions #CoreJava #Programming #SoftwareDeveloper #CodingInterview #LearnJava #BackendDeveloper #JobReady #InterviewPreparation #AshokIT
To view or add a comment, sign in
-
-
🚀 Java 11 Features You Must Know for Interviews Java 11 is an LTS version, so it’s heavily used in production systems — and frequently asked in interviews. Here are the most important Java 11 features 👇 ⸻ ✅ 1. var in Lambda Parameters Use var for cleaner syntax and when applying annotations in lambdas. ⸻ ✅ 2. New String Methods * isBlank() * lines() * strip() (Unicode-aware) * repeat(n) 👉 Interview favorite: strip() vs trim() ⸻ ✅ 3. Files API Enhancements * Files.readString() * Files.writeString() 👉 Cleaner file handling with less boilerplate. ⸻ ✅ 4. HTTP Client (Standardized) * Supports HTTP/2 * Async calls using CompletableFuture 👉 Replaces older, less flexible HTTP libraries. ⸻ ✅ 5. Collection to Array Improvement * list.toArray(String[]::new) 👉 Type-safe and concise. ⸻ ✅ 6. Run Java Without Compilation java HelloWorld.java 👉 Great for quick scripts and demos. ⸻ ✅ 7. Optional Enhancements * isEmpty() 👉 Cleaner than !isPresent() ⸻ ✅ 8. Removed Java EE & CORBA Modules 👉 Important for migration-related questions. ⸻ 🎯 Interview Tip: Don’t just list features. Be ready to explain real use cases — especially for: * String APIs * Optional * HTTP Client * Files API ⸻ 💬 Which Java version are you currently using in your project? ⸻ #Java #Java11 #SpringBoot #BackendDevelopment #InterviewPreparation #Microservices #SoftwareEngineering
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 Series – Day 23 Abstract Class vs Interface in Java? This is one of the most commonly asked Java interview questions—and also one of the most misunderstood. Let’s break it down clearly 👇 🔹 Abstract Class • Can have both abstract and concrete methods • Supports state (instance variables) • Allows constructors • Used when classes share a common base with some default behavior 🔹 Interface • Defines a contract (what to do, not how) • Supports multiple inheritance • Methods are abstract by default (Java 8+ allows default/static methods) • No instance variables (only constants) Why does this matter? ✔ Helps you choose the right design approach ✔ Impacts flexibility and scalability ✔ Core concept in system design interviews 💡 When to use what? • Use Abstract Class → when you want shared code + base functionality • Use Interface → when you want flexibility and multiple implementations ⚡ Key Insight: In modern Java and frameworks like Spring, interfaces are preferred because they promote loose coupling and better testability. 💬 Interview Tip: Don’t just list differences—explain: When to use each Real-world examples Why interfaces are often preferred in scalable systems Choosing between abstract class and interface is not just syntax—it’s a design decision that affects your entire system architecture. #Java #JavaDeveloper #OOP #Interface #AbstractClass #SoftwareEngineering #BackendDevelopment #SystemDesign #CleanCode #TechInterview #CodingInterview #Developers #LearningInPublic #CareerGrowth #IndiaJobs #USJobs #UKJobs #AustraliaJobs
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
📌 The key clue to the correct answer is already mentioned above the question.