0% found this document useful (0 votes)
27 views23 pages

Assignment2 2

The document outlines a series of Java programming assignments, each requiring the implementation of different classes and data structures, including Pair, User, Car, Student, Book, and Address. Each assignment includes specific tasks such as creating generic classes, managing collections like ArrayList and HashMap, and performing operations like sorting, searching, and removing elements. The document provides code examples and expected outputs for each assignment, demonstrating various Java concepts and data manipulation techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views23 pages

Assignment2 2

The document outlines a series of Java programming assignments, each requiring the implementation of different classes and data structures, including Pair, User, Car, Student, Book, and Address. Each assignment includes specific tasks such as creating generic classes, managing collections like ArrayList and HashMap, and performing operations like sorting, searching, and removing elements. The document provides code examples and expected outputs for each assignment, demonstrating various Java concepts and data manipulation techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Assignment-2.

2
Name-Aditya kumar Satapathy
Regd no-2341019349
Sec-2G1
Branch-B.Tech(CSE)
1. Create a generic class Pair<K, V> with private member variables key and
value. The class should include a parameterized constructor and provide
getter and setter methods for these attributes. In the main class, create
and add objects of the Pair class, then retrieve and print the key-value
pairs.
Program-package Ass22;
class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}

public V getValue() {
return value;
}
public void setKey(K key) {
this.key = key;
}

public void setValue(V value) {


this.value = value;
}
}

public class Q1 {
public static void main(String[] args) {
Pair<Integer, String> p1 = new Pair<>(1, "One");
Pair<String, Double> p2 = new Pair<>("Price", 99.99);
System.out.println("Key: " + p1.getKey() + ", Value: " + p1.getValue());
System.out.println("Key: " + p2.getKey() + ", Value: " + p2.getValue());
}
}
Output-

2. Write a Java program that includes a User class and an ArrayListUser


class. The User class should have private fields for name and age, along
with a parameterized constructor and getter/setter methods for these
attributes. The ArrayListUser class should create an ArrayList of User
objects. After adding user objects, it should retrieve and print their name
and age. Additionally, the program should sort the users based on age
and print the updated list of users using getter methods.
Program-package Ass22;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}

public int getAge() {


return age;
}
public void setName(String name) {
this.name = name;
}

public void setAge(int age) {


this.age = age;
}
}
public class Q2 {
public static void main(String[] args) {
ArrayList<User> users = new ArrayList<>();
users.add(new User("Alice", 25));
users.add(new User("Bob", 30));
users.add(new User("Charlie", 22));
System.out.println("Users before sorting:");
for (User user : users) {
System.out.println("Name: " + user.getName() + ", Age: " +
user.getAge());
}
Collections.sort(users, Comparator.comparingInt(User::getAge));
System.out.println("\nUsers after sorting by age:");
for (User user : users) {
System.out.println("Name: " + user.getName() + ", Age: " +
user.getAge());
}
}
}
Output-
3. Write a Java program that includes a Car class and a CarApp class. The Car
class should have private fields: modelNo (int), name (String), and stock
(int). Define a parameterized constructor and override the compareTo
method as public int compareTo(Car car) to enable sorting of cars based on
the total stock available.
In the CarApp class, create an ArrayList of Car objects, sort them, and print
the updated sorted list.
Example of a sorted list of Car objects:
2013 Creta 10
2020 MG 13
2018 Kia 20
2017 Audi 45
2015 BMW 55
Program-package Ass22;

import java.util.ArrayList;
import java.util.Collections;

class Car implements Comparable<Car> {


private int modelNo;
private String name;
private int stock;
public Car(int modelNo, String name, int stock) {
this.modelNo = modelNo;
this.name = name;
this.stock = stock;
}
public int getModelNo() {
return modelNo;
}

public String getName() {


return name;
}

public int getStock() {


return stock;
}
@Override
public int compareTo(Car car) {
return Integer.compare(this.stock, car.stock);
}
}

public class Q3 {
public static void main(String[] args) {
ArrayList<Car> cars = new ArrayList<>();
cars.add(new Car(2015, "BMW", 55));
cars.add(new Car(2017, "Audi", 45));
cars.add(new Car(2018, "Kia", 20));
cars.add(new Car(2020, "MG", 13));
cars.add(new Car(2013, "Creta", 10));
Collections.sort(cars);
System.out.println("Sorted list of Cars:");
for (Car car : cars) {
System.out.println(car.getModelNo() + " " + car.getName() + " " +
car.getStock());
}
}
}
Output-

4. Create a Student class with member variables name, age, and mark, along
with the necessary getter and setter methods. Implement a LinkedList of
Student objects and perform the following operations:
(a) Display the list of students. (b) Prompt the user to enter a Student object
and check its existence in the list. Specify whether the search is based on
reference comparison or content comparison using thecontains method. (c)
Remove a specified Student object from the list. (d) Count the number of
Student objects present in the list. (e) Override the equals method to compare
two Student objects based on their values rather than references.
Program-package Ass22;
import java.util.LinkedList;
import java.util.Scanner;

class Student {
private String name;
private int age;
private double mark;
public Student(String name, int age, double mark) {
this.name = name;
this.age = age;
this.mark = mark;
}
public String getName() {
return name;
}

public int getAge() {


return age;
}

public double getMark() {


return mark;
}
public void setName(String name) {
this.name = name;
}

public void setAge(int age) {


this.age = age;
}

public void setMark(double mark) {


this.mark = mark;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Student student = (Student) obj;
return age == student.age && Double.compare(student.mark, mark) == 0
&& name.equals(student.name);
}
}

public class Q4 {
public static void main(String[] args) {
LinkedList<Student> students = new LinkedList<>();
Scanner scanner = new Scanner(System.in);
students.add(new Student("Alice", 20, 85.5));
students.add(new Student("Bob", 22, 78.0));
students.add(new Student("Charlie", 21, 90.2));
System.out.println("List of Students:");
for (Student s : students) {
System.out.println(s.getName() + " " + s.getAge() + " " + s.getMark());
}
System.out.println("\nEnter student details to check existence (name, age,
mark):");
String name = scanner.next();
int age = scanner.nextInt();
double mark = scanner.nextDouble();
Student searchStudent = new Student(name, age, mark);
if (students.contains(searchStudent)) {
System.out.println("Student exists in the list (content comparison).\n");
} else {
System.out.println("Student not found.\n");
}
System.out.println("Enter student details to remove (name, age, mark):");
name = scanner.next();
age = scanner.nextInt();
mark = scanner.nextDouble();
Student removeStudent = new Student(name, age, mark);
if (students.remove(removeStudent)) {
System.out.println("Student removed successfully.\n");
} else {
System.out.println("Student not found in the list.\n");
}
System.out.println("Total number of students: " + students.size());

scanner.close();
}
}
Output-
5. Create a Book class with member variables id, name, author, and quantity to
store details of each issued book. The Book class should include a
parameterized constructor. Design a Library class that creates a HashMap of
books, where the key is an Integer (representing the book ID) and the value is a
Book object. Instantiate at least two Book objects and display the collection of
books stored in the HashMap.
Use appropriate methods of the HashMap class to perform the following
operations: (a) Check if a particular book name is present on the map. (b)
Remove a book entry by deleting the value associated with a specific key.
Program-package Ass22;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

class Book {
private int id;
private String name;
private String author;
private int quantity;
public Book(int id, String name, String author, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.quantity = quantity;
}
public int getId() {
return id;
}

public String getName() {


return name;
}

public String getAuthor() {


return author;
}

public int getQuantity() {


return quantity;
}

@Override
public String toString() {
return id + " " + name + " " + author + " " + quantity;
}
}

public class Q5 {
public static void main(String[] args) {
HashMap<Integer, Book> books = new HashMap<>();
Scanner scanner = new Scanner(System.in);
books.put(101, new Book(101, "Java Programming", "James Gosling", 10));
books.put(102, new Book(102, "Data Structures", "Robert Lafore", 5));
System.out.println("Collection of Books:");
for (Map.Entry<Integer, Book> entry : books.entrySet()) {
System.out.println(entry.getValue());
}
System.out.println("\nEnter book name to check existence:");
String bookName = scanner.nextLine();
boolean found = books.values().stream().anyMatch(book ->
book.getName().equalsIgnoreCase(bookName));
if (found) {
System.out.println("Book exists in the library.");
} else {
System.out.println("Book not found.");
}
System.out.println("\nEnter book ID to remove:");
int bookId = scanner.nextInt();
if (books.remove(bookId) != null) {
System.out.println("Book removed successfully.");
} else {
System.out.println("Book ID not found.");
}

System.out.println("\nUpdated Collection of Books:");


for (Map.Entry<Integer, Book> entry : books.entrySet()) {
System.out.println(entry.getValue());
}

scanner.close();
}
}
Output-

6. Write a program to create a TreeSet of Integer type and perform the


following operations:
(a) Display the elements of the TreeSet. (b) Prompt the user to enter a number
and check whether the number is present in the TreeSet. (c) Remove a
specified element from the TreeSet.
Program-package Ass22;
import java.util.Scanner;
import java.util.TreeSet;

public class Q6 {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
Scanner scanner = new Scanner(System.in);
numbers.add(10);
numbers.add(5);
numbers.add(20);
numbers.add(15);
numbers.add(25);
System.out.println("Elements of TreeSet: " + numbers);
System.out.println("\nEnter a number to check its existence:");
int checkNumber = scanner.nextInt();
if (numbers.contains(checkNumber)) {
System.out.println(checkNumber + " is present in the TreeSet.");
} else {
System.out.println(checkNumber + " is not found in the TreeSet.");
}
System.out.println("\nEnter a number to remove:");
int removeNumber = scanner.nextInt();
if (numbers.remove(removeNumber)) {
System.out.println(removeNumber + " removed successfully.");
} else {
System.out.println(removeNumber + " not found in the TreeSet.");
}
System.out.println("\nUpdated TreeSet: " + numbers);

scanner.close();
}
}
Output-
7. Write a Java program that includes a class Address with member variables
plotNo, at, and post. The class should define a parameterized constructor to
initialize these attributes.
Create a TreeMap, where the key is the name of a person (String), and the
value is an Address object. Insert the required key-value pairs into the TreeMap
and use an Iterator to display the entries.
Program-package Ass22;

import java.util.Iterator;
import java.util.TreeMap;
import java.util.Map;

class Address {
private int plotNo;
private String at;
private String post;
public Address(int plotNo, String at, String post) {
this.plotNo = plotNo;
this.at = at;
this.post = post;
}
public int getPlotNo() {
return plotNo;
}

public String getAt() {


return at;
}

public String getPost() {


return post;
}

@Override
public String toString() {
return "Plot No: " + plotNo + ", At: " + at + ", Post: " + post;
}
}

public class Q7 {
public static void main(String[] args) {
TreeMap<String, Address> addressBook = new TreeMap<>();
addressBook.put("John", new Address(101, "New York", "NY1001"));
addressBook.put("Alice", new Address(202, "Los Angeles", "LA2002"));
addressBook.put("Bob", new Address(303, "Chicago", "CH3003"));
System.out.println("Address Book Entries:");
Iterator<Map.Entry<String, Address>> iterator =
addressBook.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Address> entry = iterator.next();
System.out.println("Name: " + entry.getKey() + ", Address: " +
entry.getValue());
}
}
}
Output-

8. Write a Java program to determine whether two given strings are anagrams.
An anagram is a word or phrase formed by rearranging the letters of another
word or phrase.Declare two strings, str1 and str2, and initialize them with
values. Create a HashMap<Character, Integer> to store the character
frequencies of one string. Use the methods containsKey(), put(), and get() to
compare both strings and verify if they are anagrams.
Program-package Ass22;
import java.util.HashMap;

public class Q8 {
public static boolean areAnagrams(String str1, String str2) {
if (str1.length() != str2.length()) {
return false;
}

HashMap<Character, Integer> charCountMap = new HashMap<>();


for (char ch : str1.toCharArray()) {
charCountMap.put(ch, charCountMap.getOrDefault(ch, 0) + 1);
}
for (char ch : str2.toCharArray()) {
if (!charCountMap.containsKey(ch)) {
return false;
}
charCountMap.put(ch, charCountMap.get(ch) - 1);
if (charCountMap.get(ch) == 0) {
charCountMap.remove(ch);
}
}

return charCountMap.isEmpty();
}

public static void main(String[] args) {


String str1 = "listen";
String str2 = "silent";

if (areAnagrams(str1, str2)) {
System.out.println(str1 + " and " + str2 + " are anagrams.");
} else {
System.out.println(str1 + " and " + str2 + " are not anagrams.");
}
}
}

Output-

9.Given an array of integers, write a Java program to identify and print the
repeating integers using a HashSet.
Program-package Ass22;
import java.util.HashSet;

public class Q9 {
public static void findRepeating(int[] arr) {
HashSet<Integer> seen = new HashSet<>();
HashSet<Integer> duplicates = new HashSet<>();

for (int num : arr) {


if (!seen.add(num)) {
duplicates.add(num);
}
}

if (duplicates.isEmpty()) {
System.out.println("No repeating integers found.");
} else {
System.out.println("Repeating integers: " + duplicates);
}
}
public static void main(String[] args) {
int[] arr = {4, 2, 7, 2, 8, 4, 9, 7, 6};
findRepeating(arr);
}
}

Output-

10. Given an unsorted array of integers ranging from 1 to 10, write a program
to find the smallest positive number missing in the array. Use a
HashMap<Integer, Integer> to keep track of the elements and identify the
missing number.
Program-package Ass22;
import java.util.HashMap;

public class Q10 {


public static int findMissingNumber(int[] arr) {
HashMap<Integer, Integer> numberMap = new HashMap<>();
for (int num : arr) {
numberMap.put(num, 1);
}
for (int i = 1; i <= 10; i++) {
if (!numberMap.containsKey(i)) {
return i;
}
}
return -1;
}

public static void main(String[] args) {


int[] arr = {1, 2, 3, 4, 6, 7, 8, 9, 10};
int missingNumber = findMissingNumber(arr);

if (missingNumber == -1) {
System.out.println("No missing number found.");
} else {
System.out.println("Smallest missing number: " + missingNumber);
}
}
}

Output-

11. Declare an array of integers: int[] arr = {1, 2, 10, 8, 7, 3, 4, 6, 5, 9};. Then,
create a min-heap using the PriorityQueue class to store the elements from the
array. Finally, dequeue the elements from the PriorityQueue using the
appropriate methods and print them.
Program-package Ass22;

import java.util.PriorityQueue;

public class Q11 {


public static void main(String[] args) {
int[] arr = {1, 2, 10, 8, 7, 3, 4, 6, 5, 9};
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for (int num : arr) {
minHeap.add(num);
}
System.out.println("Elements in sorted order:");
while (!minHeap.isEmpty()) {
System.out.print(minHeap.poll() + " ");
}
}
}
Output-

You might also like