Program 1:
Problem statement
Implement a java program to demonstrate creating an ArrayList, adding elements, removing
elements, sorting elements of ArrayList. Also illustrate the use of toArray() method.
1. Algorithm for the Program
Start the program.
Create a Scanner object to read input from the user.
Create an ArrayList<Integer> to store integer elements.
Ask the user to enter the number of elements n.
Use a loop from 0 to n-1:
Read an integer from the user.
Add the element to the ArrayList using add().
Display the ArrayList after adding elements.
Ask the user to enter the index of the element to remove.
Check whether the index is valid:
If valid → remove the element using remove(index).
Otherwise → display Invalid index.
Display the updated ArrayList.
Sort the elements using [Link]().
Display the sorted ArrayList.
Convert the ArrayList into an array using toArray().
Display the array elements using a loop.
Close the Scanner.
Stop the program.
2. Flowchart for the Program
//java Program
// AIM: Demonstrate ArrayList operations such as
// adding elements, removing elements, sorting,
// and converting ArrayList to an array.
package advancedJavaLabPrograms;
// Import required classes
import [Link];
import [Link];
import [Link];
public class Program1 {
public static void main(String[] args) {
// Create Scanner object to read input from user
Scanner sc = new Scanner([Link]);
// Creating an ArrayList to store Integer values
ArrayList<Integer> arrayList = new ArrayList<>();
// Ask user how many elements they want to enter
[Link]("Enter number of elements: ");
int n = [Link]();
// Reading elements from the user and adding them to ArrayList
[Link]("Enter " + n + " elements:");
for (int i = 0; i < n; i++) {
// Read integer and add it to ArrayList
[Link]([Link]());
}
// Display ArrayList after adding elements
[Link]("ArrayList after adding elements: " + arrayList);
// Ask user which index element should be removed
[Link]("Enter index to remove element: ");
int index = [Link]();
// Check if the entered index is valid
if (index >= 0 && index < [Link]()) {
// Remove element at the specified index
[Link](index);
// Display ArrayList after removing element
[Link]("ArrayList after removing element: " + arrayList);
} else {
// Display error if index is invalid
[Link]("Invalid index!");
// Sort the ArrayList elements in ascending order
[Link](arrayList);
// Display ArrayList after sorting
[Link]("ArrayList after sorting: " + arrayList);
// Convert ArrayList to an array
// toArray() method converts list elements into array
Integer[] array = [Link](new Integer[0]);
// Display the array obtained from ArrayList
[Link]("Array obtained from ArrayList using toArray(): ");
// Using for-each loop to print array elements
for (int i : array) {
[Link](i + " ");
// Close the scanner to avoid resource leak
[Link]();
Sample Output
Enter number of elements: 5
Enter 5 elements:
55
99
87
65544
ArrayList after adding elements: [55, 99, 87, 2, 65544]
Enter index to remove element: 5
Invalid index!
ArrayList after sorting: [2, 55, 87, 99, 65544]
Array obtained from ArrayList using toArray(): 2 55 87 99 65544
Program 2
Problem statement
Develop a program to read random numbers between a given range that are multiples of 2 and
5, sort the numbers according to tens place using comparator.
Important Viva Questions
Basic Questions
1. What is an ArrayList in Java?
2. What package contains the ArrayList class?
3. What is the difference between Array and ArrayList?
4. Why do we use [Link]()?
5. What does the add() method do in ArrayList?
Intermediate Questions
6. What is the return type of toArray()?
7. What happens if we try to remove an element using an invalid index?
8. Why do we use Integer instead of int in ArrayList<Integer>?
9. What is autoboxing in Java?
10. Can ArrayList store duplicate values?
Advanced Viva Questions
11. What is the difference between ArrayList and LinkedList?
12. Is ArrayList synchronized?
13. What is the time complexity of adding an element to ArrayList?
14. Can ArrayList store objects of different data types?
15. What happens internally when the ArrayList capacity becomes full?
4. Expected Viva Answers (Short)
Question Answer
What is ArrayList? A dynamic array class in Java that can grow and shrink in size.
Package of ArrayList [Link]
add() method Adds an element to the list
remove() method Removes element at specified index
[Link]() Sorts elements in ascending order
toArray() Converts list to an array
Java Program
// Program 2
// AIM: Develop a program to read random numbers between a given range
// that are multiples of 2 and 5, sort the numbers according to tens place using Comparator.
1. Algorithm for the Program
Algorithm: Sorting Numbers Based on Tens Place Using Comparator
1. Start the program.
2. Define the range of numbers:
o Lower bound = 100
o Upper bound = 1000
3. Create an ArrayList<Integer> to store numbers.
4. Create a Random object to generate random numbers.
5. Repeat the following steps 10 times:
o Generate a random number between 100 and 1000.
o Check whether the number is divisible by 2 and 5.
o If not divisible, generate another number.
o If divisible, add the number to the ArrayList.
6. Display the generated random numbers.
7. Create a Comparator class that compares numbers based on their tens place digit.
8. Sort the ArrayList using [Link]() and the comparator.
9. Display the sorted list according to the tens place.
10. Stop the program.
2. Flowchart for the Program
package advancedJavaLabPrograms;
import [Link].*;
// Comparator class to compare based on tens place
class TensPlaceComparator implements Comparator<Integer> {
@Override
public int compare(Integer num1, Integer num2) {
// Get tens place of each number
int tensPlace1 = (num1 % 100) / 10;
int tensPlace2 = (num2 % 100) / 10;
// Compare tens place
return [Link](tensPlace1, tensPlace2);
public class Program2 {
public static void main(String[] args) {
// Define range
int lowerBound = 100;
int upperBound = 1000;
// Store numbers
ArrayList<Integer> numbers = new ArrayList<>();
Random random = new Random();
// Generate 10 random numbers
for (int i = 0; i < 10; i++) {
int randomNumber;
do {
randomNumber =
[Link](upperBound - lowerBound + 1)
+ lowerBound;
} while (randomNumber % 2 != 0 || randomNumber % 5 != 0);
// ensures multiple of both 2 and 5
[Link](randomNumber);
[Link]("Random Numbers: " + numbers);
// Sort using Comparator
[Link](numbers, new TensPlaceComparator());
[Link](
"Sorted Numbers According to Tens Place: " + numbers);
Sample output
Random Numbers: [370, 980, 350, 760, 200, 530, 450, 160, 850, 350]
Sorted Numbers According to Tens Place: [200, 530, 350, 450, 850, 350, 760, 160, 370, 980]
3. Important Viva Questions
Basic Questions
1. What is a Comparator in Java?
2. Which package contains the Comparator interface?
3. What method must be implemented in a Comparator class?
4. What is the purpose of [Link]()?
5. What is the use of the Random class?
Intermediate Questions
6. How do you extract the tens digit from a number?
7. What does the expression (num % 100) / 10 mean?
8. Why do we use ArrayList<Integer> instead of ArrayList<int>?
9. What is the difference between Comparable and Comparator?
10. What does [Link]() do?
Advanced Viva Questions
11. What is the advantage of using a Comparator?
12. Can we create multiple comparators for the same class?
13. What will happen if two numbers have the same tens digit?
14. What is the time complexity of [Link]()?
15. Can we sort numbers in descending order using Comparator?
4. Short Viva Answers
Question Answer
Comparator Interface used to define custom sorting logic
Package [Link]
Method compare()
Random class Generates random numbers
(num % 100) / 10 Extracts the tens digit
[Link]() Compares two integers
Program 3
Problem statement
Implement a java program to illustrate storing user defined classes in collection.
1. Algorithm for the Program
Algorithm: Storing User-Defined Objects in an ArrayList
1. Start the program.
2. Create a Scanner object to read input from the user.
3. Create an ArrayList<Person> to store Person objects.
4. Ask the user to enter the number of persons n.
5. Repeat the following steps from i = 1 to n:
o Display message to enter details of person i.
o Read the name from the user.
o Read the age from the user.
o Create a Person object using the constructor.
o Add the object to the ArrayList using add().
6. Display the message “Contents of the ArrayList”.
7. Use a for-each loop to display each Person object stored in the list.
8. Close the Scanner object.
9. Stop the program
Flow chart
┌───────────────┐
│ START │
└──────┬────────┘
│
v
┌────────────────────────┐
│ Create Scanner object │
└─────────┬─────────────┘
│
v
┌────────────────────────────┐
│ Create ArrayList<Person> │
└─────────┬─────────────────┘
│
v
┌────────────────────────────┐
│ Enter number of persons n │
└─────────┬─────────────────┘
│
v
┌─────────────────┐
│ i=1 │
└──────┬──────────┘
│
v
┌─────────────────┐
│ Is i ≤ n ? │
└──────┬─────┬────┘
│Yes │No
v v
┌─────────────────────────────┐ ┌────────────────────────────┐
│ Enter name and age for │ │ Display "Contents of │
│ person i │ │ ArrayList" │
└────────────┬────────────────┘ └───────────┬────────────────┘
│ │
v v
┌───────────────────────────┐ ┌────────────────────────────┐
│ Create Person object │ │ Print each Person using │
│ (name, age) │ │ for-each loop │
└──────────┬────────────────┘ └───────────┬────────────────┘
│ │
v v
┌───────────────────────────┐ ┌─────────────────────────┐
│ Add Person object to list │ │ STOP │
└──────────┬────────────────┘ └─────────────────────────┘
│
v
┌────────────────┐
│ i=i+1 │
└──────┬─────────┘
│
v
(back to
"Is i ≤ n ?")
Java program
package advancedJavaLabPrograms;
Java Program
// AIM: Demonstrate storing user-defined objects in an ArrayList
// and accepting data at runtime
import [Link];
import [Link];
// Person class to store name and age
class Person {
// Private data members (Encapsulation)
private String name;
private int age;
// Constructor to initialize object values
public Person(String name, int age) {
[Link] = name;
[Link] = age;
// Getter method to return name
public String getName() {
return name;
// Getter method to return age
public int getAge() {
return age;
// Overriding toString() method
// This method is automatically called when we print the object
@Override
public String toString() {
return "Person { Name = " + name + ", Age = " + age + " }";
// Main class
public class Program3 {
public static void main(String[] args) {
// Creating Scanner object to take input from user
Scanner sc = new Scanner([Link]);
// Creating ArrayList to store Person objects
ArrayList<Person> personList = new ArrayList<>();
// Asking user how many persons to add
[Link]("Enter number of persons to add: ");
int n = [Link]();
[Link](); // clear buffer
// Loop to take user input
for (int i = 1; i <= n; i++) {
[Link]("\nEnter details for Person " + i);
// Taking name input
[Link]("Enter Name: ");
String name = [Link]();
// Taking age input
[Link]("Enter Age: ");
int age = [Link]();
[Link](); // clear buffer
// Creating Person object and adding it to ArrayList
Person p = new Person(name, age);
[Link](p);
// Displaying the contents of the ArrayList
[Link]("\nContents of the ArrayList:");
// Using for-each loop to display each object
for (Person person : personList) {
[Link](person);
// Closing scanner
[Link]();
Sample output
Enter number of persons to add: 3
Enter details for Person 1
Enter Name: Raghu M T
Enter Age: 37
Enter details for Person 2
Enter Name: Rahul
Enter Age: 28
Enter details for Person 3
Enter Name: Sachin
Enter Age: 55
Contents of the ArrayList:
Person { Name = Raghu M T, Age = 37 }
Person { Name = Rahul, Age = 28 }
Person { Name = Sachin, Age = 55 }
Important Viva Questions
Basic Questions
1. What is an ArrayList in Java?
2. Which package contains the ArrayList class?
3. What is a user-defined class?
4. What is the purpose of the constructor in the Person class?
5. Why do we use Scanner in this program?
Intermediate Questions
6. What is the advantage of using ArrayList over Array?
7. What is the purpose of the toString() method?
8. What is encapsulation in Java?
9. What does the add() method do in ArrayList?
10. What type of loop is used to display the objects?
Advanced Questions
11. Can an ArrayList store objects of user-defined classes?
12. What is the difference between ArrayList and LinkedList?
13. What happens if toString() is not overridden in the Person class?
14. What is the time complexity of adding elements to an ArrayList?
15. Can we store different object types in the same ArrayList?
4. Short Viva Answers
Question Answer
ArrayList A dynamic array that can grow and shrink at runtime
Package [Link]
Constructor Initializes object variables
Encapsulation Wrapping data and methods into a single unit
toString() Converts an object into a readable string representation
add() Adds an element or object to the list