0% found this document useful (0 votes)
78 views26 pages

Ilovepdf Merged

The document provides code examples for several Java programming concepts across 3 weeks: Week 1 includes code to find prime numbers between 1 to n, solve quadratic equations, and implement inheritance and interfaces for a currency converter. Week 2 covers inheritance with abstract classes, method overloading and overriding, and implementing a currency converter with interfaces. Week 3 demonstrates creating packages and classes, user-defined exceptions, exception handling for account withdrawals, and try-with-resources, multi-catch exceptions, and exception propagation.

Uploaded by

vnraids
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)
78 views26 pages

Ilovepdf Merged

The document provides code examples for several Java programming concepts across 3 weeks: Week 1 includes code to find prime numbers between 1 to n, solve quadratic equations, and implement inheritance and interfaces for a currency converter. Week 2 covers inheritance with abstract classes, method overloading and overriding, and implementing a currency converter with interfaces. Week 3 demonstrates creating packages and classes, user-defined exceptions, exception handling for account withdrawals, and try-with-resources, multi-catch exceptions, and exception propagation.

Uploaded by

vnraids
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/ 26

WEEK-1:

a. Try debug step by step with java program to find prime numbers between 1 to n

import java.util.Scanner;
public class PrimeNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the value of n: ");
int n = input.nextInt();
for (int i = 2; i <= n; i++) {
boolean isPrime = true;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.print(i + " ");
}
}
}
}

b.Write a Java program that prints all real solutions to the quadratic equation
ax2+bx+c. Read in a, b, c and use the quadratic formula.

import java.util.Scanner;
public class QuadraticEquation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the value of a: ");
double a = input.nextDouble();
System.out.print("Enter the value of b: ");
double b = input.nextDouble();
System.out.print("Enter the value of c: ");
double c = input.nextDouble();

double discriminant = b * b - 4 * a * c;

if (discriminant > 0) {
double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
System.out.println("The roots are " + root1 + " and " + root2);
} else if (discriminant == 0) {
double root = -b / (2 * a);
System.out.println("The root is " + root);
} else {
System.out.println("The equation has no real roots.");
}
}
}
WEEK-2:
a. Write Java program on use of inheritance, preventing inheritance using final,
abstract classes.
abstract class Shape {
public abstract double getArea();
}
class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getArea() {
return width * height;
}
}
final class Square extends Shape {
private double side;
public Square(double side) {
this.side = side;
}
public double getArea() {
return side * side;
}
}
public class InheritanceDemo {
public static void main(String[] args) {
Shape s1 = new Rectangle(10, 20);
Shape s2 = new Square(10);
System.out.println("Area of rectangle: " + s1.getArea());
System.out.println("Area of square: " + s2.getArea());
}
}

b.Write Java program on dynamic binding, differentiating method overloading and


overriding.
class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("The dog barks");
}
public void makeSound(String message) {
System.out.println("The dog barks: " + message);
}
}
public class BindingDemo {
public static void main(String[] args) {
Animal animal = new Animal();
Dog dog = new Dog();
animal.makeSound();
dog.makeSound();
dog.makeSound("Hello");
}
}
c. Develop a java application to implement currency converter (Dollar to INR. EURO
to INR, Yen) using Interfaces.

import java.util.Scanner;
interface CurrencyConverter {
double convert(double amount);
}
class DollarToINR implements CurrencyConverter {
public double convert(double amount) {
return amount * 74.5;
}
}
class EuroToINR implements CurrencyConverter {
public double convert(double amount) {
return amount * 88.5;
}
}
class YenToINR implements CurrencyConverter {
public double convert(double amount) {
return amount * 0.67;
}
}
public class CurrencyConverterDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount in dollars: ");
double dollars = input.nextDouble();
System.out.print("Enter the amount in euros: ");
double euros = input.nextDouble();
System.out.print("Enter the amount in yen: ");
double yen = input.nextDouble();
CurrencyConverter dollarToINR = new DollarToINR();
CurrencyConverter euroToINR = new EuroToINR();
CurrencyConverter yenToINR = new YenToINR();
double inrFromDollars = dollarToINR.convert(dollars);
double inrFromEuros = euroToINR.convert(euros);
double inrFromYen = yenToINR.convert(yen);
System.out.println(dollars + " dollars = " + inrFromDollars + " INR");
System.out.println(euros + " euros = " + inrFromEuros + " INR");
System.out.println(yen + " yen = " + inrFromYen + " INR");
}
}
WEEK 3:
a. Write a Java program to create a package named "com.mycompany.math" that
contains a class named "Calculator" with methods to add, subtract, multiply and
divide two numbers. Write a test program to use this package.

package com.mycompany.math;
public class Calculator {
public static double add(double num1, double num2) {
return num1 + num2;
}
public static double subtract(double num1, double num2) {
return num1 - num2;
}
public static double multiply(double num1, double num2) {
return num1 * num2;
}
public static double divide(double num1, double num2) {
return num1 / num2;
}
}
import com.mycompany.math.Calculator;
public class TestCalculator {
public static void main(String[] args) {
double num1 = 10.0;
double num2 = 5.0;
System.out.println("Addition: " + Calculator.add(num1, num2));
System.out.println("Subtraction: " + Calculator.subtract(num1, num2));
System.out.println("Multiplication: " + Calculator.multiply(num1, num2));
System.out.println("Division: " + Calculator.divide(num1, num2));
}
}
b. Create a package named "com.mycompany.util" that contains a class named
"StringUtils" with a method named "reverseString" that takes a string as input and
returns the reverse of the input string. Write a test program to use this package.

package com.mycompany.util;
public class StringUtils {
public static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
}
import com.mycompany.util.StringUtils;
public class TestStringUtils {
public static void main(String[] args) {
String str = "Hello, world!";
String reversedStr = StringUtils.reverseString(str);
System.out.println("Original string: " + str);
System.out.println("Reversed string: " + reversedStr);
}
}
a. Write a Java program to implement user defined exception handling.

class MyException extends Exception {


public MyException(String message) {
super(message);
}
}
public class UserDefinedException {
public static void main(String[] args) {
int number = 0;
try {
java.util.Scanner scanner = new java.util.Scanner(System.in);
System.out.print("Enter a positive number: ");
number = scanner.nextInt();
scanner.close();
if (number < 0) {
throw new MyException("Negative number entered");
}
System.out.println("The number is " + number);
}
catch (MyException e) {
System.out.println(e.getMessage());
}
}
}

b.Write a Java program to throw an exception “Insufficient Funds” while withdrawing


the amount in the user account.
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
class BankAccount {
private String owner;
private double balance;
private double minimumBalance;
public BankAccount(String owner, double balance, double minimumBalance) {
this.owner = owner;
this.balance = balance;
this.minimumBalance = minimumBalance;
}

public String getOwner() {


return owner;
}

public double getBalance() {


return balance;
}
public double getMinimumBalance() {
return minimumBalance;
}
public void withdraw(double amount) throws InsufficientFundsException {
if (amount <= 0) {
throw new IllegalArgumentException("Invalid withdrawal amount");
}
if (amount > balance - minimumBalance) {
throw new InsufficientFundsException("Insufficient funds");
}
balance -= amount;
}
}
class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount("Alice", 10000, 1000);
try {
account.withdraw(5000);
System.out.println("Withdrawal successful");
System.out.println("New balance: " + account.getBalance());
} catch (InsufficientFundsException e) {
System.out.println("Withdrawal failed");
System.out.println(e.getMessage());
} catch (IllegalArgumentException e) {
System.out.println("Withdrawal failed");
System.out.println(e.getMessage());
}
}
}

c. Write a Java program to implement Try-with Resources, Multi-catch Exceptions,


and
Exception Propagation Concepts?

class Demo {
public static void method1() throws IOException {
throw new IOException("IO exception occurred");
}
public static void method2() throws ArithmeticException {
throw new ArithmeticException("Arithmetic exception occurred");
}
public static void method3() throws IOException, ArithmeticException {
method1();
method2();
}
public static void method4() throws IOException {
try (FileWriter fw = new FileWriter("output.txt")) {
fw.write("Hello world");
}
}
public static void main(String[] args) {
try {
method4();
System.out.println("File written successfully");
} catch (IOException e) {
System.out.println("IO exception: " + e.getMessage());
}
try {
method3();
} catch (IOException | ArithmeticException e) {
System.out.println("Exception: " + e.getMessage());
}
}
}
WEEK 5:
a. Write a java program to split a given text file into n parts. Name each part as
the name of the original file followed by .part where n is the sequence number of
the
part file.

import java.io.*;
import java.util.Scanner;
public class FileSplitter {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of the file to split: ");
String fileName = input.nextLine();
System.out.print("Enter the number of parts to split the file into: ");
int numParts = input.nextInt();
File inputFile = new File(fileName);
long fileSize = inputFile.length();
long partSize = fileSize / numParts;
long remainingBytes = fileSize % numParts;
try (BufferedInputStream bis = new BufferedInputStream(new
FileInputStream(inputFile))) {
byte[] buffer = new byte[(int) partSize];
int bytesRead = 0;
int partNumber = 1;
while ((bytesRead = bis.read(buffer)) > 0) {
String partFileName = inputFile.getName() + ".part" + partNumber;
File outputFile = new File(inputFile.getParent(), partFileName);
try (BufferedOutputStream bos = new BufferedOutputStream(new
FileOutputStream(outputFile))) {
bos.write(buffer, 0, bytesRead);
}
partNumber++;
}
if (remainingBytes > 0) {
String partFileName = inputFile.getName() + ".part" + partNumber;
File outputFile = new File(inputFile.getParent(), partFileName);
byte[] remainingBuffer = new byte[(int) remainingBytes];
bis.read(remainingBuffer);
try (BufferedOutputStream bos = new BufferedOutputStream(new
FileOutputStream(outputFile))) {
bos.write(remainingBuffer);
}
}
}
System.out.println("File has been split into " + numParts + " parts.");
}
}
b. Write a Java program that reads a file name from the user, displays information
about whether the tile exists, whether the file is readable, or writable. The type
of
tile and the length of the file in bytes.

import java.io.File;
import java.util.Scanner;
public class FileInfo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of the file: ");
String fileName = input.nextLine();
File file = new File(fileName);
if (file.exists()) {
System.out.println("File exists");
if (file.canRead()) {
System.out.println("File is readable");
} else {
System.out.println("File is not readable");
}
if (file.canWrite()) {
System.out.println("File is writable");
} else {
System.out.println("File is not writable");
}
System.out.println("File type: " + getFileType(file));
System.out.println("File length: " + file.length() + " bytes");
} else {
System.out.println("File does not exist");
}
}
private static String getFileType(File file) {
String fileName = file.getName();
int dotIndex = fileName.lastIndexOf('.');
if (dotIndex == -1) {
return "Unknown";
}
String extension = fileName.substring(dotIndex + 1).toLowerCase();
switch (extension) {
case "txt":
return "Text file";
case "doc":
case "docx":
return "Microsoft Word document";
case "xls":
case "xlsx":
return "Microsoft Excel spreadsheet";
case "ppt":
case "pptx":
return "Microsoft PowerPoint presentation";
case "pdf":
return "PDF document";
default:
return "Unknown";
}
}
}
WEEK 6:
a. Write a Java program on Random Access File class to perform different read and
write operations.
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileDemo {
public static void main(String[] args) throws IOException {
RandomAccessFile file = new RandomAccessFile("test.txt", "rw");
file.writeUTF("Hello, world!");
file.writeInt(42);
file.writeDouble(3.14);
file.seek(0);
String str = file.readUTF();
int num = file.readInt();
double dbl = file.readDouble();
System.out.println("String: " + str);
System.out.println("Integer: " + num);
System.out.println("Double: " + dbl);
file.close();
}
}
b. Create a class called Employee with properties name(String), dateofbirth
(java.util.Date), department(String), designation(String) and Salary(double).
Create respective getter and setter methods and constructors (no-argument
constructor and parameterized constructor) for the same. Create an object of the
Employee class and save this object in a file called “data” using serialization.
Later using deserialization read this object and prints the properties of this
object.
import java.io.*;
public class Employee implements Serializable {
private String name;
private java.util.Date dateOfBirth;
private String department;
private String designation;
private double salary;
public Employee() {}
public Employee(String name, java.util.Date dateOfBirth, String department,
String designation, double salary) {
this.name = name;
this.dateOfBirth = dateOfBirth;
this.department = department;
this.designation = designation;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public java.util.Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(java.util.Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String toString() {
return "Name: " + name + "\nDate of birth: " + dateOfBirth + "\nDepartment:
" + department + "\nDesignation: " + designation + "\nSalary: " + salary;
}
public static void main(String[] args) throws IOException,
ClassNotFoundException {
Employee employee = new Employee("John Doe", new java.util.Date(), "Sales",
"Manager", 50000.0);
FileOutputStream fileOut = new FileOutputStream("data");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(employee);
out.close();
fileOut.close();
System.out.println("Object has been serialized");
FileInputStream fileIn = new FileInputStream("data");
ObjectInputStream in = new ObjectInputStream(fileIn);
Employee employee2 = (Employee) in.readObject();
in.close();
fileIn.close();
System.out.println("Object has been deserialized");
System.out.println(employee2.toString());
}
}
WEEK 7:
a. Create a generic class called Box that can hold any type of object. Implement
the following methods: 1) void set(T obj): sets the object stored in the box 2) T
get():
retrieves the object stored in the box 3) boolean isEmpty(): returns true if the
box is empty, false otherwise.
public class Box<T> {
private T object;
public void set(T obj) {
this.object = obj;
}
public T get() {
return this.object;
}
public boolean isEmpty() {
return this.object == null;
}
}
Box<String> box = new Box<>();
System.out.println("Is box empty? " + box.isEmpty());
box.set("Hello, world!");
System.out.println("Is box empty? " + box.isEmpty());
System.out.println("Object in box: " + box.get());

b. Implement a generic Stack class that can hold any type of object. Implement the
following methods: 1) void push(T obj): pushes an object onto the top of the stack
,2) T pop(): removes and returns the object at the top of the stack 3) boolean
isEmpty(): returns true if the stack is empty, false otherwise
import java.util.ArrayList;
public class Stack<T> {
private ArrayList<T> stack;
public Stack() {
stack = new ArrayList<T>();
}
public void push(T obj) {
stack.add(obj);
}
public T pop() {
if (isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return stack.remove(stack.size() - 1);
}
public boolean isEmpty() {
return stack.isEmpty();
}
}
Stack<String> stack = new Stack<>();
System.out.println("Is stack empty? " + stack.isEmpty()); // prints "Is stack
empty? true"
stack.push("Hello, world!");
System.out.println("Is stack empty? " + stack.isEmpty()); // prints "Is stack
empty? false"
System.out.println("Object at top of stack: " + stack.pop()); // prints "Object at
top of stack: Hello, world!"
System.out.println("Is stack empty? " + stack.isEmpty()); // prints "Is stack
empty? true"
WEEK 8:
a. Write a Java program to implement Autoboxing and Unboxing?

public class AutoboxingUnboxingExample {


public static void main(String[] args) {
// Autoboxing
Integer i = 10;
Double d = 10.5;
// Unboxing
int j = i;
double k = d;
System.out.println("Autoboxing: " + i + ", " + d);
System.out.println("Unboxing: " + j + ", " + k);
}
}

b. Write a Java program to implement Built-In Java Annotations?

public class BuiltInAnnotationsExample {


@Deprecated
public void oldMethod() {
System.out.println("This method is deprecated.");
}
@SuppressWarnings("unchecked")
public void uncheckedMethod() {
ArrayList list = new ArrayList();
list.add("Hello");
list.add("World");
System.out.println(list);
}
@Override
public String toString() {
return "This is the BuiltInAnnotationsExample class.";
}
}
WEEK 9:
a. Write a Java program that creates three threads. First thread displays —Good
Morning every one second, the second thread displays —Hello every two seconds
and the third thread displays —Welcome every three seconds.

public class ThreadExample {


public static void main(String[] args) {
// Creating three threads
Thread thread1 = new Thread(() -> displayMessage("Good Morning", 1000));
Thread thread2 = new Thread(() -> displayMessage("Hello", 2000));
Thread thread3 = new Thread(() -> displayMessage("Welcome", 3000));
// Starting the threads
thread1.start();
thread2.start();
thread3.start();
}
// Method to display a message at a given interval
private static void displayMessage(String message, long interval) {
while (true) {
System.out.println(message);
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
b. Write a Java program that correctly implements producer consumer problem using
the concept of inter thread communication.

import java.util.LinkedList;
public class ProducerConsumerExample {
public static void main(String[] args) {
final PC pc = new PC();
Thread producerThread = new Thread(new Runnable() {
@Override
public void run() {
try {
pc.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread consumerThread = new Thread(new Runnable() {
@Override
public void run() {
try {
pc.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
producerThread.start();
consumerThread.start();
try {
producerThread.join();
consumerThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static class PC {
LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;
public void produce() throws InterruptedException {
int value = 0;
while (true) {
synchronized (this) {
while (list.size() == capacity) {
wait();
}
System.out.println("Producer produced-" + value);
list.add(value++);
notify();
Thread.sleep(1000);
}
}
}
public void consume() throws InterruptedException {
while (true) {
synchronized (this) {
while (list.size() == 0) {
wait();
}
int val = list.removeFirst();
System.out.println("Consumer consumed-" + val);
notify();
Thread.sleep(1000);
}
}
}
}
}
c. Create a Email registration Form using Java AWT. The UI should have fields such
as name, address, sex, age, email, contact number, etc.

import java.awt.*;
import java.awt.event.*;
public class EmailRegistrationForm extends Frame {
Label nameLabel, addressLabel, sexLabel, ageLabel, emailLabel, contactLabel;
TextField nameField, addressField, ageField, emailField, contactField;
Checkbox maleCheckbox, femaleCheckbox;
Button submitButton;
public EmailRegistrationForm() {
super("Email Registration Form");
setSize(500, 300);
setLayout(null);
nameLabel = new Label("Name:");
nameLabel.setBounds(50, 50, 100, 20);
add(nameLabel);
nameField = new TextField();
nameField.setBounds(150, 50, 200, 20);
add(nameField);
addressLabel = new Label("Address:");
addressLabel.setBounds(50, 80, 100, 20);
add(addressLabel);
addressField = new TextField();
addressField.setBounds(150, 80, 200, 20);
add(addressField);
sexLabel = new Label("Sex:");
sexLabel.setBounds(50, 110, 100, 20);
add(sexLabel);
maleCheckbox = new Checkbox("Male");
maleCheckbox.setBounds(150, 110, 100, 20);
add(maleCheckbox);
femaleCheckbox = new Checkbox("Female");
femaleCheckbox.setBounds(250, 110, 100, 20);
add(femaleCheckbox);
ageLabel = new Label("Age:");
ageLabel.setBounds(50, 140, 100, 20);
add(ageLabel);
ageField = new TextField();
ageField.setBounds(150, 140, 200, 20);
add(ageField);
emailLabel = new Label("Email:");
emailLabel.setBounds(50, 170, 100, 20);
add(emailLabel);
emailField = new TextField();
emailField.setBounds(150, 170, 200, 20);
add(emailField);
contactLabel = new Label("Contact Number:");
contactLabel.setBounds(50, 200, 100, 20);
add(contactLabel);
contactField = new TextField();
contactField.setBounds(150, 200, 200, 20);
add(contactField);
submitButton = new Button("Submit");
submitButton.setBounds(200, 230, 100, 20);
add(submitButton);
setVisible(true);
}
public static void main(String[] args) {
EmailRegistrationForm form = new EmailRegistrationForm();
}
}
WEEK 10:
a. Write a Java program to create a Vector and add some elements to it. Then get
the element at a specific index and print it.
import java.util.Vector;
public class VectorDemo {
public static void main(String[] args) {
Vector<String> vector = new Vector<>();
vector.add("apple");
vector.add("banana");
vector.add("cherry");
int index = 1;
String element = vector.get(index);
System.out.println("Element at index " + index + ": " + element);
}
}
b. Write a Java program to create a BitSet and set some bits in it. Then perform
some bitwise operations on the BitSet and print the result.
import java.util.BitSet;
public class BitSetDemo {
public static void main(String[] args) {
BitSet bitSet = new BitSet(8);
bitSet.set(0);
bitSet.set(2);
bitSet.set(4);
BitSet bitSet2 = new BitSet(8);
bitSet2.set(1);
bitSet2.set(3);
bitSet2.set(5);
System.out.println("BitSet 1: " + bitSet);
System.out.println("BitSet 2: " + bitSet2);
bitSet.and(bitSet2);
System.out.println("BitSet 1 AND BitSet 2: " + bitSet);
bitSet.or(bitSet2);
System.out.println("BitSet 1 OR BitSet 2: " + bitSet);
bitSet.xor(bitSet2);
System.out.println("BitSet 1 XOR BitSet 2: " + bitSet);
}
}
c. Write a Java program to read the time intervals (HH:MM) and to compare system
time if the system Time between your time intervals print correct time and exit
else
try again to repute the same thing. By using String Tokenizer class.
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean validInput = false;
int startHour = 0, startMinute = 0, endHour = 0, endMinute = 0;
while (!validInput) {
System.out.print("Enter the start time (HH:MM): ");
String startTime = input.nextLine();
System.out.print("Enter the end time (HH:MM): ");
String endTime = input.nextLine();
StringTokenizer startTokenizer = new StringTokenizer(startTime, ":");
StringTokenizer endTokenizer = new StringTokenizer(endTime, ":");
if (startTokenizer.countTokens() == 2 && endTokenizer.countTokens() ==
2) {
try {
startHour = Integer.parseInt(startTokenizer.nextToken());
startMinute = Integer.parseInt(startTokenizer.nextToken());
endHour = Integer.parseInt(endTokenizer.nextToken());
endMinute = Integer.parseInt(endTokenizer.nextToken());
if (startHour >= 0 && startHour <= 23 && startMinute >= 0 &&
startMinute <= 59 &&
endHour >= 0 && endHour <= 23 && endMinute >= 0 &&
endMinute <= 59) {
validInput = true;
} else {
System.out.println("Invalid input. Please enter a valid
time in the format HH:MM.");
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid time in
the format HH:MM.");
}
} else {
System.out.println("Invalid input. Please enter a valid time in the
format HH:MM.");
}
}
int currentHour = java.time.LocalTime.now().getHour();
int currentMinute = java.time.LocalTime.now().getMinute();
if (currentHour > startHour || (currentHour == startHour && currentMinute
>= startMinute)) {
if (currentHour < endHour || (currentHour == endHour && currentMinute
<= endMinute)) {
System.out.println("The current time is between " + startHour + ":"
+ startMinute + " and " + endHour + ":" + endMinute + ".");
System.exit(0);
}
}
System.out.println("The current time is not between " + startHour + ":" +
startMinute + " and " + endHour + ":" + endMinute + ".");
}
}
WEEK 11:
a. Write a Java program to demonstrate the working of different collection
classes.[Use package structure to store multiple classes].
package com.example.collections;
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args) {
List<String> arrayList = new ArrayList<>();
arrayList.add("apple");
arrayList.add("banana");
arrayList.add("cherry");
System.out.println("ArrayList: " + arrayList);
// LinkedList
List<String> linkedList = new LinkedList<>();
linkedList.add("apple");
linkedList.add("banana");
linkedList.add("cherry");
System.out.println("LinkedList: " + linkedList);
// HashSet
Set<String> hashSet = new HashSet<>();
hashSet.add("apple");
hashSet.add("banana");
hashSet.add("cherry");
System.out.println("HashSet: " + hashSet);
// TreeSet
Set<String> treeSet = new TreeSet<>();
treeSet.add("apple");
treeSet.add("banana");
treeSet.add("cherry");
System.out.println("TreeSet: " + treeSet);
// HashMap
Map<String, String> hashMap = new HashMap<>();
hashMap.put("apple", "red");
hashMap.put("banana", "yellow");
hashMap.put("cherry", "red");
System.out.println("HashMap: " + hashMap);
// TreeMap
Map<String, String> treeMap = new TreeMap<>();
treeMap.put("apple", "red");
treeMap.put("banana", "yellow");
treeMap.put("cherry", "red");
System.out.println("TreeMap: " + treeMap);
}
}
b. Write a Java program to create a TreeMap and add some elements to it. Then get
the value associated with a specific key and print it.

import java.util.TreeMap;
public class TreeMapDemo {
public static void main(String[] args) {
TreeMap<String, String> treeMap = new TreeMap<>();
treeMap.put("apple", "red");
treeMap.put("banana", "yellow");
treeMap.put("cherry", "red");
String key = "banana";
String value = treeMap.get(key);
System.out.println("Value associated with key " + key + ": " + value);
}
}

c. Write a Java program to create a PriorityQueue and add some elements to it. Then
remove the highest priority element from the PriorityQueue and print the
remaining elements.
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) {
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
priorityQueue.add(5);
priorityQueue.add(3);
priorityQueue.add(7);
priorityQueue.add(1);
System.out.println("PriorityQueue: " + priorityQueue);
int highestPriorityElement = priorityQueue.poll();
System.out.println("Highest priority element: " + highestPriorityElement);
System.out.println("PriorityQueue after removing highest priority element:
" + priorityQueue);
}
}

You might also like