A comprehensive repository of basic and advanced programming questions solved using the Java language. This collection is designed to showcase my problem-solving skills and mastery of core Java concepts, from fundamental data types to advanced Object-Oriented Programming.
Solutions for all the questions listed below can be found within the Module_1 directory of this repository.
- Write a program to demonstrate encapsulation in Java.
- Create a program showing the use of inheritance and polymorphism.
- Explain and implement the concept of abstraction in Java using interfaces.
- Write a program to demonstrate method overloading and method overriding.
- Create a class hierarchy for animals that demonstrates polymorphism.
- Develop a program to implement multiple inheritance using interfaces.
- Write a Java program to showcase the use of
thisandsuperkeywords. - Demonstrate the concept of constructors in OOP with a program.
- Explain and implement the concept of access modifiers in Java.
- Show an example of the
finalkeyword for variables, methods, and classes. - Write a program that uses Java's
StringBuilderfor efficient string operations. - Write a program to demonstrate the immutability of the
Stringclass.
- Write a program to declare variables of all primitive data types in Java and print their default values.
- Implement a program to demonstrate the use of
if-else,switch, andforloops. - Write a program to check if a number is prime using a
whileloop. - Create a program to calculate the factorial of a number using recursion.
- Write a program to identify valid and invalid identifiers in Java.
- Write a program to find the largest and smallest numbers in an array.
- Write a program to check if a given number is odd or even.
- Write a program to find the largest of three numbers entered by the user.
- Write a program to calculate the factorial of a given number using recursion.
- Write a program to check if a given string or number is a palindrome.
- Write a program to generate the first n terms of the Fibonacci series.
- Write a program to check whether a given number is prime.
- Write a program to find the sum of all elements in an array.
- Implement a program to reverse the elements of an array.
- Write a Java program to perform matrix addition and multiplication.
- Create a program to sort an array using the bubble sort algorithm.
- Write a program to demonstrate a 2D array and print its elements.
- Write a program to search for an element in a sorted array using the binary search algorithm.
- Write a program to remove duplicate elements from an array.
- Write a program to demonstrate the use of arithmetic, relational, and logical operators.
- Create a program to show the difference between
==andequals()for string comparison. - Write a program to illustrate the use of the ternary operator.
- Implement a program to perform bitwise operations in Java.
- Write a program to demonstrate operator precedence in Java.
- Write a program to create a class with multiple constructors (constructor overloading).
- Implement a program to demonstrate the use of a copy constructor in Java.
- Create a program that initializes class fields using a parameterized constructor.
- Write a program to demonstrate the use of
staticandnon-staticmethods. - Implement a singleton class in Java.
- Write a program to demonstrate multilevel inheritance in Java.
- Create a program to show method overriding and the use of
superto call the parent class method. - Implement an abstract class and override its methods in a subclass.
- Write a program to demonstrate
finalclasses and methods. - Create a program to show run-time polymorphism using dynamic method dispatch.
- Write a program to reverse a string without using built-in methods.
- Implement a program to count the frequency of characters in a string.
- Write a program to demonstrate the immutability of the
Stringclass. - Create a program to check if a given string is a palindrome.
- Implement a program to split a string into words and print each word on a new line.
- Create a Java package
utilitiesthat contains a classMathUtilswith a methodadd(int a, int b)to return the sum of two numbers. Demonstrate the use of this package in another class. - Define a package
shapescontaining an interfaceShapewith methodsdouble area()anddouble perimeter(). Implement the interface in classesCircleandRectangle. - Write a program to import classes from
java.utiland useArrayListto store and display a list of integers.
- Define a functional interface
Calculatorwith a methodint compute(int a, int b). Use a lambda expression to provide implementation for addition, subtraction, and multiplication. - Write a Java program to sort a list of strings in descending order using a lambda expression.
- Implement a method reference in a program to find the square of a number using a static method.
- Write a program that demonstrates the difference between
try-catchandtry-catch-finallyblocks by dividing two numbers and handlingArithmeticException. - Create a custom exception
InvalidAgeExceptionthat is thrown when a user's age is less than 18. Write a program to demonstrate its use.
- Create a custom exception
InvalidAgeExceptionthat is thrown when a user's age is less than 18. Handle the exception and log the error to a file usingjava.util.logging. - Demonstrate the use of
throwandthrowskeywords in a program that calculates the factorial of a number. Throw an exception if the input number is negative.
- Synchronized Method: Create a Java program where two threads try to update the same bank account balance. Use synchronization to ensure the balance is updated correctly and avoid race conditions.
- Synchronized Block: Modify the above program (bank account example) to use a synchronized block instead of a synchronized method.
- Thread Deadlock: Write a program that simulates a deadlock condition. Create two threads that attempt to lock two different resources and cause a deadlock.
- Using wait(), notify(), and notifyAll(): Implement a producer-consumer scenario where one thread (producer) produces data and another thread (consumer) consumes it. Use the wait() and notify() methods for synchronization.
- Stopping a Thread: Write a program that safely stops a thread using a flag. The thread should print numbers from 1 to 100, and the program should be able to stop the thread by setting the flag to false.
- Write a program that reads a text file using the FileInputStream and prints the contents to the console.
- Create a program that writes a string into a file using the FileOutputStream. Ensure that the program writes the string "Java I/O Streams Example" to a file named output.txt.
- Read string and integer values from the command prompt and process them using I/O streams.
- Write a program that demonstrates the use of Math.random(), Math.abs(), and Math.pow() from the java.lang package.
- Regular Expressions: Create a program that uses the Pattern and Matcher classes from the java.util.regex package to check if a given string is a valid email address.
- Create a thread by extending the Thread class that prints even numbers from 2 to 20 with a 500ms delay between each number.
- Create a thread by implementing the Runnable interface that takes a string "MULTITHREADING" and prints its characters in reverse order one by one.
- Thread Sleep Method: Create a program that creates two threads. The first thread should print "Thread 1" every 1 second, and the second thread should print "Thread 2" every 2 seconds.
- Countdown Timer: One thread prints a countdown from 10 to 1 (1-second delay), while another thread simultaneously prints "Tick..." every half a second.
- Thread Naming and Priority: Create three threads — "Worker-1", "Worker-2", and "Worker-3". Assign different priorities and print their execution order.
- Daemon Threads: Write a Java program where a daemon thread continuously prints "Auto-Save in progress..." every 3 seconds while the main thread performs file processing.
- Synchronized Method: Ticket booking system where multiple users (threads) attempt to book tickets simultaneously. Use synchronization to prevent overselling.
- Synchronized Block: Inventory management system where multiple threads decrease stock count. Use synchronized blocks for safe stock updates.
- Deadlock Example: Simulate a Dining Philosophers problem where two philosophers try to pick up chopsticks (resources) and create a deadlock.
- Using wait() and notify():
- Producer-consumer synchronization example.
- Two threads print numbers from 1–20 alternately (odd/even) using wait() and notify().
- Stopping a Thread: Simulate a file download that prints "Downloading chunk X" and stops gracefully when a stop flag is set to false.
- Use the ReentrantLock class to create a safe counter incremented by multiple threads. Compare results with a non-locked version.
- Create two threads acquiring two locks (lock1 and lock2) in opposite order to cause a deadlock. Then fix it using tryLock() with a timeout.
- Byte Stream: Read a file using FileInputStream and print its contents.
- Byte Stream Write: Write "Java I/O Streams Example" to output.txt using FileOutputStream.
- Character Stream Read: Read a file using FileReader and print its contents.
- Character Stream Write: Write a string to example.txt using FileWriter.
- Buffered I/O: Improve performance using BufferedReader and BufferedWriter.
- File Existence Check: Verify if a file exists. If not, create it using the File class.
- List All Files: List all files in a user-specified directory.
- Copy File: Copy the contents of one file to another using FileInputStream and FileOutputStream.
- Delete File: Delete a file using the File class.
- Random Access File: Use RandomAccessFile to write and read specific positions in a file.
- java.lang Package: Demonstrate Math.random(), Math.abs(), and Math.pow().
- java.util Package: Use Date and Calendar to display the current date and time.
- java.util.regex Package: Validate an email using Pattern and Matcher.
- Create a user-defined generic class Box with methods addItem(T item) and getItem(). Demonstrate its usage with String and Integer types.
- Write a generic method swapElements that swaps two elements in an array. Demonstrate its usage with different data types.
- Write a program to iterate over a List of integers using: a. A simple for loop b. An enhanced for loop c. A while loop with an Iterator
- Create a List of strings and perform the following operations: a. Add elements to the list. b. Remove an element by value and index. c. Replace an element at a specific index. d. Print the list after each operation.
- Write a program to sort an ArrayList of strings alphabetically and reverse alphabetically.
- Write a program to sort a list of custom objects (e.g., Student with name and marks) using a Comparator.
- Find the Maximum Product Subarray: Given an integer array nums, find the contiguous subarray (containing at least one number) with the largest product. Example: a. Input: nums = [2,3,-2,4] b. Output: 6 (subarray [2,3])
- Reverse a Linked List Write a function to reverse a singly linked list in place. Example: 1 → 2 → 3 → 4 → 4 → 3 → 2 → 1
- Write a program to demonstrate the use of TreeMap for sorting keys.
- Write a program to create a HashMap of employee IDs and names. Perform the following operations: a. Add new key-value pairs. b. Check if a key exists. c. Iterate through the map using: d. KeySet e. EntrySet
- Write a program to demonstrate the sorted order of keys in TreeMap by adding unsorted key-value pairs.
- Write a program to show the difference between HashMap and LinkedHashMap in terms of iteration order
- What is the purpose of generics in Java, and how do they improve type safety and code reusability?
- Explain the syntax for creating a user-defined generic class in Java. Provide an example.
- How do bounded type parameters work in generics? Write a generic class that accepts only subclasses of Number.
- What is the difference between ? extends T and ? super T in generics? Provide an example of when to use each.
- How do raw types differ from parameterized types in generics, and why should raw types be avoided?
- Write a generic class Pair<K, V> that holds two values of any types, K and V. Include methods to get and set the values.
- Create a user-defined generic class Box with methods addItem(T item) and getItem(). Demonstrate its usage with String and Integer types.
- Write a generic method swapElements that swaps two elements in an array. Demonstrate its usage with different data types.
- Develop a user-defined generic class Stack that provides standard stack operations like push(T item), pop(), and peek(). Demonstrate with integers and strings.
- Implement a generic class MinMaxFinder<T extends Comparable> that provides methods findMin() and findMax() to find the minimum and maximum elements in a list. Demonstrate it with a list of integers and strings.
- What is the java.util package, and why is it essential in Java programming?
- What are the key features of the Collection Framework in java.util?
- Explain the differences between Collection and Collections in java.util.
- What is the role of the Iterator interface in the java.util package?
- What is the purpose of the Comparator and Comparable interfaces in the java.util package?
- What are the key interfaces in the Java Collection Framework, and how are they related?
- What is the difference between Collection and Map interfaces in Java?
- Explain the differences between Set, List, and Queue in the Collection Framework.
- What is the significance of the Iterable interface, and how is it used in the Collection Framework?
- What are the benefits of using the Collection Framework over arrays?
- Write a program to iterate over a List of integers using: a. A simple for loop b. An enhanced for loop c. A while loop with an Iterator
- Write a generic method to print all elements of any Collection (e.g., List, Set, Queue).
- What is the List interface, and how does it differ from the Set interface?
- What is the difference between ArrayList and LinkedList in terms of performance and usage?
- Write a program to demonstrate the use of ArrayList for storing and iterating over elements.
- What is the role of the Vector class, and how does it differ from ArrayList?
- How is the Stack class implemented, and how does it relate to the List interface?
- Create a List of strings and perform the following operations: a. Add elements to the list. b. Remove an element by value and index. c. Replace an element at a specific index. d. Print the list after each operation.
- Write a program to compare the performance of ArrayList and LinkedList for: a. Adding elements at the beginning. b. Removing elements from the middle. c. Iterating through the list.
- Write a program to sort an ArrayList of strings alphabetically and reverse alphabetically.
- What is the Set interface, and how is it different from List?
- What is the difference between HashSet, LinkedHashSet, and TreeSet in Java?
- Write a program to demonstrate the use of TreeSet for storing sorted elements.
- How does HashSet handle duplicate elements? Explain with an example.
- What is the significance of equals() and hashCode() methods in HashSet?
- Write a program to demonstrate the uniqueness property of HashSet by attempting to add duplicate elements.
- Create a TreeSet of integers and perform the following operations: a. Add elements to the set. b. Find the smallest and largest elements. c. Remove a specific element.
- Write a program to iterate over a LinkedHashSet and explain its order-preserving property.
- What is the Map interface in Java, and how is it different from Collection?
- What is the difference between HashMap, LinkedHashMap, and TreeMap?
- How does HashMap handle collisions?
- Write a program to demonstrate the use of TreeMap for sorting keys.
- What is the difference between Hashtable and HashMap? Why is Hashtable considered legacy?
- Write a program to create a HashMap of employee IDs and names. Perform the following operations: a. Add new key-value pairs. b. Check if a key exists. c. Iterate through the map using: i. KeySet ii. EntrySet
- Write a program to demonstrate the sorted order of keys in TreeMap by adding unsorted key-value pairs.
- Write a program to show the difference between HashMap and LinkedHashMap in terms of iteration order.
- Implement a simple program using Queue (with LinkedList) to simulate a ticket booking system.
- Use a PriorityQueue to store a list of tasks with priorities. Add tasks, remove the highest-priority task, and print the queue.
- Write a program to implement a Stack using the Stack class. Perform operations like push, pop, peek, and check if it is empty.
- Implement a deque using the ArrayDeque class. Perform operations like: a. Add elements at both ends. b. Remove elements from both ends. c. Peek at both ends.
- Write a program to check if a string is a palindrome using a Deque.
- What is the purpose of the PriorityQueue class in Java?
- How is the Deque interface different from the Queue interface?
- What is the difference between BlockingQueue and PriorityQueue?
- Write a program to implement a simple Queue using the LinkedList class.
- What is the role of WeakHashMap in Java, and how is it different from HashMap?
- How is Vector different from ArrayList in terms of thread safety?
- Write a program to demonstrate the thread-safe nature of Vector by adding elements to it from multiple threads.
- What is the role of ConcurrentHashMap in Java, and how does it achieve thread safety?
- Create a ConcurrentHashMap and demonstrate how it handles concurrent modifications.
- What are the differences between CopyOnWriteArrayList and ArrayList?
- Write a program using CopyOnWriteArrayList to iterate and modify a list safely in a multithreaded environment.
- What is the difference between synchronizedCollection and ConcurrentHashMap?
- What are some commonly used methods in the Collections utility class?
- Write a program to shuffle and sort an ArrayList using methods from the Collections class.
- How can you make a collection thread-safe using the Collections class?
- Create an unmodifiable List using Collections.unmodifiableList() and show what happens when you try to modify it.
- Write a program to perform a binary search on a List using the Collections.binarySearch() method.
- Write a program to find the frequency of elements in a list using Collections.frequency().
- Write a program to sort a list of custom objects (e.g., Student with name and marks) using a Comparator.
- Write a program to sort a Map by its values using a custom Comparator.
- Create a class LruCache<K, V> using LinkedHashMap to implement an LRU (Least Recently Used) cache.
- Implement a basic to-do list application using ArrayList to store tasks. Add functionality to add, remove, and display tasks.
- Write a program to count the frequency of characters in a string using a HashMap.
- Create a program to store students’ grades in a TreeMap, with student names as keys and grades as values. Allow adding, removing, and querying grades.
- Write a program to merge two PriorityQueue objects and sort the resulting queue.
- Create a generic MultiMap<K, V> class that stores multiple values for a single key using a HashMap<K, List>.
- Write a program to implement a simple banking system using Map to store customer IDs and their account balances.
- Use a WeakHashMap to demonstrate how entries are garbage-collected when keys are no longer strongly referenced.
- Create a program to implement a book catalog system using HashMap, where book titles are the keys and author names are the values. Allow searching by title.
- Write a program to store a list of products and their prices in a TreeMap and display the products in sorted order by name.