0% found this document useful (0 votes)
2 views92 pages

Java-I Practical Slips Solution

The document contains multiple Java programming tasks, including calculating the perimeter and area of a rectangle, creating an abstract class for orders, implementing a menu-driven program for various calculations, and creating a product class using a marker interface. It also includes programs for reversing an array, managing student marks across packages, and defining an employee class with object counting. Each task is accompanied by sample code demonstrating the required functionality.

Uploaded by

godkratpsss
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)
2 views92 pages

Java-I Practical Slips Solution

The document contains multiple Java programming tasks, including calculating the perimeter and area of a rectangle, creating an abstract class for orders, implementing a menu-driven program for various calculations, and creating a product class using a marker interface. It also includes programs for reversing an array, managing student marks across packages, and defining an employee class with object counting. Each task is accompanied by sample code demonstrating the required functionality.

Uploaded by

godkratpsss
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

SLIP 1

1) Write a program to calculate perimeter and area of rectangle. (hint : area = length *
breadth , perimeter=2*(length+breadth))

Code:

import java.util.Scanner;

public class RectangleCalculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Prompt user for length


System.out.print("Enter the length of the rectangle: ");
double length = scanner.nextDouble();

// Prompt user for breadth


System.out.print("Enter the breadth of the rectangle: ");
double breadth = scanner.nextDouble();

// Calculate area and perimeter


double area = length * breadth;
double perimeter = 2 * (length + breadth);

// Display the results


System.out.println("Area of the rectangle is: " + area);
System.out.println("Perimeter of the rectangle is: " + perimeter);

scanner.close();
}
}
2) Create an abstract class “order” having members id,description.Create two subclasses
“Purchase Order” and “Sales Order” having members customer name and Vendor name
respectively.Define methods accept and display in all cases. Create 3 objects each of
Purchase Order and Sales Order and accept and display details.

Code:

import java.util.Scanner;
// Abstract base class
abstract class Order {
int id;
String description;

// Abstract methods to be implemented by subclasses


abstract void accept();
abstract void display();
}
// Subclass for Purchase Orders
class PurchaseOrder extends Order {
String customerName;

@Override
void accept() {
Scanner scanner = new Scanner(System.in);
System.out.println("\nEnter Purchase Order Details:");
System.out.print("Enter ID: ");
id = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.print("Enter Description: ");
description = scanner.nextLine();
System.out.print("Enter Customer Name: ");
customerName = scanner.nextLine();
}

@Override
void display() {
System.out.println("\n--- Purchase Order ---");
System.out.println("ID: " + id);
System.out.println("Description: " + description);
System.out.println("Customer Name: " + customerName);
System.out.println("----------------------");
}
}
// Subclass for Sales Orders
class SalesOrder extends Order {
String vendorName;

@Override
void accept() {
Scanner scanner = new Scanner(System.in);
System.out.println("\nEnter Sales Order Details:");
System.out.print("Enter ID: ");
id = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.print("Enter Description: ");
description = scanner.nextLine();
System.out.print("Enter Vendor Name: ");
vendorName = scanner.nextLine();
}

@Override
void display() {
System.out.println("\n--- Sales Order ---");
System.out.println("ID: " + id);
System.out.println("Description: " + description);
System.out.println("Vendor Name: " + vendorName);
System.out.println("-------------------");
}
}
public class OrderDemo {
public static void main(String[] args) {
// Create 3 PurchaseOrder objects
PurchaseOrder[] pOrders = new PurchaseOrder[3];
for (int i = 0; i < 3; i++) {
System.out.println("\nEntering details for Purchase Order " + (i + 1));
pOrders[i] = new PurchaseOrder();
pOrders[i].accept();
}
// Create 3 SalesOrder objects
SalesOrder[] sOrders = new SalesOrder[3];
for (int i = 0; i < 3; i++) {
System.out.println("\nEntering details for Sales Order " + (i + 1));
sOrders[i] = new SalesOrder();
sOrders[i].accept();
}
// Display all order details
System.out.println("\n--- All Order Details ---");
for (PurchaseOrder po : pOrders) {
po.display();
}
for (SalesOrder so : sOrders) {
so.display();
}
}
}
SLIP 2

1) Write a menu driven program to perform the following operations i. Calculate the volume
of cylinder. (hint : Volume: π × r² × h) ii. Find the factorial of given number. iii. Check the
number is Armstrong or not. iv. Exit

Code:

import java.util.Scanner;

public class MenuDrivenProgram {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;

do {
// Display menu
System.out.println("\n--- MENU ---");
System.out.println("1. Calculate Volume of Cylinder");
System.out.println("2. Find Factorial");
System.out.println("3. Check Armstrong Number");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();

switch (choice) {
case 1:
calculateCylinderVolume(scanner);
break;
case 2:
findFactorial(scanner);
break;
case 3:
checkArmstrong(scanner);
break;
case 4:
System.out.println("Exiting program. Goodbye! ");
break;
default:
System.out.println("Invalid choice! Please enter a number between 1 and 4.");
}
} while (choice != 4);

scanner.close();
}
// i. Calculate volume of a cylinder (Volume: π * r^2 * h) [cite: 15]
public static void calculateCylinderVolume(Scanner scanner) {
System.out.print("\nEnter radius of the cylinder: ");
double r = scanner.nextDouble();
System.out.print("Enter height of the cylinder: ");
double h = scanner.nextDouble();
double volume = Math.PI * r * r * h;
System.out.println("Volume of the cylinder is: " + volume);
}

// ii. Find the factorial of a given number [cite: 16]


public static void findFactorial(Scanner scanner) {
System.out.print("\nEnter a number to find its factorial: ");
int num = scanner.nextInt();
long factorial = 1;
for (int i = 1; i <= num; ++i) {
factorial *= i;
}
System.out.println("Factorial of " + num + " is: " + factorial);
}

// iii. Check if a number is an Armstrong number [cite: 17]


public static void checkArmstrong(Scanner scanner) {
System.out.print("\nEnter a number to check if it's an Armstrong number: ");
int number = scanner.nextInt();
int originalNumber, remainder, result = 0, n = 0;
originalNumber = number;

// Count number of digits


for (int temp = originalNumber; temp != 0; temp /= 10, ++n);

// Calculate result
for (int temp = originalNumber; temp != 0; temp /= 10) {
remainder = temp % 10;
result += Math.pow(remainder, n);
}

// Check and display result


if (result == number)
System.out.println(number + " is an Armstrong number. ");
else
System.out.println(number + " is not an Armstrong number.");
}
}
2) Write a program to using marker interface create a class product(product_id,
product_name, product_cost, product_quantity) define a default and parameterized
constructor. Create objects of class product and display the contents of each object and
Also display the object count.

Code:

// A marker interface has no methods or constants inside it.


// It provides run-time type information about objects.
interface Registrable {}

class Product implements Registrable {


// Member variables
int product_id;
String product_name;
double product_cost;
int product_quantity;

// Static variable to count objects


private static int objectCount = 0;

// Default constructor
public Product() {
this.product_id = 0;
this.product_name = "N/A";
this.product_cost = 0.0;
this.product_quantity = 0;
objectCount++; // Increment count when an object is created
}

// Parameterized constructor
public Product(int id, String name, double cost, int quantity) {
this.product_id = id;
this.product_name = name;
this.product_cost = cost;
this.product_quantity = quantity;
objectCount++; // Increment count when an object is created
}

// Method to display product contents


public void display() {
System.out.println("\n--- Product Details ---");
System.out.println("ID: " + this.product_id);
System.out.println("Name: " + this.product_name);
System.out.println("Cost: $" + this.product_cost);
System.out.println("Quantity: " + this.product_quantity);
System.out.println("-----------------------");
}

// Static method to get the object count


public static void displayObjectCount() {
System.out.println("\nTotal number of Product objects created: " + objectCount);
}
}

public class MarkerInterfaceDemo {


public static void main(String[] args) {
// Create objects of the Product class
Product p1 = new Product(101, "Laptop", 1200.50, 10);
Product p2 = new Product(102, "Mouse", 25.00, 50);
Product p3 = new Product(); // Using default constructor

// Display the contents of each object


p1.display();
p2.display();
p3.display();

// Display the total object count


Product.displayObjectCount();

// Check if the Product class implements the marker interface


if (p1 instanceof Registrable) {
System.out.println("\nProduct class is a registrable entity.");
}
}
}
SLIP 3

1) Write a program to accept the array element and display in reverse order

Code:

import java.util.Scanner;

public class ReverseArray {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Get array size from user


System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();

// Create the array


int[] arr = new int[n];

// Accept array elements


System.out.println("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
System.out.print("Element " + (i + 1) + ": ");
arr[i] = scanner.nextInt();
}

// Display the array in reverse order


System.out.println("\nArray elements in reverse order:");
for (int i = n - 1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
System.out.println(); // For a new line at the end

scanner.close();
}
}
2) Write a Java program to create a Package “SY” which has a class SYMarks (members –
ComputerTotal, MathsTotal, and ElectronicsTotal). Create another package TY which has a
class TYMarks (members – Theory, Practicals). Create n objects of Student class (having
rollNumber, name, SYMarks and TYMarks). Add the marks of SY and TY computer subjects
and calculate the Grade (‘A’ for >= 70, ‘B’ for >= 60 ‘C’ for >= 50 , Pass Class for > =40 else
‘FAIL’) and display the result of the student in proper format.

Instructions:

1. Create a folder named StudentSystem.

2. Inside StudentSystem, create a folder named SY.

3. Inside SY, create the file SYMarks.java.

4. Inside StudentSystem, create a folder named TY.

5. Inside TY, create the file TYMarks.java.

6. Inside StudentSystem, create the main file StudentDemo.java.

7. Compile from the StudentSystem directory: javac SY/SYMarks.java TY/TYMarks.java


StudentDemo.java

8. Run from the StudentSystem directory: java StudentDemo

Code:

File 1: SY/SYMarks.java

package SY;
import java.util.Scanner;

public class SYMarks {


public int computerTotal;
public int mathsTotal;
public int electronicsTotal;

public void acceptSYMarks() {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter Computer Total Marks: ");
this.computerTotal = scanner.nextInt();
System.out.print("Enter Maths Total Marks: ");
this.mathsTotal = scanner.nextInt();
System.out.print("Enter Electronics Total Marks: ");
this.electronicsTotal = scanner.nextInt();
}
}
File 2: TY/TYMarks.java

package TY;
import java.util.Scanner;

public class TYMarks {


public int theory;
public int practicals;

public void acceptTYMarks() {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter Theory Marks (Computer): ");
this.theory = scanner.nextInt();
System.out.print("Enter Practicals Marks (Computer): ");
this.practicals = scanner.nextInt();
}
}

File 3: StudentDemo.java

import SY.SYMarks;
import TY.TYMarks;
import java.util.Scanner;

class Student {
int rollNumber;
String name;
SYMarks syMarks;
TYMarks tyMarks;

public Student(int rollNumber, String name) {


this.rollNumber = rollNumber;
this.name = name;
this.syMarks = new SYMarks();
this.tyMarks = new TYMarks();
}

public void acceptDetails() {


System.out.println("\nEntering SY Marks:");
syMarks.acceptSYMarks();
System.out.println("\nEntering TY Marks:");
tyMarks.acceptTYMarks();
}

public char calculateGrade() {


int totalComputerMarks = syMarks.computerTotal + tyMarks.theory + tyMarks.practicals;
// Assuming the total is out of 300 for calculation percentage.
// SY Comp (100), TY Theory (100), TY Practicals (100). Adjust if max marks are different.
double percentage = (totalComputerMarks / 300.0) * 100;

if (percentage >= 70) return 'A';


if (percentage >= 60) return 'B';
if (percentage >= 50) return 'C';
if (percentage >= 40) return 'P'; // Pass Class
return 'F'; // Fail
}

public void displayResult() {


System.out.println("\n--------------------------------");
System.out.println("Roll Number: " + rollNumber);
System.out.println("Name: " + name);
System.out.println("Final Computer Grade: " + getGradeDescription(calculateGrade()));
System.out.println("--------------------------------");
}

private String getGradeDescription(char grade) {


switch (grade) {
case 'A': return "A (>= 70%)";
case 'B': return "B (>= 60%)";
case 'C': return "C (>= 50%)";
case 'P': return "Pass Class (>= 40%)";
default: return "FAIL (< 40%)";
}
}
}

public class StudentDemo {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("How many students do you want to enter? ");
int n = scanner.nextInt();
scanner.nextLine(); // consume newline

Student[] students = new Student[n];

for (int i = 0; i < n; i++) {


System.out.println("\nEnter details for Student " + (i + 1) + ":");
System.out.print("Enter Roll Number: ");
int roll = scanner.nextInt();
scanner.nextLine(); // consume newline
System.out.print("Enter Name: ");
String name = scanner.nextLine();

students[i] = new Student(roll, name);


students[i].acceptDetails();
}

System.out.println("\n--- Student Results ---");


for (Student s : students) {
s.displayResult();
}

scanner.close();
}
}
SLIP 4

1) Create an employee class(id,name,deptname,salary). Define a default and parameterized


constructor. Use ‘this’ keyword to initialize instance variables. Keep a count of objects
created. Create objects using parameterized constructor and display the object count after
each object is created.(Use static member and method). Also display the contents of each
object.

Code:

public class Employee {


// Instance variables
int id;
String name;
String deptName;
double salary;

// Static variable to keep a count of objects created


private static int objectCount = 0;

// Default constructor
public Employee() {
this.id = 0;
this.name = "Unknown";
this.deptName = "Unassigned";
this.salary = 0.0;
objectCount++;
}

// Parameterized constructor using 'this' keyword


public Employee(int id, String name, String deptName, double salary) {
this.id = id;
this.name = name;
this.deptName = deptName;
this.salary = salary;
objectCount++; // Increment count when a new object is created
}

// Method to display employee details


public void display() {
System.out.println("\n--- Employee Details ---");
System.out.println("ID: " + this.id);
System.out.println("Name: " + this.name);
System.out.println("Department: " + this.deptName);
System.out.println("Salary: $" + this.salary);
System.out.println("------------------------");
}

// Static method to get the current object count


public static int getObjectCount() {
return objectCount;
}

public static void main(String[] args) {


System.out.println("Creating employees...");

// Create first object and display count


Employee emp1 = new Employee(101, "Alice", "IT", 75000);
System.out.println("Object count after creating emp1: " + Employee.getObjectCount());
emp1.display();

// Create second object and display count


Employee emp2 = new Employee(102, "Bob", "HR", 60000);
System.out.println("Object count after creating emp2: " + Employee.getObjectCount());
emp2.display();

// Create third object and display count


Employee emp3 = new Employee(103, "Charlie", "Finance", 82000);
System.out.println("Object count after creating emp3: " + Employee.getObjectCount());
emp3.display();
}
}

2) Q.2 Write a program to read book information (bookid, bookname, bookprice, bookqty) in
file “book.dat”. Write a menu driven program to perform the following operations using
Random access file: i. Search for a specific book by name. ii. Display all book and total cost

Code:

import java.io.*;
import java.util.Scanner;

public class BookManager {


// Each record has a fixed size for easier random access.
// bookId (int) = 4 bytes
// bookName (String) = 50 chars * 2 bytes/char = 100 bytes
// bookPrice (double) = 8 bytes
// bookQty (int) = 4 bytes
// TOTAL = 116 bytes per record
static final int RECORD_SIZE = 116;
static final String FILE_NAME = "book.dat";
public static void main(String[] args) {
// Pre-populate the file with some data for demonstration
addInitialData();

Scanner scanner = new Scanner(System.in);


int choice;

do {
System.out.println("\n--- Book Management Menu ---");
System.out.println("1. Search for a book by name");
System.out.println("2. Display all books and total cost");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
scanner.nextLine(); // Consume newline

switch (choice) {
case 1:
System.out.print("Enter the name of the book to search for: ");
String nameToSearch = scanner.nextLine();
searchBookByName(nameToSearch);
break;
case 2:
displayAllBooks();
break;
case 3:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 3);
scanner.close();
}

// Search for a specific book by name [cite: 42]


public static void searchBookByName(String name) {
try (RandomAccessFile raf = new RandomAccessFile(FILE_NAME, "r")) {
long fileLength = raf.length();
boolean found = false;
for (long pos = 0; pos < fileLength; pos += RECORD_SIZE) {
raf.seek(pos);
int id = raf.readInt();
String bookName = raf.readUTF();
double price = raf.readDouble();
int qty = raf.readInt();

if (bookName.trim().equalsIgnoreCase(name.trim())) {
System.out.println("\n--- Book Found ---");
System.out.println("ID: " + id);
System.out.println("Name: " + bookName.trim());
System.out.println("Price: $" + price);
System.out.println("Quantity: " + qty);
System.out.println("------------------");
found = true;
break; // Exit loop once found
}
}
if (!found) {
System.out.println("Book with name '" + name + "' not found.");
}
} catch (IOException e) {
System.err.println("Error searching for book: " + e.getMessage());
}
}

// Display all books and the total cost of all books [cite: 43]
public static void displayAllBooks() {
double totalCost = 0;
try (RandomAccessFile raf = new RandomAccessFile(FILE_NAME, "r")) {
long fileLength = raf.length();
if (fileLength == 0) {
System.out.println("No books in the file.");
return;
}
System.out.println("\n--- All Books ---");
for (long pos = 0; pos < fileLength; pos += RECORD_SIZE) {
raf.seek(pos);
System.out.println("ID: " + raf.readInt());
System.out.println("Name: " + raf.readUTF().trim());
double price = raf.readDouble();
System.out.println("Price: $" + price);
int qty = raf.readInt();
System.out.println("Quantity: " + qty);
System.out.println("-----------------");
totalCost += price * qty;
}
System.out.printf("Total cost of all books: $%.2f\n", totalCost);
} catch (IOException e) {
System.err.println("Error displaying books: " + e.getMessage());
}
}

// Helper method to write a fixed-size string


public static void writeFixedString(DataOutput out, String s, int size) throws IOException {
// RandomAccessFile doesn't have a fixed size string writer.
// We use writeUTF, but for true fixed-size records, one would typically
// convert the string to bytes and pad it. We'll use writeUTF for simplicity.
out.writeUTF(s);
}

// Helper method to add some initial data to the file


public static void addInitialData() {
try (RandomAccessFile raf = new RandomAccessFile(FILE_NAME, "rw")) {
// Clear the file first
raf.setLength(0);

// Book 1
raf.writeInt(1);
raf.writeUTF("The Hobbit");
raf.writeDouble(15.99);
raf.writeInt(10);

// Book 2
raf.writeInt(2);
raf.writeUTF("Java: The Complete Reference");
raf.writeDouble(55.50);
raf.writeInt(5);

// Book 3
raf.writeInt(3);
raf.writeUTF("A Tale of Two Cities");
raf.writeDouble(12.00);
raf.writeInt(8);

} catch (IOException e) {
// We are using a simplified version for RandomAccessFile with writeUTF.
// A true fixed-length record system would require padding strings to a fixed byte length.
// The provided solution is a common practical approach.
}
}
}
SLIP 5

1) Define Student class(roll_no, name, percentage) to create n objects of the Student class.
Accept details from the user for each object. Define a static method “sortStudent” which
sorts the array on the basis of percentage.

Code:

import java.util.Scanner;
import java.util.Arrays;
import java.util.Comparator;

class Student {
int roll_no;
String name;
double percentage;

public Student(int roll_no, String name, double percentage) {


this.roll_no = roll_no;
this.name = name;
this.percentage = percentage;
}

public void display() {


System.out.printf("Roll No: %-5d | Name: %-20s | Percentage: %.2f%%\n", roll_no, name,
percentage);
}

// Static method to sort the array of students by percentage [cite: 51]


public static void sortStudent(Student[] students) {
// Using Comparator to sort in descending order of percentage
Arrays.sort(students, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return Double.compare(s2.percentage, s1.percentage);
}
});
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of students: ");


int n = scanner.nextInt();

Student[] students = new Student[n];


// Accept details for each student [cite: 51]
for (int i = 0; i < n; i++) {
System.out.println("\nEnter details for student " + (i + 1) + ":");
System.out.print("Roll No: ");
int roll = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.print("Percentage: ");
double perc = scanner.nextDouble();
students[i] = new Student(roll, name, perc);
}

System.out.println("\n--- Students Before Sorting ---");


for (Student s : students) {
s.display();
}

// Sort the students


Student.sortStudent(students);

System.out.println("\n--- Students After Sorting (by Percentage) ---");


for (Student s : students) {
s.display();
}

scanner.close();
}
}
2) Define a class MyNumber having one private int data member. Write a default constructor
to initialize it to 0 and another constructor to initialize it to a value (Use this). Write
methods isNegative, isPositive, isZero, isOdd, isEven. Create an object in main. Use
command line arguments to pass a value to the object (Hint : convert string argument to
integer) and perform the above tests. Provide javadoc comments for all constructors and
methods and generate the html help file.

This program defines a

MyNumber class to perform various tests on an integer14141414. It initializes the number using a
command-line argument 15and includes Javadoc comments16.

Instructions:

1. Save the code as MyNumber.java.

2. Compile it: javac MyNumber.java

3. Run from the command line with an argument (e.g., java MyNumber 42 or java MyNumber -
7).

4. Generate Javadoc: javadoc MyNumber.java (This will create HTML documentation files).

Java

/**
* Represents a number and provides methods to check its properties.
* @author Gemini
* @version 1.0
*/
public class MyNumber {
/**
* The private integer data member.
*/
private int data;

/**
* Default constructor. Initializes the data member to 0. [cite: 53]
*/
public MyNumber() {
this.data = 0;
}

/**
* Parameterized constructor. Initializes the data member to a given value.
* Uses the 'this' keyword to distinguish instance variable from parameter. [cite: 53]
* @param data The integer value to initialize the object with.
*/
public MyNumber(int data) {
this.data = data;
}

/**
* Checks if the number is negative.
* @return true if the number is less than 0, false otherwise.
*/
public boolean isNegative() {
return this.data < 0;
}

/**
* Checks if the number is positive.
* @return true if the number is greater than 0, false otherwise.
*/
public boolean isPositive() {
return this.data > 0;
}

/**
* Checks if the number is zero.
* @return true if the number is equal to 0, false otherwise.
*/
public boolean isZero() {
return this.data == 0;
}

/**
* Checks if the number is odd.
* @return true if the number is not divisible by 2, false otherwise.
*/
public boolean isOdd() {
return this.data % 2 != 0;
}

/**
* Checks if the number is even.
* @return true if the number is divisible by 2, false otherwise.
*/
public boolean isEven() {
return this.data % 2 == 0;
}

public static void main(String[] args) {


// Check if a command-line argument is provided
if (args.length == 0) {
System.out.println("Usage: java MyNumber <integer>");
System.out.println("No argument provided. Using default value 0.");
MyNumber num = new MyNumber();
performTests(num);
return;
}

try {
// Convert string argument to integer [cite: 56]
int value = Integer.parseInt(args[0]);
MyNumber num = new MyNumber(value);
System.out.println("Testing number: " + value);
performTests(num);
} catch (NumberFormatException e) {
System.err.println("Error: The provided argument is not a valid integer.");
}
}

/**
* Helper method to perform and display all tests on a MyNumber object.
* @param num The MyNumber object to test.
*/
private static void performTests(MyNumber num) {
System.out.println("Is Positive? " + num.isPositive());
System.out.println("Is Negative? " + num.isNegative());
System.out.println("Is Zero? " + num.isZero());
System.out.println("Is Odd? " + num.isOdd());
System.out.println("Is Even? " + num.isEven());
}
}
SLIP 6

1) Write a java program to accept 5 numbers using command line arguments sort and display
them.

Code:

import java.util.Arrays;

public class SortCommandLine {


public static void main(String[] args) {
// Check if exactly 5 arguments are provided
if (args.length != 5) {
System.out.println("Please provide exactly 5 numbers as command-line arguments.");
return;
}

int[] numbers = new int[5];


try {
// Convert string arguments to integers
for (int i = 0; i < 5; i++) {
numbers[i] = Integer.parseInt(args[i]);
}
} catch (NumberFormatException e) {
System.err.println("Error: All arguments must be valid integers.");
return;
}

System.out.println("Original numbers: " + Arrays.toString(numbers));

// Sort the array


Arrays.sort(numbers);

System.out.println("Sorted numbers: " + Arrays.toString(numbers));


}
}
2) Write a java program to display the system date and time in various formats shown below:
Current date is : 31/08/2021 Current date is : 08-31-2021 Current date is : Tuesday August
31 2021 Current date and time is : Fri August 31 15:25:59 IST 2021 Current date and time is
: 31/08/21 15:25:59 PM +0530 Current time is : 15:25:59 Current week of year is : 35
Current week of month : 5 Current day of the year is : 243 Note: Use java.util.Date and
java.text.SimpleDateFormat class

Code:

import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class DateTimeFormatterDemo {


public static void main(String[] args) {
// Get the current date and time
Date currentDate = new Date();
Calendar calendar = Calendar.getInstance();

System.out.println("--- Displaying Date and Time in Various Formats ---");

// Format 1: 31/08/2021
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
System.out.println("Current date is: " + sdf1.format(currentDate));

// Format 2: 08-31-2021
SimpleDateFormat sdf2 = new SimpleDateFormat("MM-dd-yyyy");
System.out.println("Current date is: " + sdf2.format(currentDate));

// Format 3: Tuesday August 31 2021


SimpleDateFormat sdf3 = new SimpleDateFormat("EEEE MMMM dd yyyy");
System.out.println("Current date is: " + sdf3.format(currentDate));

// Format 4: Fri August 31 15:25:59 IST 2021


SimpleDateFormat sdf4 = new SimpleDateFormat("E MMMM dd HH:mm:ss z yyyy");
System.out.println("Current date and time is: " + sdf4.format(currentDate));

// Format 5: 31/08/21 15:25:59 PM +0530


SimpleDateFormat sdf5 = new SimpleDateFormat("dd/MM/yy hh:mm:ss a Z");
System.out.println("Current date and time is: " + sdf5.format(currentDate));

// Format 6: 15:25:59
SimpleDateFormat sdf6 = new SimpleDateFormat("HH:mm:ss");
System.out.println("Current time is: " + sdf6.format(currentDate));

System.out.println("\n--- Calendar Information ---");

// Current week of year


System.out.println("Current week of year is: " + calendar.get(Calendar.WEEK_OF_YEAR));
// Current week of month
System.out.println("Current week of month: " + calendar.get(Calendar.WEEK_OF_MONTH));

// Current day of the year


System.out.println("Current day of the year is: " + calendar.get(Calendar.DAY_OF_YEAR));
}
}
SLIP 7

1) Write a java program that take input as a person name in the format of first, middle and
last name and then print it in the form last, first and middle name, where in the middle
name first character is capital letter.

Code:

import java.util.Scanner;

public class NameFormatter {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter person's name (first middle last): ");


String fullName = scanner.nextLine();

// Split the name into parts


String[] nameParts = fullName.split(" ");

if (nameParts.length != 3) {
System.out.println("Invalid format. Please enter the name as 'first middle last'.");
} else {
String firstName = nameParts[0];
String middleName = nameParts[1];
String lastName = nameParts[2];

// Get the first character of the middle name and capitalize it


char middleInitial = Character.toUpperCase(middleName.charAt(0));

// Format the output string


String formattedName = lastName + ", " + firstName + " " + middleInitial + ".";

System.out.println("Formatted name: " + formattedName);


}

scanner.close();
}
}
2) Define class EmailId with members ,username and password. Define default and
parameterized constructors. Accept values from the command line Throw user defined
exceptions – “InvalidUsernameException” or “InvalidPasswordException” if the username
and password are invalid.

Code:

Instructions:

1. Save the code as EmailValidator.java.

2. Compile it: javac EmailValidator.java

3. Run with valid credentials: java EmailValidator admin admin123

4. Run with invalid username: java EmailValidator wronguser admin123

5. Run with invalid password: java EmailValidator admin wrongpass

// User-defined exception for invalid username


class InvalidUsernameException extends Exception {
public InvalidUsernameException(String message) {
super(message);
}
}

// User-defined exception for invalid password


class InvalidPasswordException extends Exception {
public InvalidPasswordException(String message) {
super(message);
}
}

class EmailId {
String username;
String password;

// Default constructor
public EmailId() {
this.username = "default";
this.password = "default";
}

// Parameterized constructor
public EmailId(String username, String password) {
this.username = username;
this.password = password;
}

// Method to validate credentials


public void validate() throws InvalidUsernameException, InvalidPasswordException {
// Simple validation logic for demonstration
// Correct username: "admin"
// Correct password: "admin123"
if (!this.username.equals("admin")) {
throw new InvalidUsernameException("Username '" + this.username + "' is invalid.");
}
if (!this.password.equals("admin123")) {
throw new InvalidPasswordException("The provided password is incorrect.");
}
System.out.println("Login Successful! ");
}
}

public class EmailValidator {


public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: java EmailValidator <username> <password>");
return;
}

String username = args[0];


String password = args[1];

EmailId credentials = new EmailId(username, password);

try {
System.out.println("Attempting to validate credentials...");
credentials.validate();
} catch (InvalidUsernameException e) {
System.err.println("Validation Error: " + e.getMessage());
} catch (InvalidPasswordException e) {
System.err.println("Validation Error: " + e.getMessage());
} finally {
System.out.println("Validation process finished.");
}
}
}
SLIP 8

1) Write a java program that take input as a person name in the format of first, middle and
last name and then print it in the form last, first and middle name, where in the middle
name first character is capital letter.

Code:

import java.util.Scanner;

public class NameFormatter {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter person's name (first middle last): ");


String fullName = scanner.nextLine();

// Split the name into parts


String[] nameParts = fullName.split(" ");

if (nameParts.length != 3) {
System.out.println("Invalid format. Please enter the name as 'first middle last'.");
} else {
String firstName = nameParts[0];
String middleName = nameParts[1];
String lastName = nameParts[2];

// Get the first character of the middle name and capitalize it


char middleInitial = Character.toUpperCase(middleName.charAt(0));

// Format the output string


String formattedName = lastName + ", " + firstName + " " + middleInitial + ".";

System.out.println("Formatted name: " + formattedName);


}

scanner.close();
}
}
2) Define a class MyDate (day, month, year) with methods to accept and display a MyDate
object. Accept date as dd, mm, yyyy. Throw user defined exception “InvalidDateException”
if the date is invalid. Examples of invalid dates : 03 15 2019, 31 6 2000, 29 2 2021

Code:

import java.util.Scanner;

// User-defined exception for invalid dates


class InvalidDateException extends Exception {
public InvalidDateException(String message) {
super(message);
}
}

class MyDate {
int day, month, year;

public void accept(int d, int m, int y) {


day = d;
month = m;
year = y;
}

public void display() {


System.out.println("Date is valid: " + day + "/" + month + "/" + year);
}

// Method to validate the date


public void validate() throws InvalidDateException {
if (month < 1 || month > 12) {
throw new InvalidDateException("Month is invalid (must be 1-12).");
}
if (day < 1 || day > 31) {
throw new InvalidDateException("Day is invalid (must be 1-31).");
}

// Check for months with 30 days


if ((month == 4 || month == 6 || month == 9 || month == 11) && day > 30) {
throw new InvalidDateException("Invalid date: Day cannot be 31 for month " + month + ".");
}

// Check for February and leap years


if (month == 2) {
boolean isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
if (isLeap && day > 29) {
throw new InvalidDateException("Invalid date: Day cannot be > 29 in a leap year for
February.");
}
if (!isLeap && day > 28) {
throw new InvalidDateException("Invalid date: Day cannot be > 28 in a non-leap year for
February.");
}
}
}
}

public class DateValidator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
MyDate date = new MyDate();

System.out.print("Enter date (dd mm yyyy): ");


int d = scanner.nextInt();
int m = scanner.nextInt();
int y = scanner.nextInt();

date.accept(d, m, y);

try {
date.validate();
date.display();
} catch (InvalidDateException e) {
System.err.println("Error: " + e.getMessage());
} finally {
scanner.close();
System.out.println("Date validation process complete.");
}
}
}
SLIP 9

1) Define a class CricketPlayer (name,no_of_innings,no_of_times_notout, totatruns,


bat_avg). Create an array of n player objects .Calculate the batting average for each player
using static method avg(). Define a static sort method which sorts the array on the basis of
average. Display the player details in sorted order.

Code:

import java.util.Scanner;
import java.util.Arrays;
import java.util.Comparator;

class CricketPlayer {
String name;
int no_of_innings;
int no_of_times_notout;
int total_runs;
double bat_avg;

public CricketPlayer(String name, int innings, int notout, int runs) {


this.name = name;
this.no_of_innings = innings;
this.no_of_times_notout = notout;
this.total_runs = runs;
// Batting average is calculated upon creation
this.bat_avg = avg(runs, innings, notout);
}

// Static method to calculate batting average [cite: 96]


public static double avg(int total_runs, int no_of_innings, int no_of_times_notout) {
int dismissals = no_of_innings - no_of_times_notout;
if (dismissals <= 0) {
// If the player has never been out, average is technically infinite.
// A common convention is to just show the runs. Or return 0 if no runs.
return total_runs > 0 ? (double)total_runs : 0.0;
}
return (double) total_runs / dismissals;
}

// Static method to sort players by batting average [cite: 97]


public static void sort(CricketPlayer[] players) {
Arrays.sort(players, Comparator.comparingDouble(p -> p.bat_avg));
}

public void display() {


System.out.printf("Name: %-15s | Innings: %-3d | Not Out: %-3d | Total Runs: %-5d | Avg:
%.2f\n",
name, no_of_innings, no_of_times_notout, total_runs, bat_avg);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of cricket players: ");
int n = scanner.nextInt();
scanner.nextLine(); // consume newline

CricketPlayer[] players = new CricketPlayer[n];

for (int i = 0; i < n; i++) {


System.out.println("\nEnter details for player " + (i + 1) + ":");
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.print("Number of Innings: ");
int innings = scanner.nextInt();
System.out.print("Number of Times Not Out: ");
int notout = scanner.nextInt();
System.out.print("Total Runs: ");
int runs = scanner.nextInt();
scanner.nextLine(); // consume newline

players[i] = new CricketPlayer(name, innings, notout, runs);


}

// Sort the players


CricketPlayer.sort(players);

System.out.println("\n--- Player Details (Sorted by Batting Average) ---");


// Display players in sorted order [cite: 98]
for (CricketPlayer player : players) {
player.display();
}

scanner.close();
}
}
2) Create the following GUI screen using appropriate layout managers. Accept the name, class
, hobbies of the user and apply the changes and display the selected options in a text box.

Code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class UserInfoGUI extends JFrame {


private JTextField nameField, classField;
private JCheckBox musicCheckBox, sportsCheckBox, readingCheckBox;
private JTextArea displayArea;
private JButton submitButton;

public UserInfoGUI() {
// Frame setup
setTitle("User Information");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout(10, 10));

// Input Panel
JPanel inputPanel = new JPanel(new GridLayout(4, 2, 5, 5));
inputPanel.setBorder(BorderFactory.createTitledBorder("Enter Your Details"));

inputPanel.add(new JLabel("Name:"));
nameField = new JTextField();
inputPanel.add(nameField);

inputPanel.add(new JLabel("Class:"));
classField = new JTextField();
inputPanel.add(classField);

inputPanel.add(new JLabel("Hobbies:"));
JPanel hobbiesPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
musicCheckBox = new JCheckBox("Music");
sportsCheckBox = new JCheckBox("Sports");
readingCheckBox = new JCheckBox("Reading");
hobbiesPanel.add(musicCheckBox);
hobbiesPanel.add(sportsCheckBox);
hobbiesPanel.add(readingCheckBox);
inputPanel.add(hobbiesPanel);

// Submit Button
submitButton = new JButton("Submit");
inputPanel.add(new JLabel()); // Placeholder
inputPanel.add(submitButton);
// Display Area
displayArea = new JTextArea(10, 30);
displayArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(displayArea);
scrollPane.setBorder(BorderFactory.createTitledBorder("Submitted Information"));

// Add panels to frame


add(inputPanel, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);

// Action Listener for the submit button


submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Get user input
String name = nameField.getText();
String className = classField.getText();
StringBuilder hobbies = new StringBuilder();
if (musicCheckBox.isSelected()) hobbies.append("Music, ");
if (sportsCheckBox.isSelected()) hobbies.append("Sports, ");
if (readingCheckBox.isSelected()) hobbies.append("Reading, ");

// Remove trailing comma and space


String selectedHobbies = hobbies.length() > 0 ?
hobbies.substring(0, hobbies.length() - 2) : "None";

// Display the information


String result = "Name: " + name + "\n"
+ "Class: " + className + "\n"
+ "Hobbies: " + selectedHobbies;
displayArea.setText(result);
}
});

// Make the frame visible


setVisible(true);
}

public static void main(String[] args) {


// Run the GUI on the Event Dispatch Thread
SwingUtilities.invokeLater(() -> new UserInfoGUI());
}
}
SLIP 10

1) Write a program for multilevel inheritance such that country is inherited from continent.
State is inherited from country. Display the place, state, country and continent.

Code:

// Base class
class Continent {
String continentName;

public Continent(String continentName) {


this.continentName = continentName;
}
}

// Intermediate class inheriting from Continent


class Country extends Continent {
String countryName;

public Country(String continentName, String countryName) {


super(continentName); // Call parent class constructor
this.countryName = countryName;
}
}

// Derived class inheriting from Country


class State extends Country {
String stateName;
String placeName;

public State(String continentName, String countryName, String stateName, String placeName) {


super(continentName, countryName); // Call parent class constructor
this.stateName = stateName;
this.placeName = placeName;
}

public void display() {


System.out.println("--- Location Details ---");
System.out.println("Place: " + placeName);
System.out.println("State: " + stateName);
System.out.println("Country: " + countryName);
System.out.println("Continent: " + continentName);
System.out.println("------------------------");
}
}
public class LocationDemo {
public static void main(String[] args) {
// Create an object of the most derived class
State location = new State("Asia", "India", "Maharashtra", "Pune");

// Display all details


location.display();
}
}

2) Write a Java program to design a screen using Awt that will take a user name and
password. If the user name and password are not same, raise an Exception with
appropriate message. User can have 3 login chances only. Use clear button to clear the
TextFields.

Code:

import java.awt.*;
import java.awt.event.*;

public class LoginScreen extends Frame implements ActionListener {


private TextField userField, passField;
private Button loginButton, clearButton;
private Label messageLabel;
private int loginAttempts = 0;
private static final int MAX_ATTEMPTS = 3;

public LoginScreen() {
// Frame setup
setTitle("Login");
setSize(400, 200);
setLayout(new GridLayout(4, 2, 10, 10));

// Add components
add(new Label("Username:"));
userField = new TextField();
add(userField);

add(new Label("Password:"));
passField = new TextField();
passField.setEchoChar('*'); // Mask password
add(passField);

loginButton = new Button("Login");


clearButton = new Button("Clear");
add(loginButton);
add(clearButton);

messageLabel = new Label("You have " + MAX_ATTEMPTS + " attempts remaining.");


add(messageLabel);

// Add action listeners


loginButton.addActionListener(this);
clearButton.addActionListener(this);

// Window listener to handle closing the frame


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});

setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) {
handleLogin();
} else if (e.getSource() == clearButton) {
handleClear();
}
}

private void handleLogin() {


String username = userField.getText();
String password = passField.getText();

try {
// In a real app, you'd check against a database.
// Here we use a simple check for demonstration.
if (!username.equals(password)) {
loginAttempts++;
int remaining = MAX_ATTEMPTS - loginAttempts;
messageLabel.setText("Incorrect. " + remaining + " attempts left.");
messageLabel.setForeground(Color.RED);

if (loginAttempts >= MAX_ATTEMPTS) {


messageLabel.setText("Login failed. No attempts left.");
loginButton.setEnabled(false);
userField.setEditable(false);
passField.setEditable(false);
}
throw new Exception("Username and Password do not match.");
} else {
messageLabel.setText("Login Successful!");
messageLabel.setForeground(Color.GREEN);
loginButton.setEnabled(false); // Disable after successful login
}
} catch (Exception ex) {
// The message is already updated in the label.
// We can print to console for debugging if needed.
System.err.println(ex.getMessage());
}
}

private void handleClear() {


userField.setText("");
passField.setText("");
userField.requestFocus(); // Set focus back to the username field
}

public static void main(String[] args) {


new LoginScreen();
}
}
SLIP 11

1) Define an abstract class Staff with protected members id and name. Define a
parameterized constructor. Define one subclass OfficeStaff with member department.
Create n objects of OfficeStaff and display all details.

Code:

import java.util.Scanner;

// Abstract base class with protected members and a parameterized constructor


abstract class Staff {
protected int id;
protected String name;

public Staff(int id, String name) {


this.id = id;
this.name = name;
}

abstract void display();


}

// Subclass inheriting from Staff


class OfficeStaff extends Staff {
private String department;

public OfficeStaff(int id, String name, String department) {


super(id, name); // Call the constructor of the abstract superclass
this.department = department;
}

@Override
void display() {
System.out.println("--------------------");
System.out.println("Staff ID: " + id);
System.out.println("Staff Name: " + name);
System.out.println("Department: " + department);
System.out.println("--------------------");
}
}

public class StaffDemo {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of Office Staff members: ");
int n = scanner.nextInt();
scanner.nextLine(); // Consume newline

OfficeStaff[] staffArray = new OfficeStaff[n];

// Create n objects of OfficeStaff


for (int i = 0; i < n; i++) {
System.out.println("\nEnter details for staff member " + (i + 1) + ":");
System.out.print("ID: ");
int id = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.print("Department: ");
String dept = scanner.nextLine();
staffArray[i] = new OfficeStaff(id, name, dept);
}

System.out.println("\n--- All Office Staff Details ---");


// Display all details
for (OfficeStaff staff : staffArray) {
staff.display();
}

scanner.close();
}
}
2) Define a class MyNumber having one private int data member. Write a default constructor
to initialize it to 0 and another constructor to initialize it to a value (Use this). Write
methods isNegative, isPositive, isZero, isOdd, isEven. Create an object in main. Use
command line arguments to pass a value to the object (Hint : convert string argument to
integer) and perform the above tests. Provide javadoc comments for all constructors and
methods and generate the html help file.

Code:

Instructions:

1. Save the code as MyNumber.java.

2. Compile it: javac MyNumber.java

3. Run from the command line with an argument (e.g., java MyNumber -10 or java MyNumber
15).

4. Generate Javadoc: javadoc MyNumber.java (This will create HTML documentation files).

Java

/**
* Represents a number and provides methods to check its properties.
* @author Gemini
* @version 1.0
*/
public class MyNumber {
/**
* The private integer data member.
*/
private int data;

/**
* Default constructor. Initializes the data member to 0. [cite: 124]
*/
public MyNumber() {
this.data = 0;
}

/**
* Parameterized constructor. Initializes the data member to a given value.
* Uses the 'this' keyword to distinguish instance variable from parameter. [cite: 124]
* @param data The integer value to initialize the object with.
*/
public MyNumber(int data) {
this.data = data;
}

/**
* Checks if the number is negative.
* @return true if the number is less than 0, false otherwise.
*/
public boolean isNegative() {
return this.data < 0;
}

/**
* Checks if the number is positive.
* @return true if the number is greater than 0, false otherwise.
*/
public boolean isPositive() {
return this.data > 0;
}

/**
* Checks if the number is zero.
* @return true if the number is equal to 0, false otherwise.
*/
public boolean isZero() {
return this.data == 0;
}

/**
* Checks if the number is odd.
* @return true if the number is not divisible by 2, false otherwise.
*/
public boolean isOdd() {
return this.data % 2 != 0;
}

/**
* Checks if the number is even.
* @return true if the number is divisible by 2, false otherwise.
*/
public boolean isEven() {
return this.data % 2 == 0;
}

public static void main(String[] args) {


// Check if a command-line argument is provided
if (args.length == 0) {
System.out.println("Usage: java MyNumber <integer>");
System.out.println("No argument provided. Using default value 0.");
MyNumber num = new MyNumber();
performTests(num);
return;
}

try {
// Convert string argument to integer [cite: 127]
int value = Integer.parseInt(args[0]);
MyNumber num = new MyNumber(value);
System.out.println("Testing number: " + value);
performTests(num);
} catch (NumberFormatException e) {
System.err.println("Error: The provided argument is not a valid integer.");
}
}

/**
* Helper method to perform and display all tests on a MyNumber object.
* @param num The MyNumber object to test.
*/
private static void performTests(MyNumber num) {
System.out.println("Is Positive? " + num.isPositive());
System.out.println("Is Negative? " + num.isNegative());
System.out.println("Is Zero? " + num.isZero());
System.out.println("Is Odd? " + num.isOdd());
System.out.println("Is Even? " + num.isEven());
}
}
SLIP 12

1) Define an interface “Operation” which has methods area(),volume().Define a constant PI


having a value 3.142.Create a class cylinder which implements this interface (members –
radius, height) Create one object and calculate the area and volume.

Code:

import java.util.Scanner;

// Define the interface "Operation" [cite: 134]


interface Operation {
// Constant PI
double PI = 3.142;

// Abstract methods
void area();
void volume();
}

// Create a class Cylinder that implements the interface


class Cylinder implements Operation {
double radius;
double height;

public Cylinder(double radius, double height) {


this.radius = radius;
this.height = height;
}

// Implement the area method for a cylinder


// Total Surface Area = 2 * PI * r * (r + h)
@Override
public void area() {
double surfaceArea = 2 * PI * radius * (radius + height);
System.out.printf("Surface Area of the cylinder is: %.3f\n", surfaceArea);
}

// Implement the volume method for a cylinder


// Volume = PI * r^2 * h
@Override
public void volume() {
double vol = PI * radius * radius * height;
System.out.printf("Volume of the cylinder is: %.3f\n", vol);
}
}

public class InterfaceDemo {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the radius of the cylinder: ");


double r = scanner.nextDouble();
System.out.print("Enter the height of the cylinder: ");
double h = scanner.nextDouble();

// Create one object and calculate the area and volume


Cylinder myCylinder = new Cylinder(r, h);
myCylinder.area();
myCylinder.volume();

scanner.close();
}
}
2) Write a Java program to create a Package “SY” which has a class SYMarks (members –
ComputerTotal, MathsTotal, and ElectronicsTotal). Create another package TY which has a
class TYMarks (members – Theory, Practicals). Create n objects of Student class (having
rollNumber, name, SYMarks and TYMarks). Add the marks of SY and TY computer subjects
and calculate the Grade (‘A’ for >= 70, ‘B’ for >= 60 ‘C’ for >= 50 , Pass Class for > =40 else
‘FAIL’) and display the result of the student in proper format.

Code:

File 1: SY/SYMarks.java

package SY;
import java.util.Scanner;

public class SYMarks {


public int computerTotal;
public int mathsTotal;
public int electronicsTotal;

public void acceptSYMarks() {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter Computer Total Marks: ");
this.computerTotal = scanner.nextInt();
System.out.print("Enter Maths Total Marks: ");
this.mathsTotal = scanner.nextInt();
System.out.print("Enter Electronics Total Marks: ");
this.electronicsTotal = scanner.nextInt();
}
}

File 2: TY/TYMarks.java

package TY;
import java.util.Scanner;

public class TYMarks {


public int theory;
public int practicals;

public void acceptTYMarks() {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter Theory Marks (Computer): ");
this.theory = scanner.nextInt();
System.out.print("Enter Practicals Marks (Computer): ");
this.practicals = scanner.nextInt();
}
}
File 3: StudentDemo.java

import SY.SYMarks;
import TY.TYMarks;
import java.util.Scanner;

class Student {
int rollNumber;
String name;
SYMarks syMarks;
TYMarks tyMarks;

public Student(int rollNumber, String name) {


this.rollNumber = rollNumber;
this.name = name;
this.syMarks = new SYMarks();
this.tyMarks = new TYMarks();
}

public void acceptDetails() {


System.out.println("\nEntering SY Marks:");
syMarks.acceptSYMarks();
System.out.println("\nEntering TY Marks:");
tyMarks.acceptTYMarks();
}

public char calculateGrade() {


int totalComputerMarks = syMarks.computerTotal + tyMarks.theory + tyMarks.practicals;
// Assuming the total is out of 300 for calculation percentage.
double percentage = (totalComputerMarks / 300.0) * 100;

if (percentage >= 70) return 'A';


if (percentage >= 60) return 'B';
if (percentage >= 50) return 'C';
if (percentage >= 40) return 'P'; // Pass Class
return 'F'; // Fail
}

public void displayResult() {


System.out.println("\n--------------------------------");
System.out.println("Roll Number: " + rollNumber);
System.out.println("Name: " + name);
System.out.println("Final Computer Grade: " + getGradeDescription(calculateGrade()));
System.out.println("--------------------------------");
}
private String getGradeDescription(char grade) {
switch (grade) {
case 'A': return "A (>= 70%)";
case 'B': return "B (>= 60%)";
case 'C': return "C (>= 50%)";
case 'P': return "Pass Class (>= 40%)";
default: return "FAIL (< 40%)";
}
}
}

public class StudentDemo {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("How many students do you want to enter? ");
int n = scanner.nextInt();
scanner.nextLine(); // consume newline

Student[] students = new Student[n];

for (int i = 0; i < n; i++) {


System.out.println("\nEnter details for Student " + (i + 1) + ":");
System.out.print("Enter Roll Number: ");
int roll = scanner.nextInt();
scanner.nextLine(); // consume newline
System.out.print("Enter Name: ");
String name = scanner.nextLine();

students[i] = new Student(roll, name);


students[i].acceptDetails();
}

System.out.println("\n--- Student Results ---");


for (Student s : students) {
s.displayResult();
}

scanner.close();
}
}
SLIP 13

1) Write a program to find the cube of given number using function interface.

Code:

import java.util.Scanner;
import java.util.function.Function;

public class CubeCalculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Define a lambda expression for the Function interface to calculate the cube.
// It takes an Integer as input and returns an Integer.
Function<Integer, Integer> cubeFunction = number -> number * number * number;

// Get input from the user


System.out.print("Enter a number to find its cube: ");
int inputNumber = scanner.nextInt();

// Apply the function to the input number


int result = cubeFunction.apply(inputNumber);

// Display the result


System.out.println("The cube of " + inputNumber + " is: " + result);

scanner.close();
}
}
2) Define a class CricketPlayer (name,no_of_innings,no_of_times_notout, totatruns,
bat_avg). Create an array of n player objects .Calculate the batting average for each player
using static method avg(). Define a static sort method which sorts the array on the basis of
average. Display the player details in sorted order.

Code:

import java.util.Scanner;
import java.util.Arrays;
import java.util.Comparator;

class CricketPlayer {
String name;
int no_of_innings;
int no_of_times_notout;
int total_runs;
double bat_avg;

public CricketPlayer(String name, int innings, int notout, int runs) {


this.name = name;
this.no_of_innings = innings;
this.no_of_times_notout = notout;
this.total_runs = runs;
// Batting average is calculated upon creation
this.bat_avg = avg(runs, innings, notout);
}

// Static method to calculate batting average [cite: 149]


public static double avg(int total_runs, int no_of_innings, int no_of_times_notout) {
int dismissals = no_of_innings - no_of_times_notout;
if (dismissals <= 0) {
return total_runs > 0 ? (double)total_runs : 0.0;
}
return (double) total_runs / dismissals;
}

// Static method to sort players by batting average [cite: 150]


public static void sort(CricketPlayer[] players) {
Arrays.sort(players, Comparator.comparingDouble(p -> p.bat_avg));
}

public void display() {


System.out.printf("Name: %-15s | Innings: %-3d | Not Out: %-3d | Total Runs: %-5d | Avg:
%.2f\n",
name, no_of_innings, no_of_times_notout, total_runs, bat_avg);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of cricket players: ");
int n = scanner.nextInt();
scanner.nextLine(); // consume newline

CricketPlayer[] players = new CricketPlayer[n];

for (int i = 0; i < n; i++) {


System.out.println("\nEnter details for player " + (i + 1) + ":");
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.print("Number of Innings: ");
int innings = scanner.nextInt();
System.out.print("Number of Times Not Out: ");
int notout = scanner.nextInt();
System.out.print("Total Runs: ");
int runs = scanner.nextInt();
scanner.nextLine(); // consume newline

players[i] = new CricketPlayer(name, innings, notout, runs);


}

// Sort the players


CricketPlayer.sort(players);

System.out.println("\n--- Player Details (Sorted by Batting Average) ---");


// Display players in sorted order [cite: 151]
for (CricketPlayer player : players) {
player.display();
}

scanner.close();
}
}
SLIP 14

1) Define a class patient (patient_name, patient_age,


patient_oxy_level,patient_HRCT_report). Create an object of patient. Handle appropriate
exception while patient oxygen level less than 95% and HRCT scan report greater than 10,
then throw user defined Exception “Patient is Covid Positive(+) and Need to Hospitalized”
otherwise display its information.

Code:

import java.util.Scanner;

// User-defined exception for COVID-positive patients needing hospitalization


class CovidPositiveException extends Exception {
public CovidPositiveException(String message) {
super(message);
}
}

class Patient {
String patient_name;
int patient_age;
double patient_oxy_level;
int patient_HRCT_report;

public Patient(String name, int age, double oxy, int hrct) {


this.patient_name = name;
this.patient_age = age;
this.patient_oxy_level = oxy;
this.patient_HRCT_report = hrct;
}

public void diagnose() throws CovidPositiveException {


if (this.patient_oxy_level < 95 && this.patient_HRCT_report > 10) {
throw new CovidPositiveException("Patient is Covid Positive(+) and Needs to be
Hospitalized.");
}
}

public void display() {


System.out.println("\n--- Patient Information ---");
System.out.println("Name: " + this.patient_name);
System.out.println("Age: " + this.patient_age);
System.out.println("Oxygen Level: " + this.patient_oxy_level + "%");
System.out.println("HRCT Report Score: " + this.patient_HRCT_report);
System.out.println("Diagnosis: Patient seems stable.");
System.out.println("---------------------------");
}
}

public class PatientDiagnosis {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter Patient Details:");


System.out.print("Name: ");
String name = scanner.nextLine();
System.out.print("Age: ");
int age = scanner.nextInt();
System.out.print("Oxygen Level (%): ");
double oxy = scanner.nextDouble();
System.out.print("HRCT Report Score: ");
int hrct = scanner.nextInt();

Patient patient = new Patient(name, age, oxy, hrct);

try {
patient.diagnose();
// If no exception is thrown, display normal information
patient.display();
} catch (CovidPositiveException e) {
System.err.println("\n!!! ALERT !!!");
System.err.println("Error: " + e.getMessage());
System.err.println("!!!!!!!!!!!!!!!!");
} finally {
scanner.close();
System.out.println("\nDiagnosis process complete.");
}
}
}

2) Create an abstract class “order” having members id,description.Create two subclasses


“Purchase Order” and “Sales Order” having members customer name and Vendor name
respectively.Define methods accept and display in all cases. Create 3 objects each of
Purchase Order and Sales Order and accept and display details.

Code:

import java.util.Scanner;

// Abstract base class [cite: 160]


abstract class Order {
int id;
String description;

// Abstract methods to be implemented by subclasses


abstract void accept();
abstract void display();
}

// Subclass for Purchase Orders [cite: 161]


class PurchaseOrder extends Order {
String customerName;

@Override
void accept() {
Scanner scanner = new Scanner(System.in);
System.out.println("\nEnter Purchase Order Details:");
System.out.print("Enter ID: ");
id = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.print("Enter Description: ");
description = scanner.nextLine();
System.out.print("Enter Customer Name: ");
customerName = scanner.nextLine();
}

@Override
void display() {
System.out.println("\n--- Purchase Order ---");
System.out.println("ID: " + id);
System.out.println("Description: " + description);
System.out.println("Customer Name: " + customerName);
System.out.println("----------------------");
}
}

// Subclass for Sales Orders [cite: 161]


class SalesOrder extends Order {
String vendorName;

@Override
void accept() {
Scanner scanner = new Scanner(System.in);
System.out.println("\nEnter Sales Order Details:");
System.out.print("Enter ID: ");
id = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.print("Enter Description: ");
description = scanner.nextLine();
System.out.print("Enter Vendor Name: ");
vendorName = scanner.nextLine();
}

@Override
void display() {
System.out.println("\n--- Sales Order ---");
System.out.println("ID: " + id);
System.out.println("Description: " + description);
System.out.println("Vendor Name: " + vendorName);
System.out.println("-------------------");
}
}

public class OrderDemo {


public static void main(String[] args) {
// Create 3 PurchaseOrder objects
PurchaseOrder[] pOrders = new PurchaseOrder[3];
for (int i = 0; i < 3; i++) {
System.out.println("\nEntering details for Purchase Order " + (i + 1));
pOrders[i] = new PurchaseOrder();
pOrders[i].accept();
}

// Create 3 SalesOrder objects


SalesOrder[] sOrders = new SalesOrder[3];
for (int i = 0; i < 3; i++) {
System.out.println("\nEntering details for Sales Order " + (i + 1));
sOrders[i] = new SalesOrder();
sOrders[i].accept();
}

// Display all order details


System.out.println("\n--- All Order Details ---");
for (PurchaseOrder po : pOrders) {
po.display();
}
for (SalesOrder so : sOrders) {
so.display();
}
}
}
SLIP 15

1) Write a program to read a text file “sample.txt” and display the contents of a file in reverse
order and also original contents change the case (display in upper case).

Code:

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class FileManipulator {


public static void main(String[] args) {
String fileName = "sample.txt";
List<String> lines = new ArrayList<>();

// Step 1: Read the file and store its lines


try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String currentLine;
while ((currentLine = reader.readLine()) != null) {
lines.add(currentLine);
}
} catch (FileNotFoundException e) {
System.err.println("Error: The file '" + fileName + "' was not found.");
return;
} catch (IOException e) {
System.err.println("Error reading the file: " + e.getMessage());
return;
}

// Step 2: Display contents in reverse order


System.out.println("--- File Contents in Reverse Order ---");
for (int i = lines.size() - 1; i >= 0; i--) {
System.out.println(lines.get(i));
}

// Step 3: Display original contents in uppercase


System.out.println("\n--- Original Contents in Uppercase ---");
for (String line : lines) {
System.out.println(line.toUpperCase());
}
}
}
2) Write a program to using marker interface create a class product(product_id,
product_name, product_cost, product_quantity) define a default and parameterized
constructor. Create objects of class product and display the contents of each object and
Also display the object count.

Code:

// A marker interface has no methods or constants. It provides run-time type information.


interface Registrable {}

class Product implements Registrable {


// Member variables
int product_id;
String product_name;
double product_cost;
int product_quantity;

// Static variable to count objects


private static int objectCount = 0;

// Default constructor
public Product() {
this.product_id = 0;
this.product_name = "N/A";
this.product_cost = 0.0;
this.product_quantity = 0;
objectCount++;
}

// Parameterized constructor
public Product(int id, String name, double cost, int quantity) {
this.product_id = id;
this.product_name = name;
this.product_cost = cost;
this.product_quantity = quantity;
objectCount++;
}

// Method to display product contents


public void display() {
System.out.println("\n--- Product Details ---");
System.out.println("ID: " + this.product_id);
System.out.println("Name: " + this.product_name);
System.out.println("Cost: $" + this.product_cost);
System.out.println("Quantity: " + this.product_quantity);
System.out.println("-----------------------");
}

// Static method to get the object count


public static void displayObjectCount() {
System.out.println("\nTotal number of Product objects created: " + objectCount);
}
}

public class MarkerInterfaceDemo {


public static void main(String[] args) {
// Create objects of the Product class
Product p1 = new Product(101, "Keyboard", 75.00, 30);
Product p2 = new Product(102, "Webcam", 45.50, 25);
Product p3 = new Product();

// Display the contents of each object


p1.display();
p2.display();
p3.display();

// Display the total object count


Product.displayObjectCount();
}
}
SLIP 16

1) Accept the names of two files and copy the contents of the first to the second. First file
having Book name and Author name in file. Second file having the contents of First file and
also add the comment ‘end of file’ at the end.

Code:

import java.io.*;
import java.util.Scanner;

public class FileCopier {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the source file name: ");


String sourceFileName = scanner.nextLine();
System.out.print("Enter the destination file name: ");
String destFileName = scanner.nextLine();

try (BufferedReader reader = new BufferedReader(new FileReader(sourceFileName));


BufferedWriter writer = new BufferedWriter(new FileWriter(destFileName))) {

String line;
// Read from the first file and write to the second
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}

writer.write("\n--- end of file ---");

System.out.println("File copied successfully from '" + sourceFileName + "' to '" + destFileName


+ "'.");

} catch (FileNotFoundException e) {
System.err.println("Error: Source file '" + sourceFileName + "' not found.");
} catch (IOException e) {
System.err.println("An error occurred during file operation: " + e.getMessage());
} finally {
scanner.close();
}
}
}
2) Write a program to read book information (bookid, bookname, bookprice, bookqty) in file
“book.dat”. Write a menu driven program to perform the following operations using
Random access file: i. Search for a specific book by name. ii. Display all book and total cost

Code:

import java.io.*;
import java.util.Scanner;

public class BookManager {


static final String FILE_NAME = "book.dat";

public static void main(String[] args) {


addInitialData(); // Helper to pre-populate the file

Scanner scanner = new Scanner(System.in);


int choice;

do {
System.out.println("\n--- Book Management Menu ---");
System.out.println("1. Search for a book by name");
System.out.println("2. Display all books and total cost");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
scanner.nextLine(); // Consume newline

switch (choice) {
case 1:
System.out.print("Enter the name of the book to search for: ");
String nameToSearch = scanner.nextLine();
searchBookByName(nameToSearch);
break;
case 2:
displayAllBooks();
break;
case 3:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 3);
scanner.close();
}

// Search for a specific book by name [cite: 186]


public static void searchBookByName(String name) {
try (RandomAccessFile raf = new RandomAccessFile(FILE_NAME, "r")) {
boolean found = false;
while (raf.getFilePointer() < raf.length()) {
int id = raf.readInt();
String bookName = raf.readUTF();
double price = raf.readDouble();
int qty = raf.readInt();

if (bookName.trim().equalsIgnoreCase(name.trim())) {
System.out.println("\n--- Book Found ---");
System.out.println("ID: " + id + ", Name: " + bookName.trim() +
", Price: $" + price + ", Quantity: " + qty);
found = true;
break;
}
}
if (!found) {
System.out.println("Book with name '" + name + "' not found.");
}
} catch (IOException e) {
System.err.println("Error searching for book: " + e.getMessage());
}
}

// Display all books and the total cost of all books [cite: 187]
public static void displayAllBooks() {
double totalCost = 0;
try (RandomAccessFile raf = new RandomAccessFile(FILE_NAME, "r")) {
if (raf.length() == 0) {
System.out.println("No books in the file.");
return;
}
System.out.println("\n--- All Books ---");
while (raf.getFilePointer() < raf.length()) {
int id = raf.readInt();
String name = raf.readUTF();
double price = raf.readDouble();
int qty = raf.readInt();

System.out.println("ID: " + id + ", Name: " + name.trim() +


", Price: $" + price + ", Quantity: " + qty);
totalCost += price * qty;
}
System.out.printf("\nTotal cost of all books: $%.2f\n", totalCost);
} catch (IOException e) {
System.err.println("Error displaying books: " + e.getMessage());
}
}
// Helper method to add some initial data to the file
public static void addInitialData() {
try (RandomAccessFile raf = new RandomAccessFile(FILE_NAME, "rw")) {
raf.setLength(0); // Clear the file
// Book 1
raf.writeInt(1); raf.writeUTF("Clean Code"); raf.writeDouble(45.99); raf.writeInt(10);
// Book 2
raf.writeInt(2); raf.writeUTF("Effective Java"); raf.writeDouble(50.00); raf.writeInt(7);
// Book 3
raf.writeInt(3); raf.writeUTF("Design Patterns"); raf.writeDouble(65.25); raf.writeInt(5);
} catch (IOException e) {
System.err.println("Error initializing data: " + e.getMessage());
}
}
}
SLIP 17

1) Write a java program that works as a simple calculator. Use a grid layout to arrange buttons
for the digits and for the +, -, *, % operations. Add a text field to display the result.

Code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SimpleCalculator extends JFrame implements ActionListener {


private JTextField displayField;
private String operator = "";
private double operand1 = 0;
private boolean isOperatorClicked = false;

public SimpleCalculator() {
// Frame setup
setTitle("Simple Calculator");
setSize(400, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

// Display field [cite: 197]


displayField = new JTextField();
displayField.setEditable(false);
displayField.setFont(new Font("Arial", Font.BOLD, 24));
displayField.setHorizontalAlignment(JTextField.RIGHT);
add(displayField, BorderLayout.NORTH);

// Button panel with Grid Layout [cite: 196]


JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 5, 5));

String[] buttonLabels = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"C", "0", "=", "+"
};

for (String label : buttonLabels) {


JButton button = new JButton(label);
button.setFont(new Font("Arial", Font.BOLD, 20));
button.addActionListener(this);
buttonPanel.add(button);
}

add(buttonPanel, BorderLayout.CENTER);
setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();

if ("0123456789".contains(command)) {
if (isOperatorClicked) {
displayField.setText(command);
isOperatorClicked = false;
} else {
displayField.setText(displayField.getText() + command);
}
} else if ("+-*/".contains(command)) {
operand1 = Double.parseDouble(displayField.getText());
operator = command;
isOperatorClicked = true;
} else if ("=".equals(command)) {
double operand2 = Double.parseDouble(displayField.getText());
double result = 0;
switch (operator) {
case "+": result = operand1 + operand2; break;
case "-": result = operand1 - operand2; break;
case "*": result = operand1 * operand2; break;
case "/":
if (operand2 != 0) {
result = operand1 / operand2;
} else {
displayField.setText("Error");
return;
}
break;
}
displayField.setText(String.valueOf(result));
isOperatorClicked = true;
} else if ("C".equals(command)) {
displayField.setText("");
operand1 = 0;
operator = "";
isOperatorClicked = false;
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(SimpleCalculator::new);
}
}

2) Define a class MyDate (day, month, year) with methods to accept and display a MyDate
object. Accept date as dd, mm, yyyy. Throw user defined exception “InvalidDateException”
if the date is invalid. Examples of invalid dates : 03 15 2019, 31 6 2000, 29 2 2021

Code:

import java.util.Scanner;

// User-defined exception for invalid dates


class InvalidDateException extends Exception {
public InvalidDateException(String message) {
super(message);
}
}

class MyDate {
int day, month, year;

public void accept(int d, int m, int y) {


day = d;
month = m;
year = y;
}

public void display() {


System.out.println("Date is valid: " + day + "/" + month + "/" + year);
}

// Method to validate the date


public void validate() throws InvalidDateException {
if (month < 1 || month > 12) throw new InvalidDateException("Month is invalid.");
if (day < 1 || day > 31) throw new InvalidDateException("Day is invalid.");
if ((month == 4 || month == 6 || month == 9 || month == 11) && day > 30) throw new
InvalidDateException("Invalid date for this month.");
if (month == 2) {
boolean isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
if ((isLeap && day > 29) || (!isLeap && day > 28)) throw new InvalidDateException("Invalid
date for February in year " + year + ".");
}
}
}
public class DateValidator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
MyDate date = new MyDate();

System.out.print("Enter date (dd mm yyyy): ");


int d = scanner.nextInt();
int m = scanner.nextInt();
int y = scanner.nextInt();

date.accept(d, m, y);

try {
date.validate();
date.display();
} catch (InvalidDateException e) {
System.err.println("Error: " + e.getMessage());
} finally {
scanner.close();
}
}
}
SLIP 18

1) Design a screen to handle the Mouse Events such as MOUSE_MOVED and MOUSE_CLICK
and display the position of the Mouse_Click in a TextField.

Code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MouseEventsDemo extends JFrame {


private JTextField coordinatesField;
private JLabel statusLabel;

public MouseEventsDemo() {
// Frame setup
setTitle("Mouse Event Handler");
setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

// Panel to listen for mouse events


JPanel eventPanel = new JPanel();
eventPanel.setBackground(Color.LIGHT_GRAY);
add(eventPanel, BorderLayout.CENTER);

// Bottom panel for status and coordinates


JPanel infoPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
statusLabel = new JLabel("Status: Move mouse over the gray area.");
coordinatesField = new JTextField("Click coordinates will appear here", 20);
coordinatesField.setEditable(false);
infoPanel.add(statusLabel);
infoPanel.add(coordinatesField);
add(infoPanel, BorderLayout.SOUTH);

// Add mouse listener to the event panel


eventPanel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// Display click position in the TextField
String coords = "X: " + e.getX() + ", Y: " + e.getY();
coordinatesField.setText(coords);
statusLabel.setText("Status: Mouse Clicked!");
}
});
// Add mouse motion listener to the event panel
eventPanel.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
// Display current mouse position in the status label
statusLabel.setText("Status: Mouse at (" + e.getX() + ", " + e.getY() + ")");
}
});

setVisible(true);
}

public static void main(String[] args) {


SwingUtilities.invokeLater(MouseEventsDemo::new);
}
}

2) Define class EmailId with members ,username and password. Define default and
parameterized constructors. Accept values from the command line Throw user defined
exceptions – “InvalidUsernameException” or “InvalidPasswordException” if the username
and password are invalid.

Code:

// User-defined exception for invalid username


class InvalidUsernameException extends Exception {
public InvalidUsernameException(String message) { super(message); }
}

// User-defined exception for invalid password


class InvalidPasswordException extends Exception {
public InvalidPasswordException(String message) { super(message); }
}

class EmailId {
String username;
String password;

public EmailId() { /* Default constructor */ }


public EmailId(String username, String password) { // Parameterized constructor
this.username = username;
this.password = password;
}

public void validate() throws InvalidUsernameException, InvalidPasswordException {


// Simple validation logic
if (!this.username.equals("admin")) {
throw new InvalidUsernameException("Invalid username.");
}
if (!this.password.equals("admin123")) {
throw new InvalidPasswordException("Invalid password.");
}
System.out.println("Login Successful!");
}
}

public class EmailValidator {


public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: java EmailValidator <username> <password>");
return;
}

EmailId credentials = new EmailId(args[0], args[1]);

try {
credentials.validate();
} catch (InvalidUsernameException | InvalidPasswordException e) {
System.err.println("Validation Error: " + e.getMessage());
}
}
}
SLIP 19

1) Write a java program that take input as a person name in the format of first, middle and
last name and then print it in the form last, first and middle name, where in the middle
name first character is capital letter.

Code:

import java.util.Scanner;

public class NameFormatter {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter person's name (first middle last): ");


String fullName = scanner.nextLine();
String[] nameParts = fullName.split(" ");

if (nameParts.length != 3) {
System.out.println("Invalid format.");
} else {
String formattedName = nameParts[2] + ", " + nameParts[0] + " " +
Character.toUpperCase(nameParts[1].charAt(0)) + ".";
System.out.println("Formatted name: " + formattedName);
}
scanner.close();
}
}
2) Define class EmailId with members ,username and password. Define default and
parameterized constructors. Accept values from the command line Throw user defined
exceptions – “InvalidUsernameException” or “InvalidPasswordException” if the username
and password are invalid.

Code:

// User-defined exception for invalid username


class InvalidUsernameException extends Exception {
public InvalidUsernameException(String message) { super(message); }
}

// User-defined exception for invalid password


class InvalidPasswordException extends Exception {
public InvalidPasswordException(String message) { super(message); }
}

class EmailId {
String username, password;
public EmailId() {}
public EmailId(String u, String p) { this.username = u; this.password = p; }

public void validate() throws InvalidUsernameException, InvalidPasswordException {


if (!"admin".equals(this.username)) throw new InvalidUsernameException("Username is
incorrect.");
if (!"pass123".equals(this.password)) throw new InvalidPasswordException("Password is
incorrect.");
System.out.println("Login successful!");
}
}

public class EmailValidator {


public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: java EmailValidator <username> <password>");
return;
}
EmailId creds = new EmailId(args[0], args[1]);
try {
creds.validate();
} catch (InvalidUsernameException | InvalidPasswordException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
SLIP 20

1) Accept the names of two files and copy the contents of the first to the second. First file
having Book name and Author name in file. Second file having the contents of First file and
also add the comment ‘end of file’ at the end.

Code:

import java.io.*;
import java.util.Scanner;

public class FileCopier {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter source file name: ");


String sourceFile = scanner.nextLine();
System.out.print("Enter destination file name: ");
String destFile = scanner.nextLine();

try (BufferedReader reader = new BufferedReader(new FileReader(sourceFile));


BufferedWriter writer = new BufferedWriter(new FileWriter(destFile))) {

String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
writer.write("\nend of file");
System.out.println("File copied successfully.");

} catch (IOException e) {
System.err.println("An error occurred: " + e.getMessage());
} finally {
scanner.close();
}
}
}
2) Create an abstract class “order” having members id,description.Create two subclasses
“Purchase Order” and “Sales Order” having members customer name and Vendor name
respectively.Define methods accept and display in all cases. Create 3 objects each of
Purchase Order and Sales Order and accept and display details.

Code:

import java.util.Scanner;

abstract class Order {


int id; String description;
abstract void accept();
abstract void display();
}

class PurchaseOrder extends Order {


String customerName;
void accept() {
Scanner s = new Scanner(System.in);
System.out.println("\nEnter Purchase Order (ID, Desc, Customer):");
id = s.nextInt(); s.nextLine();
description = s.nextLine();
customerName = s.nextLine();
}
void display() {
System.out.println("\n--- Purchase Order ---");
System.out.println("ID: " + id + ", Desc: " + description + ", Customer: " + customerName);
}
}

class SalesOrder extends Order {


String vendorName;
void accept() {
Scanner s = new Scanner(System.in);
System.out.println("\nEnter Sales Order (ID, Desc, Vendor):");
id = s.nextInt(); s.nextLine();
description = s.nextLine();
vendorName = s.nextLine();
}
void display() {
System.out.println("\n--- Sales Order ---");
System.out.println("ID: " + id + ", Desc: " + description + ", Vendor: " + vendorName);
}
}

public class OrderDemo {


public static void main(String[] args) {
Order[] orders = new Order[6];
for (int i = 0; i < 3; i++) {
orders[i] = new PurchaseOrder();
orders[i].accept();
}
for (int i = 3; i < 6; i++) {
orders[i] = new SalesOrder();
orders[i].accept();
}
System.out.println("\n--- All Order Details ---");
for (Order o : orders) {
o.display();
}
}
}
SLIP 21

1) Write a program to accept the array element and display in reverse order.

Code:

import java.util.Scanner;

public class ReverseArray {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Enter elements:");
for (int i = 0; i < n; i++) arr[i] = scanner.nextInt();
System.out.println("\nArray in reverse order:");
for (int i = n - 1; i >= 0; i--) System.out.print(arr[i] + " ");
System.out.println();
scanner.close();
}
}

2) Write a program to read book information (bookid, bookname, bookprice, bookqty) in file
“book.dat”. Write a menu driven program to perform the following operations using
Random access file: i. Search for a specific book by name. ii. Display all book and total cost

Code:

import java.io.*;
import java.util.Scanner;

public class BookManager {


static final String FILE_NAME = "book.dat";

public static void main(String[] args) {


addInitialData();
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("\nMenu:\n1. Search by name\n2. Display all & total cost\n3. Exit");
System.out.print("Choice: ");
choice = scanner.nextInt();
scanner.nextLine();
if (choice == 1) {
System.out.print("Enter book name: ");
searchBookByName(scanner.nextLine());
} else if (choice == 2) {
displayAllBooks();
}
} while (choice != 3);
scanner.close();
}

public static void searchBookByName(String name) { // [cite: 238]


try (RandomAccessFile raf = new RandomAccessFile(FILE_NAME, "r")) {
boolean found = false;
while (raf.getFilePointer() < raf.length()) {
int id = raf.readInt(); String bName = raf.readUTF();
double price = raf.readDouble(); int qty = raf.readInt();
if (bName.equalsIgnoreCase(name)) {
System.out.println("Found: ID=" + id + ", Price=" + price + ", Qty=" + qty);
found = true; break;
}
}
if (!found) System.out.println("Book not found.");
} catch (IOException e) { e.printStackTrace(); }
}

public static void displayAllBooks() { // [cite: 239]


double totalCost = 0;
try (RandomAccessFile raf = new RandomAccessFile(FILE_NAME, "r")) {
System.out.println("\n--- All Books ---");
while (raf.getFilePointer() < raf.length()) {
int id = raf.readInt(); String name = raf.readUTF();
double price = raf.readDouble(); int qty = raf.readInt();
System.out.println("ID: " + id + ", Name: " + name + ", Price: " + price);
totalCost += price * qty;
}
System.out.printf("Total Cost: $%.2f\n", totalCost);
} catch (IOException e) { e.printStackTrace(); }
}

public static void addInitialData() {


try (RandomAccessFile raf = new RandomAccessFile(FILE_NAME, "rw")) {
raf.setLength(0);
raf.writeInt(1); raf.writeUTF("Java Basics"); raf.writeDouble(25.50); raf.writeInt(10);
raf.writeInt(2); raf.writeUTF("Advanced Java"); raf.writeDouble(40.00); raf.writeInt(5);
} catch (IOException e) { e.printStackTrace(); }
}
}
SLIP 22

1) Create an employee class(id,name,deptname,salary). Define a default and parameterized


constructor. Use ‘this’ keyword to initialize instance variables. Keep a count of objects
created. Create objects using parameterized constructor and display the object count after
each object is created.(Use static member and method). Also display the contents of each
object.

Code:

public class Employee {


int id; String name, deptName; double salary;
private static int objectCount = 0;

public Employee() { objectCount++; }


public Employee(int id, String name, String deptName, double salary) {
this.id = id; this.name = name; this.deptName = deptName; this.salary = salary;
objectCount++;
}

public void display() {


System.out.println("ID: " + id + ", Name: " + name + ", Dept: " + deptName + ", Salary: " + salary);
}

public static void displayObjectCount() {


System.out.println("Total objects created: " + objectCount);
}

public static void main(String[] args) {


Employee emp1 = new Employee(1, "John Doe", "IT", 60000);
emp1.display();
Employee.displayObjectCount();

Employee emp2 = new Employee(2, "Jane Smith", "HR", 55000);


emp2.display();
Employee.displayObjectCount();
}
}
2) Write a Java program to create a Package “SY” which has a class SYMarks (members –
ComputerTotal, MathsTotal, and ElectronicsTotal). Create another package TY which has a
class TYMarks (members – Theory, Practicals). Create n objects of Student class (having
rollNumber, name, SYMarks and TYMarks). Add the marks of SY and TY computer subjects
and calculate the Grade (‘A’ for >= 70, ‘B’ for >= 60 ‘C’ for >= 50 , Pass Class for > =40 else
‘FAIL’) and display the result of the student in proper format.

Code:

File 1: SY/SYMarks.java

package SY;
import java.util.Scanner;
public class SYMarks {
public int computerTotal, mathsTotal, electronicsTotal;
public SYMarks() {
Scanner s = new Scanner(System.in);
System.out.print("Enter SY marks (Comp, Maths, Elec): ");
computerTotal = s.nextInt(); mathsTotal = s.nextInt(); electronicsTotal = s.nextInt();
}
}

File 2: TY/TYMarks.java

package TY;
import java.util.Scanner;
public class TYMarks {
public int theory, practicals;
public TYMarks() {
Scanner s = new Scanner(System.in);
System.out.print("Enter TY Comp marks (Theory, Practicals): ");
theory = s.nextInt(); practicals = s.nextInt();
}
}

File 3: StudentDemo.java

import SY.SYMarks; import TY.TYMarks; import java.util.Scanner;


class Student {
int rollNumber; String name; SYMarks syMarks; TYMarks tyMarks;
public Student(int r, String n) {
this.rollNumber = r; this.name = n;
this.syMarks = new SYMarks(); this.tyMarks = new TYMarks();
}
public void calculateGrade() {
double percentage = (syMarks.computerTotal + tyMarks.theory + tyMarks.practicals) / 3.0;
String grade = (percentage >= 70) ? "A" : (percentage >= 60) ? "B" : (percentage >= 50) ? "C" :
(percentage >= 40) ? "Pass" : "FAIL";
System.out.println("Result for " + name + " (Roll: " + rollNumber + "): Grade " + grade);
}
}
public class StudentDemo {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter number of students: "); int n = s.nextInt(); s.nextLine();
Student[] students = new Student[n];
for(int i=0; i<n; i++) {
System.out.print("Enter roll & name for student " + (i+1) + ": ");
int roll = s.nextInt(); String name = s.next();
students[i] = new Student(roll, name);
}
for(Student stud : students) stud.calculateGrade();
}
}
SLIP 23

1) Define a class CricketPlayer (name,no_of_innings,no_of_times_notout, totatruns,


bat_avg). Create an array of n player objects .Calculate the batting average for each player
using static method avg(). Define a static sort method which sorts the array on the basis of
average. Display the player details in sorted order.

Code:

import java.util.*;
class CricketPlayer {
String name; int innings, notout, runs; double avg;
public CricketPlayer(String n, int i, int no, int r) {
name = n; innings = i; notout = no; runs = r; avg = avg(runs, innings, notout);
}
public static double avg(int r, int i, int no) {
return (i - no == 0) ? r : (double) r / (i - no);
}
public static void sort(CricketPlayer[] p) {
Arrays.sort(p, Comparator.comparingDouble(player -> player.avg));
}
public void display() {
System.out.printf("Name: %s, Avg: %.2f\n", name, avg);
}
public static void main(String[] args) {
CricketPlayer[] players = {
new CricketPlayer("PlayerA", 10, 2, 500),
new CricketPlayer("PlayerB", 10, 0, 400),
new CricketPlayer("PlayerC", 10, 5, 600)
};
sort(players);
for (CricketPlayer p : players) p.display();
}
}
2) Write a Java program to design a screen using Awt that will take a user name and
password. If the user name and password are not same, raise an Exception with
appropriate message. User can have 3 login chances only. Use clear button to clear the
TextFields.

Code:

import java.awt.*; import java.awt.event.*;


public class LoginScreen extends Frame implements ActionListener {
TextField user, pass; Button login, clear; Label msg; int attempts = 3;
public LoginScreen() {
setTitle("Login"); setSize(300, 150); setLayout(new GridLayout(4, 2));
add(new Label("User:")); user = new TextField(); add(user);
add(new Label("Pass:")); pass = new TextField(); pass.setEchoChar('*'); add(pass);
login = new Button("Login"); add(login); clear = new Button("Clear"); add(clear);
msg = new Label("Attempts left: 3"); add(msg);
login.addActionListener(this); clear.addActionListener(this);
addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent we)
{System.exit(0);}});
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == clear) { user.setText(""); pass.setText(""); }
if (e.getSource() == login) {
try {
if (!user.getText().equals(pass.getText())) throw new Exception("Mismatch");
msg.setText("Success!"); login.setEnabled(false);
} catch (Exception ex) {
attempts--;
if (attempts > 0) msg.setText("Error. Attempts left: " + attempts);
else { msg.setText("Failed."); login.setEnabled(false); }
}
}
}
public static void main(String[] args) { new LoginScreen(); }
}
SLIP 24

1) Write a program for multilevel inheritance such that country is inherited from continent.
State is inherited from country. Display the place, state, country and continent.

Code:

class Continent { String cName; public Continent(String n) { cName = n; } }


class Country extends Continent { String coName; public Country(String c, String co) { super(c);
coName = co; } }
class State extends Country { String sName; String pName;
public State(String c, String co, String s, String p) { super(c, co); sName = s; pName = p; }
public void display() {
System.out.println("Place: " + pName + ", State: " + sName + ", Country: " + coName + ",
Continent: " + cName);
}
}
public class LocationDemo {
public static void main(String[] args) {
new State("Asia", "India", "Maharashtra", "Pune").display();
}
}
2) Create the following GUI screen using appropriate layout managers. Accept the name, class
, hobbies of the user and apply the changes and display the selected options in a text box.

Code:

import java.awt.*; import java.awt.event.*;


public class UserInfoGUI extends Frame implements ActionListener {
TextField nameField, classField; Checkbox music, sports, reading; Button submit; TextArea display;
public UserInfoGUI() {
setTitle("User Info"); setSize(400, 300); setLayout(new FlowLayout());
add(new Label("Name:")); nameField = new TextField(20); add(nameField);
add(new Label("Class:")); classField = new TextField(20); add(classField);
add(new Label("Hobbies:"));
music = new Checkbox("Music"); sports = new Checkbox("Sports"); reading = new
Checkbox("Reading");
add(music); add(sports); add(reading);
submit = new Button("Submit"); add(submit);
display = new TextArea(5, 40); add(display);
submit.addActionListener(this);
addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent we)
{System.exit(0);}});
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String hobbies = (music.getState()?"Music ":"")+(sports.getState()?"Sports
":"")+(reading.getState()?"Reading":"");
display.setText("Name: " + nameField.getText() + "\nClass: " + classField.getText() + "\nHobbies: "
+ hobbies);
}
public static void main(String[] args) { new UserInfoGUI(); }
}
SLIP 25

1) Define Student class(roll_no, name, percentage) to create n objects of the Student class.
Accept details from the user for each object. Define a static method “sortStudent” which
sorts the array on the basis of percentage.

Code:

import java.util.*;
class Student {
int roll_no; String name; double percentage;
public Student(int r, String n, double p) { roll_no = r; name = n; percentage = p; }
public static void sortStudent(Student[] students) {
Arrays.sort(students, Comparator.comparingDouble(s -> s.percentage).reversed());
}
public String toString() { return "Roll: " + roll_no + ", Name: " + name + ", %: " + percentage; }
public static void main(String[] args) {
Student[] students = {new Student(1, "A", 88.5), new Student(2, "B", 91.2), new Student(3, "C",
85.0)};
System.out.println("Before sort: " + Arrays.toString(students));
sortStudent(students);
System.out.println("After sort: " + Arrays.toString(students));
}
}
2) Write a java program to display the system date and time in various formats shown below:
Current date is : 31/08/2021 Current date is : 08-31-2021 Current date is : Tuesday August
31 2021 Current date and time is : Fri August 31 15:25:59 IST 2021 Current date and time is
: 31/08/21 15:25:59 PM +0530 Current time is : 15:25:59 Current week of year is : 35
Current week of month : 5 Current day of the year is : 243 Note: Use java.util.Date and
java.text.SimpleDateFormat class

Code:

import java.util.Date; import java.text.SimpleDateFormat; import java.util.Calendar;


public class DateTimeFormatterDemo {
public static void main(String[] args) {
Date now = new Date();
System.out.println("Current date is: " + new SimpleDateFormat("dd/MM/yyyy").format(now));
System.out.println("Current date is: " + new SimpleDateFormat("MM-dd-yyyy").format(now));
System.out.println("Current date is: " + new SimpleDateFormat("EEEE MMMM dd
yyyy").format(now));
System.out.println("Current date and time is: " + new SimpleDateFormat("E MMMM dd
HH:mm:ss z yyyy").format(now));
System.out.println("Current date and time is: " + new SimpleDateFormat("dd/MM/yy hh:mm:ss
a Z").format(now));
System.out.println("Current time is: " + new SimpleDateFormat("HH:mm:ss").format(now));
Calendar cal = Calendar.getInstance();
System.out.println("Current week of year is: " + cal.get(Calendar.WEEK_OF_YEAR));
System.out.println("Current week of month: " + cal.get(Calendar.WEEK_OF_MONTH));
System.out.println("Current day of the year is: " + cal.get(Calendar.DAY_OF_YEAR));
}
}
SLIP 26

1) Write a java program to accept 5 numbers using command line arguments sort and display
them.

Code:

import java.util.Arrays;
public class SortCommandLine {
public static void main(String[] args) {
if (args.length != 5) { System.out.println("Provide 5 numbers."); return; }
int[] nums = new int[5];
for (int i=0; i<5; i++) nums[i] = Integer.parseInt(args[i]);
Arrays.sort(nums);
System.out.println("Sorted: " + Arrays.toString(nums));
}
}

2) Define a class MyNumber having one private int data member. Write a default constructor
to initialize it to 0 and another constructor to initialize it to a value (Use this). Write
methods isNegative, isPositive, isZero, isOdd, isEven. Create an object in main. Use
command line arguments to pass a value to the object (Hint : convert string argument to
integer) and perform the above tests. Provide javadoc comments for all constructors and
methods and generate the html help file.

Code:

/** A class to test integer properties. */


public class MyNumber {
/** The integer data. */
private int data;
/** Default constructor, initializes to 0. */
public MyNumber() { this.data = 0; }
/** Parameterized constructor. @param d The value. */
public MyNumber(int d) { this.data = d; }
/** Checks if negative. @return boolean. */
public boolean isNegative() { return data < 0; }
/** Checks if positive. @return boolean. */
public boolean isPositive() { return data > 0; }
/** Checks if zero. @return boolean. */
public boolean isZero() { return data == 0; }
/** Checks if odd. @return boolean. */
public boolean isOdd() { return data % 2 != 0; }
/** Checks if even. @return boolean. */
public boolean isEven() { return data % 2 == 0; }
public static void main(String[] args) {
if (args.length == 0) { System.out.println("Usage: java MyNumber <int>"); return; }
MyNumber num = new MyNumber(Integer.parseInt(args[0]));
System.out.println("Positive: " + num.isPositive() + ", Negative: " + num.isNegative() +
", Zero: " + num.isZero() + ", Odd: " + num.isOdd() + ", Even: " + num.isEven());
}
}
SLIP 27

1) Write a java program that take input as a person name in the format of first, middle and
last name and then print it in the form last, first and middle name, where in the middle
name first character is capital letter.

Code:

import java.util.Scanner;
public class NameFormatter {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter name (first middle last): ");
String[] parts = s.nextLine().split(" ");
if (parts.length == 3) {
System.out.println(parts[2] + ", " + parts[0] + " " + parts[1].toUpperCase().charAt(0) + ".");
} else { System.out.println("Invalid format."); }
s.close();
}
}

2) Define a class MyDate (day, month, year) with methods to accept and display a MyDate
object. Accept date as dd, mm, yyyy. Throw user defined exception “InvalidDateException”
if the date is invalid. Examples of invalid dates : 03 15 2019, 31 6 2000, 29 2 2021

Code:

import java.util.Scanner;
class InvalidDateException extends Exception { public InvalidDateException(String s) { super(s); } }
class MyDate {
int d, m, y;
public void accept(int d, int m, int y) { this.d = d; this.m = m; this.y = y; }
public void display() { System.out.println(d + "/" + m + "/" + y + " is valid."); }
public void validate() throws InvalidDateException {
if (m<1||m>12||d<1||d>31) throw new InvalidDateException("Invalid month/day.");
if ((m==4||m==6||m==9||m==11) && d>30) throw new InvalidDateException("Invalid day for
month.");
boolean leap = (y%4==0&&y%100!=0)||(y%400==0);
if (m==2 && ((leap && d>29) || (!leap && d>28))) throw new InvalidDateException("Invalid Feb
day.");
}
}
public class DateValidator {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter date (dd mm yyyy): ");
MyDate date = new MyDate(); date.accept(s.nextInt(), s.nextInt(), s.nextInt());
try { date.validate(); date.display(); }
catch (InvalidDateException e) { System.err.println("Error: " + e.getMessage()); }
finally { s.close(); }
}
}
SLIP 28

1) Write a java program that take input as a person name in the format of first, middle and
last name and then print it in the form last, first and middle name, where in the middle
name first character is capital letter.

Code:

import java.util.Scanner;
public class NameFormatter {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter name (first middle last): ");
String[] parts = s.nextLine().split(" ");
if (parts.length == 3) {
System.out.println(parts[2] + ", " + parts[0] + " " + parts[1].toUpperCase().charAt(0) + ".");
} else { System.out.println("Invalid format."); }
s.close();
}
}

2) Define class EmailId with members ,username and password. Define default and
parameterized constructors. Accept values from the command line Throw user defined
exceptions – “InvalidUsernameException” or “InvalidPasswordException” if the username
and password are invalid.

Code:

class InvalidUsernameException extends Exception { public InvalidUsernameException(String s) {


super(s); } }
class InvalidPasswordException extends Exception { public InvalidPasswordException(String s) {
super(s); } }
class EmailId {
String user, pass;
public EmailId(String u, String p) { this.user = u; this.pass = p; }
public void validate() throws InvalidUsernameException, InvalidPasswordException {
if (!"admin".equals(user)) throw new InvalidUsernameException("Bad username.");
if (!"password".equals(pass)) throw new InvalidPasswordException("Bad password.");
System.out.println("Success.");
}
}
public class EmailValidator {
public static void main(String[] args) {
if(args.length != 2) { System.out.println("Usage: java EmailValidator <user> <pass>"); return; }
try { new EmailId(args[0], args[1]).validate(); }
catch (Exception e) { System.err.println("Error: " + e.getMessage()); }
}
}

You might also like