ASSIGNMENT-1
NAME: GK.CHANDANA
ROLLNO: 2211CS010163
SECTION: GROUP-1
1. Write a java program to build a class Employee having name, department, salary &
performanceRating as attributes. And using Java Streams :
Filters the employees who have a performance rating of 4.0 or higher.
Find the highest paid employee after filtering.
Print the salary of the highest-paid employee with rating above 4.0 .
Program:
import java.util.*;
import java.util.stream.*;
class Employee {
private String name;
private String department;
private double salary;
private double performanceRating;
public Employee(String name, String department, double salary, double performanceRating) {
this.name = name;
this.department = department;
this.salary = salary;
this.performanceRating = performanceRating;
}
public double getSalary() {
return salary;
}
public double getPerformanceRating() {
return performanceRating;
}
public String getName() {
return name;
}
}
public class EmployeeStream {
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee("Alice", "IT", 75000, 4.5),
new Employee("Bob", "Finance", 60000, 3.9),
new Employee("Charlie", "HR", 80000, 4.2),
new Employee("David", "IT", 95000, 4.8)
);
Optional<Employee> highestPaid = employees.stream()
.filter(emp -> emp.getPerformanceRating() >= 4.0)
.max(Comparator.comparingDouble(Employee::getSalary));
if (highestPaid.isPresent()) {
System.out.println("Highest Paid Employee Salary (Rating >= 4.0): "
+ highestPaid.get().getSalary());
} else {
System.out.println("No employee found with rating >= 4.0");
}
}
}
Output:
2. Create a student class with roll number, name & address as data members, initialize and display
student details.
Program:
class Student {
private int rollNumber;
private String name;
private String address;
// Constructor to initialize data members
public Student(int rollNumber, String name, String address) {
this.rollNumber = rollNumber;
this.name = name;
this.address = address;
}
// Method to display student details
public void displayDetails() {
System.out.println("Roll Number: " + rollNumber);
System.out.println("Name : " + name);
System.out.println("Address : " + address);
}
}
public class Student1 {
public static void main(String[] args) {
// Creating Student objects and initializing
Student student1 = new Student(101, "Akhil", "HYD");
Student student2 = new Student(102, "Bindhu", "MRUH");
Student student3 = new Student(103, "Charan", "SEC");
// Displaying details
System.out.println("Student 1 Details:");
student1.displayDetails();
System.out.println("\nStudent 2 Details:");
student2.displayDetails();
System.out.println("\nStudent 3 Details:");
student3.displayDetails();
}
}
Output:
3. How to copy an object in Java?
A: There are mainly three ways
i. Shallow Copy
• Copies only primitive fields and references of objects.
• Changes in referenced objects reflect in the copied object.
• Achieved using clone() method from Object class.
ii. Deep Copy
• Creates a new object and copies all fields, including new copies of referenced objects.
• Changes in the copy do not affect the original.
• Implemented manually or using serialization.
iii. Copy Constructor
• A special constructor that takes an object of the same class and copies all its fields.
• Simple and safe compared to clone().
Example program:
class Address {
String city;
Address(String city) {
this.city = city;
}
}
class Student implements Cloneable {
int rollNo;
String name;
Address address;
// Normal Constructor
Student(int rollNo, String name, Address address) {
this.rollNo = rollNo;
this.name = name;
this.address = address;
}
// Copy Constructor (Deep Copy)
Student(Student s) {
this.rollNo = s.rollNo;
this.name = s.name;
this.address = new Address(s.address.city); // new Address object
}
// Shallow Copy using clone()
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone(); // Only references are copied (shallow copy)
}
public void display() {
System.out.println("Roll No: " + rollNo + ", Name: " + name + ", City: " + address.city);
}
}
public class CopyExample {
public static void main(String[] args) throws CloneNotSupportedException {
Address addr = new Address("New York");
Student original = new Student(101, "John", addr);
// 1. Shallow Copy using clone()
Student shallowCopy = (Student) original.clone();
// 2. Deep Copy using Copy Constructor
Student deepCopy = new Student(original);
System.out.println("Original Object:");
original.display();
System.out.println("\nShallow Copy Object:");
shallowCopy.display();
System.out.println("\nDeep Copy Object:");
deepCopy.display();
// Modifying address city in shallow copy
shallowCopy.address.city = "Los Angeles";
System.out.println("\nAfter changing shallow copy city:");
System.out.println("Original Object:");
original.display(); // Affected because of shallow copy
System.out.println("Shallow Copy Object:");
shallowCopy.display();
// Modifying address city in deep copy
deepCopy.address.city = "Chicago";
System.out.println("\nAfter changing deep copy city:");
System.out.println("Original Object:");
original.display(); // Unaffected because deep copy is separate
System.out.println("Deep Copy Object:");
deepCopy.display();
}
Output:
4. Build java program for the following class structure.
Program:
// Interface
interface Printable {
void print();
}
// Abstract class
abstract class Person implements Printable {
protected String name;
protected String gender;
protected String email;
public Person(String name, String gender, String email) {
this.name = name;
this.gender = gender;
this.email = email;
}
}
// Concrete class Student
class Student extends Person {
private String grade;
public Student(String name, String gender, String email, String grade) {
super(name, gender, email);
this.grade = grade;
}
@Override
public void print() {
System.out.println("Student Details:");
System.out.println("Name : " + name);
System.out.println("Gender : " + gender);
System.out.println("Email : " + email);
System.out.println("Grade : " + grade);
}
}
// Concrete class Staff
class Staff extends Person {
private double salary;
public Staff(String name, String gender, String email, double salary) {
super(name, gender, email);
this.salary = salary;
}
@Override
public void print() {
System.out.println("Staff Details:");
System.out.println("Name : " + name);
System.out.println("Gender : " + gender);
System.out.println("Email : " + email);
System.out.println("Salary : " + salary);
}
}
// Main class
public class Main {
public static void main(String[] args) {
Printable student = new Student("John Doe", "Male", "john@example.com", "A+");
Printable staff = new Staff("Jane Smith", "Female", "jane@example.com", 55000);
student.print();
System.out.println();
staff.print();
}
}
Output:
5. Build java program for the following class structure.
Program:
// Address class
class Address {
String hno;
String street;
String area;
String district;
String state;
String pincode;
public Address(String hno, String street, String area, String district, String state, String pincode) {
this.hno = hno;
this.street = street;
this.area = area;
this.district = district;
this.state = state;
this.pincode = pincode;
}
public void display() {
System.out.println("Address: " + hno + ", " + street + ", " + area +
", " + district + ", " + state + " - " + pincode);
}
}
// Person class
class Person {
String name;
String gender;
String email;
Address address; // Has-A relationship
public Person(String name, String gender, String email, Address address) {
this.name = name;
this.gender = gender;
this.email = email;
this.address = address;
}
public void display() {
System.out.println("Name : " + name);
System.out.println("Gender : " + gender);
System.out.println("Email : " + email);
address.display();
}
}
// Student class
class Student extends Person {
String grade;
public Student(String name, String gender, String email, Address address, String grade) {
super(name, gender, email, address);
this.grade = grade;
}
@Override
public void display() {
System.out.println("Student Details:");
super.display();
System.out.println("Grade : " + grade);
}
}
// Main class
public class Main {
public static void main(String[] args) {
Address addr = new Address("12-34", "MG Road", "Banjara Hills", "Hyderabad", "Telangana",
"500001");
Student student = new Student("John Doe", "Male", "john@example.com", addr, "A+");
student.display();
}
}
Output:
6. Create a BankAccount class with an Inner class Interest implementing a scenario such that only an
authenticated bank person can interact with inner class by calling contact() method of BankAccount.
When contact() method will be called, it will verify with password and then he will be able to use the
inner class and access it.
Program:
import java.util.Scanner;
class BankAccount {
private String accountNumber;
private double balance;
private String password = "secure123"; // sample password
// Constructor
public BankAccount(String accountNumber, double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
// Inner class
private class Interest {
private double interestRate = 5.0;
public void calculateInterest() {
double interest = (balance * interestRate) / 100;
System.out.println("Interest on account " + accountNumber + ": " + interest);
}
}
// contact method
public void contact() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter password to access Interest calculations: ");
String input = sc.nextLine();
if (input.equals(password)) {
System.out.println("Authentication successful.");
Interest interest = new Interest();
interest.calculateInterest();
} else {
System.out.println("Authentication failed. Access denied!");
}
// sc.close(); // avoid closing System.in here
}
}
// Main class to test
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount("ACC12345", 10000);
account.contact(); // triggers authentication and access
}
}
Output:
7. A software development company is designing a library management system that requires a
flexible data container to store different types of items, such as books, magazines, and DVDs. The
company wants a generic class that can store any type of object
Program:
// Generic class
class LibraryItem<T> {
private T item;
public void addItem(T item) {
this.item = item;
System.out.println("Item added: " + item.toString());
}
public T getItem() {
return item;
}
}
// Sample Book class
class Book {
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
@Override
public String toString() {
return "Book [Title=" + title + ", Author=" + author + "]";
}
}
// Sample DVD class
class DVD {
private String title;
private int duration;
public DVD(String title, int duration) {
this.title = title;
this.duration = duration;
}
@Override
public String toString() {
return "DVD [Title=" + title + ", Duration=" + duration + " mins]";
}
}
// Main class
public class Main {
public static void main(String[] args) {
// Generic container for Book
LibraryItem<Book> bookItem = new LibraryItem<>();
bookItem.addItem(new Book("Effective Java", "Joshua Bloch"));
System.out.println("Retrieved: " + bookItem.getItem());
// Generic container for DVD
LibraryItem<DVD> dvdItem = new LibraryItem<>();
dvdItem.addItem(new DVD("Inception", 148));
System.out.println("Retrieved: " + dvdItem.getItem());
// Generic container for String (can store any type)
LibraryItem<String> noteItem = new LibraryItem<>();
noteItem.addItem("Reference Notes");
System.out.println("Retrieved: " + noteItem.getItem());
}
}
Output:
8. Java Regular Expression Example: Email Validation
Program:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;
public class EmailValidation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Regular expression for email
String regex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
Pattern pattern = Pattern.compile(regex);
System.out.print("Enter an email address: ");
String email = sc.nextLine();
Matcher matcher = pattern.matcher(email);
if (matcher.matches()) {
System.out.println("Valid Email Address");
} else {
System.out.println("Invalid Email Address");
}
sc.close();
}
}
Output:
9. For the Appilcation on International flight booking system, the system needs to calculate the
arrival time of a flight based on:
1. Departure time (Local Time Zone)
2. Flight duration
3. Destination time zone
Your task is to write a Java program that:
• Takes a departure time in one time zone.
• Adds the flight duration to determine the arrival time.
Converts the arrival time to the destination's time zone.
Program:
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
public class FlightArrivalTime {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input: Departure Time Zone, Time and Flight Duration
System.out.print("Enter departure time zone (e.g., Asia/Kolkata): ");
String departureZone = sc.nextLine();
System.out.print("Enter destination time zone (e.g., America/New_York): ");
String destinationZone = sc.nextLine();
System.out.print("Enter departure time (yyyy-MM-dd HH:mm): ");
String departureTimeStr = sc.nextLine();
System.out.print("Enter flight duration in hours: ");
long hours = sc.nextLong();
System.out.print("Enter additional minutes: ");
long minutes = sc.nextLong();
// Parse departure time with zone
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime departureLocalDateTime = LocalDateTime.parse(departureTimeStr, formatter);
ZonedDateTime departureTime = departureLocalDateTime.atZone(ZoneId.of(departureZone));
// Add flight duration
ZonedDateTime arrivalTimeAtDepartureZone =
departureTime.plusHours(hours).plusMinutes(minutes);
// Convert to destination time zone
ZonedDateTime arrivalTimeAtDestination =
arrivalTimeAtDepartureZone.withZoneSameInstant(ZoneId.of(destinationZone));
// Display results
System.out.println("\nDeparture Time: " + departureTime.format(formatter) + " " +
departureTime.getZone());
System.out.println("Arrival Time at Destination: " +
arrivalTimeAtDestination.format(formatter) + " " +
arrivalTimeAtDestination.getZone());
sc.close();}}
Output:
10. Bank Account Withdrawal System with Custom Exceptions
Design a Java application to simulate a basic bank withdrawal system. The system must include
robust error handling using user-defined exceptions to enforce business rules and ensure valid
transactions.
Program:
import java.util.Scanner;
// Custom Exception for insufficient funds
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
// Custom Exception for invalid amount
class InvalidAmountException extends Exception {
public InvalidAmountException(String message) {
super(message);
}
}
// BankAccount class
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
public double getBalance() {
return balance;
}
// Withdrawal method with custom exceptions
public void withdraw(double amount) throws InsufficientFundsException,
InvalidAmountException {
if (amount <= 0) {
throw new InvalidAmountException("Withdrawal amount must be greater than zero.");
}
if (amount > balance) {
throw new InsufficientFundsException("Insufficient funds. Your balance is " + balance);
}
balance -= amount;
System.out.println("Withdrawal successful! Remaining Balance: " + balance);
}
}
public class BankWithdrawalSystem {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
BankAccount account = new BankAccount(5000.00); // initial balance
System.out.println("Your Current Balance: " + account.getBalance());
System.out.print("Enter amount to withdraw: ");
double amount = sc.nextDouble();
try {
account.withdraw(amount);
} catch (InvalidAmountException | InsufficientFundsException e) {
System.out.println("Transaction Failed: " + e.getMessage());
}sc.close();
}
}
Output: