Q1 ) Create a Book class with bookId, bookName and authorName.
Create
parameterized constructor to initialize the object. Create an ArrayList of
type Book and store all book objects into collections and display all book
details.
Code -->
import java.util.*;
class Book {
int bookId;
String bookName;
// Parameterized constructor hai
Book(int id, String name) {
this.bookId = id;
this.bookName = name;
// toString method to display book details
public String toString() {
return "Book ID: " + bookId + ", Book Name: " + bookName;
}
}
public class BookArrayListDemo {
public static void main(String[] args) {
ArrayList<Book> bookList = new ArrayList<>();
bookList.add(new Book(101, "Java Programming"));
bookList.add(new Book(102, "C Programming" ));
bookList.add(new Book(103, "Python Basics"));
bookList.add(new Book(104, "Data Structures"));
// Displaying book details using loop
System.out.println("Book Details:");
for (Book b : bookList) {
System.out.println(b);
}
}
}
-----------------------------------------------------------------------------------
-----------------------
Q2) Write a Java program that calculates the sum of all even numbers present:
code -->
import java.util.*;
public class EvenNumberSum {
public static void main(String[] args) {
// ArrayList
ArrayList<Integer> num = new ArrayList<>();
num.add(23);
num.add(10);
num.add(45);
num.add(66);
num.add(88);
num.add(13);
int sum = 0;
for (int num : num) {
if (num % 2 == 0) {
sum += num;
}
}
System.out.println("Sum of Even Numbers: " + sum);
}
}
-----------------------------------------------------------------------------------
-----------------------
Q3) . Write a program to reverse a given List of strings.
code-->
import java.util.*;
public class ReverseStringList{
public static void main(String [] args){
List<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");
list.add("Welcome");
list.add("To");
list.add("Anudip");
list.add("classes");
System.out.println("Original List: " + list);
// Reverse the list
Stack<String> stack = new Stack<>();
for (String str : list) {
stack.push(str);
}
List<String> reversedList = new ArrayList<>();
while (!stack.isEmpty()) {
reversedList.add(stack.pop());
}
System.out.println("Reversed List: " + reversedList);
}
}
-----------------------------------------------------------------------------------
-----------------------