Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
21 views159 pages

Practical Java Final

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)
21 views159 pages

Practical Java Final

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 159

1

1
2

INDEX

2
3

Assignment No. 1: Introduction to Java


Set A
Q1. Write a java Program to check whether given number is Prime or Not.

class check {
public static void main(String[] args) {
int num = 29;
boolean flag = false;
for (int i = 2; i <= num / 2; ++i) {

if (num % i == 0) {
flag = true;
break;
}
}

if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}

3
4

Q2. Write a java Program to display all the perfect numbers between 1 to n

import java.util.Scanner;
class perfect {
public static void main(String[] args) {
long n, sum = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number: ");
n = sc.nextLong();
sc.close();

int i = 1;
while (i <= n / 2) {
if (n % i == 0) {
sum = sum + i;
}
i++;
}
if (sum == n) {
System.out.println(n + " is a perfect number.");
} else {
System.out.println(n + " is not a perfect number.");
}
}
}

4
5

Q3. Write a java Program to accept employee name from a user and display it in
reverse order.

import java.util.Scanner;

public class setaq3 {


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

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


String employeeName = scanner.nextLine();

String reversedName = "";


for (int i = employeeName.length() - 1; i >= 0; i--) {
reversedName += employeeName.charAt(i);
}
System.out.println("Employee name in reverse order: " + reversedName);

scanner.close();
}
}

5
6

Q4. Write a java program to display all the even numbers from an array. (Use Command
Line arguments)

import java.util.Scanner;

public class setaq4 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] numbers = new int[n];
System.out.println("Enter " + n + " numbers:");
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextInt();
}
System.out.println("Even numbers from the given array:");
for (int number : numbers) {
if (number % 2 == 0) {
System.out.println(number);
}
}
scanner.close();
}
}

6
7

Q5. Write a java program to display the vowels from a given string.

import java.util.Scanner;
public class setaq5 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
inputString = inputString.toLowerCase();
System.out.println("Vowels in the given string:");
for (int i = 0; i < inputString.length(); i++) {
char ch = inputString.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
System.out.print(ch + " ");
}
}
scanner.close();
}
}

7
8

Set B
Q1. Write a java program to accept n city names and display them in ascending order.

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

public class setbq1 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of city names: ");
int n = scanner.nextInt();
scanner.nextLine();
String[] cities = new String[n];
System.out.println("Enter " + n + " city names:");
for (int i = 0; i < n; i++) {
cities[i] = scanner.nextLine();
}
Arrays.sort(cities);
System.out.println("City names in ascending order:");
for (String city : cities) {
System.out.println(city);
}
scanner.close();
}
}

8
9

Q2. Write a java program to accept n numbers from a user store only Armstrong
numbers in an array and display it.

import java.util.*;

public class setbq2 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of numbers: ");
int n = scanner.nextInt();

ArrayList<Integer> armstrongNumbers = new ArrayList<>();


System.out.println("Enter " + n + " numbers:");
for (int i = 0; i < n; i++) {
int num = scanner.nextInt();

if (isArmstrong(num)) {
armstrongNumbers.add(num);
}
}

System.out.println("Armstrong numbers from the given input:");


for (int number : armstrongNumbers) {
System.out.println(number);
}

scanner.close();
}

public static boolean isArmstrong(int num) {


int originalNum = num;
int result = 0;
int digits = Integer.toString(num).length();

while (num != 0) {

9
10

int remainder = num % 10;


result += Math.pow(remainder, digits);
num /= 10;
}

return result == originalNum;


}
}

10
11

Q3. Write a java program to search given name into the array, if it is found then display
its index otherwise display appropriate message

import java.util.Scanner;
public class setbq3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of names: ");
int n = scanner.nextInt();
scanner.nextLine();
String[] names = new String[n];
System.out.println("Enter " + n + " names:");
for (int i = 0; i < n; i++) {
names[i] = scanner.nextLine();
}
System.out.print("Enter the name to search: ");
String searchName = scanner.nextLine();
boolean found = false;
for (int i = 0; i < names.length; i++) {
if (names[i].equalsIgnoreCase(searchName)) {
System.out.println("Name found at index: " + i);
found = true;
break;
}
}
if (!found) {
System.out.println("Name not found in the array.");
}
scanner.close();
}
}

11
12

12
13

Q4. Write a java program to display following pattern:


5
45
345
2345
12345

public class setbq4 {


public static void main(String[] args) {
int rows = 5;

for (int i = rows; i >= 1; i--) {


for (int j = i; j <= rows; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}

13
14

Q5. Write a java program to display following pattern:


1
01
010
1010

public class setbq5 {


public static void main(String[] args) {
int rows = 4;
for (int i = 0; i < rows; i++) {
for (int j = 0; j <= i; j++) {
if ((i + j) % 2 == 0) {
System.out.print("1 ");
} else {
System.out.print("0 ");
}
}
System.out.println();
}
}
}

14
15

Set C
Q1. Write a java program to count the frequency of each character in a given string.

import java.util.*;

public class setcq1 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();

Map<Character, Integer> frequencyMap = new HashMap<>();

char[] characters = inputString.toCharArray();


for (char ch : characters) {
if (frequencyMap.containsKey(ch)) {
frequencyMap.put(ch, frequencyMap.get(ch) + 1);
} else {
frequencyMap.put(ch, 1);
}
}

System.out.println("Character frequencies:");
for (Map.Entry<Character, Integer> entry : frequencyMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}

scanner.close();
}
}

15
16

16
17

Q2. Write a java program to display each word in reverse order from a string array.

public class setcq2 {


public static void main(String[] args) {
String[] words = {"hello", "world", "java", "programming"};

System.out.println("Original words and their reversed versions:");


for (String word : words) {
String reversedWord = reverseString(word);
System.out.println("Original: " + word + " | Reversed: " + reversedWord);
}
}

public static String reverseString(String input) {


StringBuilder reversed = new StringBuilder(input);
return reversed.reverse().toString();
}
}

17
18

Q3. Write a java program for union of two integer array.

import java.util.*;

public class setcq3 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements in the first array: ");
int n1 = scanner.nextInt();
int[] array1 = new int[n1];
System.out.println("Enter " + n1 + " elements for the first array:");
for (int i = 0; i < n1; i++) {
array1[i] = scanner.nextInt();
}

System.out.print("Enter the number of elements in the second array: ");


int n2 = scanner.nextInt();
int[] array2 = new int[n2];
System.out.println("Enter " + n2 + " elements for the second array:");
for (int i = 0; i < n2; i++) {
array2[i] = scanner.nextInt();
}

Set<Integer> unionSet = new HashSet<>();

for (int num : array1) {


unionSet.add(num);
}

for (int num : array2) {


unionSet.add(num);
}

System.out.println("Union of the two arrays:");


for (int num : unionSet) {

18
19

System.out.print(num + " ");


}

scanner.close();
}
}

19
20

Q4. Write a java program to display transpose of given matrix.

import java.util.Scanner;

public class setcq4 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows in the matrix: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns in the matrix: ");
int cols = scanner.nextInt();

int[][] matrix = new int[rows][cols];

System.out.println("Enter the elements of the matrix:");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = scanner.nextInt();
}
}

int[][] transpose = new int[cols][rows];


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transpose[j][i] = matrix[i][j];
}
}

System.out.println("Transpose of the given matrix:");


for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
System.out.print(transpose[i][j] + " ");
}
System.out.println();
}

20
21

scanner.close();
}
}

21
22

Q5. Write a java program to display alternate character from a given string.

import java.util.Scanner;

public class setcq5 {


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

System.out.print("Enter a string: ");


String inputString = scanner.nextLine();

System.out.print("Alternate characters: ");


for (int i = 0; i < inputString.length(); i += 2) {
System.out.print(inputString.charAt(i));
}

scanner.close();
}
}

22
23

Assignment No. 2: Classes, Objects and Methods


Set A
Q1. Write a Java program to calculate power of a number using recursion.

import java.util.Scanner;

public class setaq1 {


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

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


int base = scanner.nextInt();
System.out.print("Enter the exponent: ");
int exponent = scanner.nextInt();

int result = power(base, exponent);

System.out.println(base + " raised to the power of " + exponent + " is: " + result);

scanner.close();
}
public static int power(int base, int exponent) {
if (exponent == 0) {
return 1;
}
return base * power(base, exponent - 1);
}
}

23
24

Q2. Write a Java program to display Fibonacci series using function.

import java.util.Scanner;

public class setaq2 {


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

System.out.print("Enter the number of terms in the Fibonacci series: ");


int numTerms = scanner.nextInt();

System.out.println("Fibonacci series up to " + numTerms + " terms:");


for (int i = 0; i < numTerms; i++) {
System.out.print(fibonacci(i) + " ");
}

scanner.close();
}

public static int fibonacci(int n) {


if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
}

24
25

Q3. Write a Java program to calculate area of Circle, Triangle & Rectangle.(Use Method
Overloading)

import java.util.Scanner;

public class setaq3 {


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

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


double radius = scanner.nextDouble();
System.out.println("Debug: Radius entered = " + radius);
if (radius > 0) {
System.out.println("Area of the circle: " + calculateArea(radius));
} else {
System.out.println("Radius must be positive.");
}

System.out.print("Enter the base of the triangle: ");


double base = scanner.nextDouble();
System.out.println("Debug: Base entered = " + base);
System.out.print("Enter the height of the triangle: ");
double height = scanner.nextDouble();
System.out.println("Debug: Height entered = " + height);
if (base > 0 && height > 0) {
System.out.println("Area of the triangle: " + calculateArea(base, height));
} else {
System.out.println("Base and height must be positive.");
}

System.out.print("Enter the length of the rectangle: ");


double length = scanner.nextDouble();
System.out.println("Debug: Length entered = " + length);
System.out.print("Enter the width of the rectangle: ");
double width = scanner.nextDouble();

25
26

System.out.println("Debug: Width entered = " + width);


if (length > 0 && width > 0) {
System.out.println("Area of the rectangle: " + calculateArea(length, width));
} else {
System.out.println("Length and width must be positive.");
}

scanner.close();
}

public static double calculateArea(double radius) {


return Math.PI * radius * radius;
}

public static double calculateArea(double base, double height) {


return 0.5 * base * height;
}

public static double calculateArea1(double length, double width) {


return length * width;
}
}

26
27

Q4. Write a Java program to Copy data of one object to another Object.

class setaq4 {
private String name;
private int age;

public setaq4(String name, int age) {


this.name = name;
this.age = age;
}

public void display() {


System.out.println("Name: " + name + ", Age: " + age);
}

public void copyFrom(setaq4 other) {


this.name = other.name;
this.age = other.age;
}

public static void main(String[] args) {


setaq4 person1 = new setaq4("Alice", 30);
System.out.println("Person 1 details:");
person1.display();

setaq4 person2 = new setaq4("Bob", 25);


System.out.println("Person 2 details before copying:");
person2.display();

person2.copyFrom(person1);
System.out.println("Person 2 details after copying:");
person2.display();
}
}

27
28

28
29

Q5. Write a Java program to calculate factorial of a number using recursion.

import java.util.Scanner;

public class setaq5 {

public static long factorial(int n) {


if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n - 1);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter a positive integer: ");


int number = scanner.nextInt();

if (number < 0) {
System.out.println("Factorial is not defined for negative numbers.");
} else {
long result = factorial(number);
System.out.println("Factorial of " + number + " is: " + result);
}

scanner.close();
}
}

29
30

Set B
Q1. Define a class person(pid,pname,age,gender). Define Default and parameterised
constructor. Overload the constructor. Accept the 5 person details and display it.(use
this keyword).

import java.util.Scanner;

class setbq1 {
private int pid;
private String pname;
private int age;
private String gender;

public setbq1() {
this.pid = 0;
this.pname = "Unknown";
this.age = 0;
this.gender = "Unknown";
}

public setbq1(int pid, String pname, int age, String gender) {


this.pid = pid;
this.pname = pname;
this.age = age;
this.gender = gender;
}

public setbq1(int pid, String pname) {


this(pid, pname, 0, "Unknown");
}

public void display() {


System.out.println("ID: " + pid + ", Name: " + pname + ", Age: " + age + ", Gender: "
+ gender);
}

30
31

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
setbq1[] persons = new setbq1[5];

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


System.out.println("Enter details for Person " + (i + 1) + ":");
System.out.print("ID: ");
int id = scanner.nextInt();
scanner.nextLine();
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.print("Age: ");
int age = scanner.nextInt();
scanner.nextLine();
System.out.print("Gender: ");
String gender = scanner.nextLine();

persons[i] = new setbq1(id, name, age, gender);


}

System.out.println("\nDetails of all persons:");


for (setbq1 person : persons) {
person.display();
}

scanner.close();
}
}

31
32

32
33

Q2. Define a class product(pid,pname,price). Write a function to accept the product


details, to display product details and to calculate total amount. (use array of Objects)

import java.util.Scanner;

class Product {
private int pid;
private String pname;
private double price;

public void acceptDetails(Scanner scanner) {


System.out.print("Enter Product ID: ");
this.pid = scanner.nextInt();
scanner.nextLine();

System.out.print("Enter Product Name: ");


this.pname = scanner.nextLine();

System.out.print("Enter Product Price: ");


this.price = scanner.nextDouble();
scanner.nextLine();
}

public void displayDetails() {


System.out.println("Product ID: " + pid + ", Name: " + pname + ", Price: Rs " +
price);
}

public double getPrice() {


return price;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

33
34

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


int numProducts = scanner.nextInt();
scanner.nextLine();

Product[] products = new Product[numProducts];

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


System.out.println("Enter details for Product " + (i + 1) + ":");
products[i] = new Product();
products[i].acceptDetails(scanner);
}

System.out.println("\nProduct Details:");
double totalAmount = 0;

for (Product product : products) {


product.displayDetails();
totalAmount += product.getPrice();
}

System.out.println("\nTotal Amount: Rs " + totalAmount);

scanner.close();
}
}

34
35

35
36

Q3. Define a class Student(rollno,name,per). Create n objects of the student class and
Display it using toString().(Use parameterized constructor)

import java.util.Scanner;

class Student {
private int rollno;
private String name;
private double per;

public Student(int rollno, String name, double per) {


this.rollno = rollno;
this.name = name;
this.per = per;
}

@Override
public String toString() {
return "Roll No: " + rollno + ", Name: " + name + ", Percentage: " + per;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

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


int n = scanner.nextInt();
scanner.nextLine();

Student[] students = new Student[n];

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


System.out.println("Enter details for Student " + (i + 1) + ":");

System.out.print("Enter Roll Number: ");

36
37

int rollno = scanner.nextInt();


scanner.nextLine();

System.out.print("Enter Name: ");


String name = scanner.nextLine();

System.out.print("Enter Percentage: ");


double per = scanner.nextDouble();
scanner.nextLine();

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


}

System.out.println("\nStudent Details:");
for (Student student : students) {
System.out.println(student);
}

scanner.close();
}
}

37
38

Q4. Define a class MyNumber having one private integer data member. Write a default
constructor to initialize it to 0 and another constructor to initialize it to a value. Write
methods isNegative, isPositive. Use command line argument to pass a value to the
object and perform the above tests

import java.util.Scanner;

public class setbq4 {


private int number;

public setbq4() {
this.number = 0;
}

public setbq4(int number) {


this.number = number;
}

public boolean isNegative() {


return number < 0;
}

public boolean isPositive() {


return number > 0;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");


int value = 0;
boolean validInput = false;

while (!validInput) {
try {

38
39

value = Integer.parseInt(scanner.nextLine());
validInput = true; // Input is valid, exit loop
} catch (NumberFormatException e) {
System.out.print("Invalid input. Please enter a valid integer: ");
}
}

setbq4 myNumber = new setbq4(value);

System.out.println("Is the number negative? " + myNumber.isNegative());


System.out.println("Is the number positive? " + myNumber.isPositive());

scanner.close();
}
}

39
40

Set C
Q1. Define class Student(rno, name, mark1, mark2). Define Result class(total,
percentage) inside the student class. Accept the student details & display the mark
sheet with rno, name, mark1, mark2, total, percentage. (Use inner class concept)

import java.util.Scanner;

public class setcq1 {


private int rno;
private String name;
private double mark1;
private double mark2;

class Result {
private double total;
private double percentage;

public void calculateResult() {


total = mark1 + mark2;
percentage = (total / 200) * 100;
}

public void displayResult() {


System.out.printf("Total: %.2f\n", total);
System.out.printf("Percentage: %.2f%%\n", percentage);
}
}

public void acceptDetails() {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter Roll Number: ");


rno = scanner.nextInt();
scanner.nextLine();

40
41

System.out.print("Enter Name: ");


name = scanner.nextLine();

System.out.print("Enter Mark 1: ");


mark1 = scanner.nextDouble();

System.out.print("Enter Mark 2: ");


mark2 = scanner.nextDouble();

scanner.close();
}

public void displayMarkSheet() {


Result result = new Result();
result.calculateResult();

System.out.println("\nMark Sheet:");
System.out.println("Roll Number: " + rno);
System.out.println("Name: " + name);
System.out.println("Mark 1: " + mark1);
System.out.println("Mark 2: " + mark2);
result.displayResult();
}

public static void main(String[] args) {


setcq1 student = new setcq1();
student.acceptDetails();
student.displayMarkSheet();
}
}

41
42

42
43

Q2. Write a java program to accept n employee names from user. Sort them in
ascending order and Display them.(Use array of object nd Static keyword)

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

public class setcq2 {


private static String[] employeeNames;

public static void acceptNames(int n) {


Scanner scanner = new Scanner(System.in);
employeeNames = new String[n];

System.out.println("Enter " + n + " employee names:");


for (int i = 0; i < n; i++) {
System.out.print("Employee " + (i + 1) + ": ");
employeeNames[i] = scanner.nextLine();
}
}

public static void sortNames() {


Arrays.sort(employeeNames);
}

public static void displayNames() {


System.out.println("\nSorted Employee Names:");
for (String name : employeeNames) {
System.out.println(name);
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

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

43
44

int n = scanner.nextInt();
scanner.nextLine();

acceptNames(n);
sortNames();
displayNames();

scanner.close();
}
}

44
45

Q3. Write a java program to accept details of ‘n’ cricket players(pid, pname, totalRuns,
InningsPlayed, NotOuttimes). Calculate the average of all the players. Display the
details of player having maximum average.

import java.util.Scanner;

class CricketPlayer {
private int pid;
private String pname;
private int totalRuns;
private int inningsPlayed;
private int notOutTimes;

public CricketPlayer(int pid, String pname, int totalRuns, int inningsPlayed, int
notOutTimes) {
this.pid = pid;
this.pname = pname;
this.totalRuns = totalRuns;
this.inningsPlayed = inningsPlayed;
this.notOutTimes = notOutTimes;
}

public double calculateAverage() {


return (double) totalRuns / inningsPlayed;
}

public void displayDetails() {


System.out.println("Player ID: " + pid);
System.out.println("Player Name: " + pname);
System.out.println("Total Runs: " + totalRuns);
System.out.println("Innings Played: " + inningsPlayed);
System.out.println("Not Out Times: " + notOutTimes);
System.out.println("Average Runs per Innings: " + calculateAverage());
}

45
46

public double getAverage() {


return calculateAverage();
}
}

public class setcq3 {


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();

CricketPlayer[] players = new CricketPlayer[n];


double maxAverage = -1;
CricketPlayer bestPlayer = null;

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


System.out.println("Enter details for Player " + (i + 1) + ":");

System.out.print("Player ID: ");


int pid = scanner.nextInt();
scanner.nextLine();

System.out.print("Player Name: ");


String pname = scanner.nextLine();

System.out.print("Total Runs: ");


int totalRuns = scanner.nextInt();

System.out.print("Innings Played: ");


int inningsPlayed = scanner.nextInt();

System.out.print("Not Out Times: ");

46
47

int notOutTimes = scanner.nextInt();


scanner.nextLine();

players[i] = new CricketPlayer(pid, pname, totalRuns, inningsPlayed,


notOutTimes);

double average = players[i].getAverage();


if (average > maxAverage) {
maxAverage = average;
bestPlayer = players[i];
}
}

System.out.println("\nPlayer with the highest average:");


if (bestPlayer != null) {
bestPlayer.displayDetails();
} else {
System.out.println("No player data available.");
}

scanner.close();
}
}

47
48

48
49

Q4. Write a java program to accept details of ‘n’ books. And Display the quantity of
given book.

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

class Book {
private String title;
private String author;
private int quantity;

public Book(String title, String author, int quantity) {


this.title = title;
this.author = author;
this.quantity = quantity;
}

public String getTitle() {


return title;
}

public int getQuantity() {


return quantity;
}

public void displayDetails() {


System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Quantity: " + quantity);
}
}

public class BookInventory {


private static Map<String, Book> bookMap = new HashMap<>();

49
50

public static void acceptBookDetails(int n) {


Scanner scanner = new Scanner(System.in);

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


System.out.println("Enter details for Book " + (i + 1) + ":");

System.out.print("Title: ");
String title = scanner.nextLine();

System.out.print("Author: ");
String author = scanner.nextLine();

System.out.print("Quantity: ");
int quantity = scanner.nextInt();
scanner.nextLine();

bookMap.put(title, new Book(title, author, quantity));


}
}

public static void displayBookQuantity(String title) {


Book book = bookMap.get(title);
if (book != null) {
System.out.println("Quantity of '" + title + "': " + book.getQuantity());
} else {
System.out.println("Book not found.");
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

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

50
51

int n = scanner.nextInt();
scanner.nextLine();

acceptBookDetails(n);

System.out.print("Enter the title of the book to check quantity: ");


String searchTitle = scanner.nextLine();
displayBookQuantity(searchTitle);

scanner.close();
}
}

51
52

Assignment No. 3: Inheritance, Package and Collection


Set A
Q1. Write a java program to calculate area of Cylinder and Circle.(Use super keyword)

import java.util.Scanner;

class Shape {
protected double radius;

public Shape(double radius) {


this.radius = radius;
}

public double calculateCircleArea() {


return Math.PI * radius * radius;
}
}

class Cylinder extends Shape {


private double height;

public Cylinder(double radius, double height) {


super(radius);
this.height = height;
}

public double calculateSurfaceArea() {


double circleArea = super.calculateCircleArea(); // Use super keyword to access
method from base class
double lateralSurfaceArea = 2 * Math.PI * radius * height;
return 2 * circleArea + lateralSurfaceArea;
}

public double calculateVolume() {


return super.calculateCircleArea() * height;

52
53

}
}

public class setaq1 {


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

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


double radius = scanner.nextDouble();

Shape circle = new Shape(radius);


System.out.println("Area of the circle: " + circle.calculateCircleArea());

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


double height = scanner.nextDouble();

Cylinder cylinder = new Cylinder(radius, height);


System.out.println("Surface area of the cylinder: " +
cylinder.calculateSurfaceArea());
System.out.println("Volume of the cylinder: " + cylinder.calculateVolume());

scanner.close();
}
}

53
54

Q2.Define an Interface Shape with abstract method area(). Write a java program to
calculate an area of Circle and Sphere.(use final keyword)

import java.util.Scanner;

interface Shape {
double area();
}

final class Circle implements Shape {


private final double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
public double area() {
return Math.PI * radius * radius;
}
}

final class Sphere implements Shape {


private final double radius;

public Sphere(double radius) {


this.radius = radius;
}

@Override
public double area() {
return 4 * Math.PI * radius * radius;
}
}

54
55

public class setaq2 {


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

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


double circleRadius = scanner.nextDouble();
Shape circle = new Circle(circleRadius);
System.out.println("Area of the circle: " + circle.area());

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


double sphereRadius = scanner.nextDouble();
Shape sphere = new Sphere(sphereRadius);
System.out.println("Surface area of the sphere: " + sphere.area());

scanner.close();
}
}

55
56

Q3. Define an Interface “Integer” with a abstract method check().Write a Java program
to check whether a given number is Positive or Negative

import java.util.Scanner;
interface NumberCheck {
void check();
}

class Number implements NumberCheck {


private int number;

public Number(int number) {


this.number = number;
}

@Override
public void check() {
if (number > 0) {
System.out.println("The number is Positive.");
} else if (number < 0) {
System.out.println("The number is Negative.");
} else {
System.out.println("The number is Zero.");
}
}
}

public class setaq3 {


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

System.out.print("Enter a number: ");


int num = scanner.nextInt();

Number number = new Number(num);

56
57

number.check();

scanner.close();
}
}

57
58

Q4. Define a class Student with attributes rollno and name. Define default and
parameterized constructor. Override the toString() method. Keep the count of Objects
created. Create objects using parameterized constructor and Display the object count
after each object is created.

public class setaq4 {


private int rollno;
private String name;
private static int count = 0;

public setaq4() {
this.rollno = 0;
this.name = "Unknown";
count++;
displayCount();
}

public setaq4(int rollno, String name) {


this.rollno = rollno;
this.name = name;
count++;
displayCount();
}

private void displayCount() {


System.out.println("Number of Student objects created: " + count);
}

@Override
public String toString() {
return "Student[Roll No: " + rollno + ", Name: " + name + "]";
}

public static void main(String[] args) {


setaq4 s1 = new setaq4(101, "Alice");

58
59

setaq4 s2 = new setaq4(102, "Bob");

System.out.println(s1);
System.out.println(s2);
}
}

59
60

Q5. Write a java program to accept ‘n’ integers from the user & store them in an
ArrayList collection. Display the elements of ArrayList collection in reverse order

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

public class setaq5 {


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

ArrayList<Integer> numbers = new ArrayList<>();

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


int n = scanner.nextInt();

System.out.println("Enter " + n + " integers:");


for (int i = 0; i < n; i++) {
System.out.print("Integer " + (i + 1) + ": ");
numbers.add(scanner.nextInt());
}

scanner.close();

Collections.reverse(numbers);

System.out.println("Elements in reverse order:");


for (int number : numbers) {
System.out.println(number);
}
}
}

60
61

61
62

Set C
Q1. Create an abstract class Shape with methods calc_area() & calc_volume(). Derive
two classes Sphere(radius)& Cone(radius, height) from it. Calculate area and volume of
both. (Use Method Overriding)

abstract class Shape {


abstract double calc_area();

abstract double calc_volume();


}

class Sphere extends Shape {


private double radius;

public Sphere(double radius) {


this.radius = radius;
}

@Override
double calc_area() {
return 4 * Math.PI * radius * radius;
}

@Override
double calc_volume() {
return (4.0 / 3) * Math.PI * Math.pow(radius, 3);
}
}

class Cone extends Shape {


private double radius;
private double height;

public Cone(double radius, double height) {


this.radius = radius;

62
63

this.height = height;
}

@Override
double calc_area() {
double slantHeight = Math.sqrt(radius * radius + height * height);
return Math.PI * radius * (radius + slantHeight);
}

@Override
double calc_volume() {
return (1.0 / 3) * Math.PI * radius * radius * height;
}
}

public class setcq1 {


public static void main(String[] args) {
Shape sphere = new Sphere(5.0);
System.out.println("Sphere:");
System.out.println("Area: " + sphere.calc_area());
System.out.println("Volume: " + sphere.calc_volume());

Shape cone = new Cone(5.0, 10.0);


System.out.println("\nCone:");
System.out.println("Area: " + cone.calc_area());
System.out.println("Volume: " + cone.calc_volume());
}
}

63
64

64
65

Q2. Define a class Employee having private members-id, name, department, salary.
Define default & parameterized constructors. Create a subclass called Manager with
private member bonus. Define methods accept & display in both the classes. Create n
objects of the manager class & display the details of the manager having the maximum
total salary(salary+bonus).

import java.util.Scanner;

class Employee {
private int id;
private String name;
private String department;
private double salary;

public Employee() {
this.id = 0;
this.name = "";
this.department = "";
this.salary = 0.0;
}

public Employee(int id, String name, String department, double salary) {


this.id = id;
this.name = name;
this.department = department;
this.salary = salary;
}

public void accept() {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter Employee ID: ");


this.id = scanner.nextInt();
scanner.nextLine(); // Consume newline

65
66

System.out.print("Enter Employee Name: ");


this.name = scanner.nextLine();

System.out.print("Enter Employee Department: ");


this.department = scanner.nextLine();

System.out.print("Enter Employee Salary: ");


this.salary = scanner.nextDouble();
}

public void display() {


System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Department: " + department);
System.out.println("Salary: " + salary);
}

public double getSalary() {


return salary;
}
}

class Manager extends Employee {


private double bonus;

public Manager() {
super();
this.bonus = 0.0;
}

public Manager(int id, String name, String department, double salary, double bonus) {
super(id, name, department, salary);
this.bonus = bonus;
}

66
67

@Override
public void accept() {
super.accept();
Scanner scanner = new Scanner(System.in);

System.out.print("Enter Bonus: ");


this.bonus = scanner.nextDouble();
}

@Override
public void display() {
super.display();
System.out.println("Bonus: " + bonus);
}

public double getTotalSalary() {


return getSalary() + bonus;
}
}

public class setcq2 {


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

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


int n = scanner.nextInt();
scanner.nextLine(); // Consume newline

Manager[] managers = new Manager[n];

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


System.out.println("Enter details for Manager " + (i + 1) + ":");
managers[i] = new Manager();

67
68

managers[i].accept();
}

Manager maxManager = managers[0];


for (int i = 1; i < n; i++) {
if (managers[i].getTotalSalary() > maxManager.getTotalSalary()) {
maxManager = managers[i];
}
}

System.out.println("\nManager with the Maximum Total Salary:");


maxManager.display();

scanner.close();
}
}

68
69

Q3. Construct a Linked List containg name: CPP, Java, Python and PHP. Then extend
your program to do the following:
i. Display the contents of the List using an iterator
ii. Display the contents of the List in reverse order using a ListIterator.

import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Iterator;

public class setbq3 {


public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add("CPP");
list.add("Java");
list.add("Python");
list.add("PHP");

System.out.println("Contents of the list using an iterator:");


Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}

System.out.println("\nContents of the list in reverse order using a ListIterator:");


ListIterator<String> listIterator = list.listIterator(list.size()); // Start from the end
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
}
}

69
70

70
71

Q4. Create a hashtable containing employee name & salary. Display the details of the
hashtable. Also search for a specific Employee and display salary of that employee.

import java.util.Hashtable;
import java.util.Scanner;

public class setbq4 {


public static void main(String[] args) {
Hashtable<String, Double> employeeTable = new Hashtable<>();

employeeTable.put("Alice", 55000.00);
employeeTable.put("Bob", 60000.00);
employeeTable.put("Charlie", 75000.00);
employeeTable.put("David", 65000.00);

System.out.println("Employee Details:");
for (String name : employeeTable.keySet()) {
System.out.println("Name: " + name + ", Salary: Rs " +
employeeTable.get(name));
}

Scanner scanner = new Scanner(System.in);


System.out.print("\nEnter the name of the employee to search: ");
String searchName = scanner.nextLine();

if (employeeTable.containsKey(searchName)) {
double salary = employeeTable.get(searchName);
System.out.println("Salary of " + searchName + ": Rs " + salary);
} else {
System.out.println("Employee not found.");
}

scanner.close();
}
}

71
72

72
73

Q5. Write a package game which will have 2 classes Indoor & Outdoor. Use a function
display() to generate the list of player for the specific game. Use default &
parameterized constructor.

import java.util.*;

class Indoor {
private String[] players;

public Indoor() {
this.players = new String[]{"Player1", "Player2", "Player3"};
}

public Indoor(String[] players) {


this.players = players;
}

public void display() {


System.out.println("Indoor Game Players:");
for (String player : players) {
System.out.println(player);
}
}
}

class Outdoor {
private String[] players;

public Outdoor() {
this.players = new String[]{"PlayerA", "PlayerB", "PlayerC"};
}

public Outdoor(String[] players) {


this.players = players;
}

73
74

public void display() {


System.out.println("Outdoor Game Players:");
for (String player : players) {
System.out.println(player);
}
}
}

public class setbq5 {


public static void main(String[] args) {
Indoor indoorGame = new Indoor();
Outdoor outdoorGame = new Outdoor();

indoorGame.display();
outdoorGame.display();

String[] customIndoorPlayers = {"Alice", "Bob", "Charlie"};


String[] customOutdoorPlayers = {"Xander", "Yara", "Zane"};

Indoor customIndoorGame = new Indoor(customIndoorPlayers);


Outdoor customOutdoorGame = new Outdoor(customOutdoorPlayers);

customIndoorGame.display();
customOutdoorGame.display();
}
}

74
75

75
76

Set C
Q1. Create a hashtable containing city name & STD code. Display the details of the
hashtable. Also search for a specific city and display STD code of that city.

import java.util.*;

public class setcq1 {


public static void main(String[] args) {
Hashtable<String, String> citySTD = new Hashtable<>();

citySTD.put("Mumbai", "022");
citySTD.put("Delhi", "011");
citySTD.put("Bangalore", "080");
citySTD.put("Chennai", "044");
citySTD.put("Kolkata", "033");

System.out.println("City and STD Code Details:");


Enumeration<String> keys = citySTD.keys();
while (keys.hasMoreElements()) {
String city = keys.nextElement();
String stdCode = citySTD.get(city);
System.out.println("City: " + city + ", STD Code: " + stdCode);
}

String searchCity = "Bangalore";


String stdCode = citySTD.get(searchCity);
if (stdCode != null) {
System.out.println("\nThe STD code for " + searchCity + " is: " + stdCode);
} else {
System.out.println("\nCity " + searchCity + " not found in the hashtable.");
}
}
}

76
77

77
78

Q2. Construct a Linked List containing name: red, blue, yellow and orange. Then extend
your program to do the following:
Display the contents of the List using an iterator Display the contents of the List in
reverse order using a ListIterator.
Create another list containing pink & green.
Insert the elements of this list between blue & yellow.

import java.util.*;

public class setcq2 {


public static void main(String[] args) {
LinkedList<String> colors = new LinkedList<>();
colors.add("red");
colors.add("blue");
colors.add("yellow");
colors.add("orange");

System.out.println("Contents of the LinkedList:");


Iterator<String> iterator = colors.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}

System.out.println("\nContents of the LinkedList in reverse order:");


ListIterator<String> listIterator = colors.listIterator(colors.size());
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}

LinkedList<String> newColors = new LinkedList<>();


newColors.add("pink");
newColors.add("green");

int indexYellow = colors.indexOf("yellow");

78
79

colors.addAll(indexYellow, newColors);

System.out.println("\nModified LinkedList with new colors inserted:");


for (String color : colors) {
System.out.println(color);
}
}
}

79
80

Q3. Define an abstract class Staff with members name &address. Define two sub
classes FullTimeStaff(Departmet, Salary) and PartTimeStaff(numberOfHours,
ratePerHour). Define appropriate constructors. Create n objects which could be of either
FullTimeStaff or PartTimeStaff class by asking the user’s choice. Display details of
FulltimeStaff and PartTimeStaff.

import java.util.*;
abstract class Staff {
protected String name;
protected String address;

public Staff(String name, String address) {


this.name = name;
this.address = address;
}

public abstract void displayDetails();


}

class FullTimeStaff extends Staff {


private String department;
private double salary;

public FullTimeStaff(String name, String address, String department, double salary) {


super(name, address);
this.department = department;
this.salary = salary;
}

@Override
public void displayDetails() {
System.out.println("Full-Time Staff");
System.out.println("Name: " + name);
System.out.println("Address: " + address);
System.out.println("Department: " + department);

80
81

System.out.println("Salary: " + salary);


System.out.println();
}
}

class PartTimeStaff extends Staff {


private int numberOfHours;
private double ratePerHour;

public PartTimeStaff(String name, String address, int numberOfHours, double


ratePerHour) {
super(name, address);
this.numberOfHours = numberOfHours;
this.ratePerHour = ratePerHour;
}

@Override
public void displayDetails() {
System.out.println("Part-Time Staff");
System.out.println("Name: " + name);
System.out.println("Address: " + address);
System.out.println("Number of Hours: " + numberOfHours);
System.out.println("Rate Per Hour: " + ratePerHour);
System.out.println();
}
}

public class setcq3 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Staff> staffList = new ArrayList<>();

System.out.print("Enter number of staff members: ");


int n = scanner.nextInt();

81
82

scanner.nextLine();

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


System.out.println("Enter details for staff member " + (i + 1));
System.out.print("Enter type (FullTime/PartTime): ");
String type = scanner.nextLine();
System.out.print("Enter name: ");
String name = scanner.nextLine();
System.out.print("Enter address: ");
String address = scanner.nextLine();

if (type.equalsIgnoreCase("FullTime")) {
System.out.print("Enter department: ");
String department = scanner.nextLine();
System.out.print("Enter salary: ");
double salary = scanner.nextDouble();
scanner.nextLine(); // Consume newline
staffList.add(new FullTimeStaff(name, address, department, salary));
} else if (type.equalsIgnoreCase("PartTime")) {
System.out.print("Enter number of hours: ");
int numberOfHours = scanner.nextInt();
System.out.print("Enter rate per hour: ");
double ratePerHour = scanner.nextDouble();
scanner.nextLine();
staffList.add(new PartTimeStaff(name, address, numberOfHours,
ratePerHour));
} else {
System.out.println("Invalid type! Please enter FullTime or PartTime.");
i--;
}
}

System.out.println("\nDisplaying Staff Details:");


for (Staff staff : staffList) {

82
83

staff.displayDetails();
}

scanner.close();
}
}

83
84

Q4. Derive a class Square from class Rectangle. Create one more class Circle. Create
an interface with only one method called area(). Implement this interface in all classes.
Include appropriate data members and constructors in all classes. Write a java program
to accept details of Square, Circle & Rectangle and display the area

import java.util.Scanner;

interface Shape {
double area();
}

class Rectangle implements Shape {


protected double length;
protected double width;

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

@Override
public double area() {
return length * width;
}
}

class Square extends Rectangle {

public Square(double side) {


super(side, side);
}

@Override
public double area() {
return super.area();

84
85

}
}

class Circle implements Shape {


private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
public double area() {
return Math.PI * radius * radius;
}
}

public class setcq4 {


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

System.out.print("Enter length of Rectangle: ");


double rectLength = scanner.nextDouble();
System.out.print("Enter width of Rectangle: ");
double rectWidth = scanner.nextDouble();
Rectangle rectangle = new Rectangle(rectLength, rectWidth);

System.out.print("Enter side of Square: ");


double side = scanner.nextDouble();
Square square = new Square(side);

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


double radius = scanner.nextDouble();
Circle circle = new Circle(radius);

85
86

System.out.println("\nArea of Rectangle: " + rectangle.area());


System.out.println("Area of Square: " + square.area());
System.out.println("Area of Circle: " + circle.area());

scanner.close();
}
}

86
87

Q5. Create a package named Series having three different classes to print series:
i. Fibonacci series
ii. Cube of numbers
iii. Square of numbers
Write a java program to generate ‘n’ terms of the above series.

import java.util.Scanner;

public class setcq5 {

static class FibonacciSeries {


public void generate(int n) {
int a = 0, b = 1;
System.out.print("Fibonacci Series: ");
for (int i = 0; i < n; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
System.out.println();
}
}

static class CubeSeries {


public void generate(int n) {
System.out.print("Cube Series: ");
for (int i = 1; i <= n; i++) {
System.out.print(i * i * i + " ");
}
System.out.println();
}
}

static class SquareSeries {

87
88

public void generate(int n) {


System.out.print("Square Series: ");
for (int i = 1; i <= n; i++) {
System.out.print(i * i + " ");
}
System.out.println();
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of terms for the series: ");


int n = scanner.nextInt();

FibonacciSeries fibonacci = new FibonacciSeries();


CubeSeries cube = new CubeSeries();
SquareSeries square = new SquareSeries();

fibonacci.generate(n);
cube.generate(n);
square.generate(n);

scanner.close();
}
}

88
89

Assignment No. 4 : File and Exception Handling


Set A
Q1. Write a java program to count the number of integers from a given list.(Use
command line arguments).

import java.util.Scanner;

public class setaq1 {


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

System.out.println("Enter a list of values separated by spaces:");

String input = scanner.nextLine();

String[] inputs = input.split(" ");

int count = 0;

for (String arg : inputs) {


try {
Integer.parseInt(arg);
count++;
} catch (NumberFormatException e) {
}
}

System.out.println("Number of integers in the given list: " + count);

scanner.close();
}
}

89
90

90
91

Q2. Write a java program to check whether given candidate is eligible for voting or not.
Handle user defined as well as system defined Exception.

import java.util.*;

class UnderageException extends Exception {


public UnderageException(String message) {
super(message);
}
}

public class setaq2 {

public static void checkEligibility(int age) throws UnderageException {


if (age < 18) {
throw new UnderageException("You are under 18, not eligible for voting.");
} else {
System.out.println("You are eligible for voting.");
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter your age: ");
int age = scanner.nextInt();

checkEligibility(age);

} catch (InputMismatchException e) {
System.out.println("Error: Please enter a valid number for age.");

} catch (UnderageException e) {
System.out.println(e.getMessage());

91
92

} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
} finally {
scanner.close();
}
}
}

92
93

Q3. Write a java program to calculate the size of a file.

import java.io.File;

public class setaq3 {

public static void main(String[] args) {


String filePath = "path_to_your_file";
File file = new File(filePath);
if (file.exists()) {
long fileSizeInBytes = file.length();
System.out.println("File Size: " + fileSizeInBytes + " bytes");

double fileSizeInKB = (double) fileSizeInBytes / 1024;


System.out.printf("File Size: %.2f KB%n", fileSizeInKB);

double fileSizeInMB = fileSizeInKB / 1024;


System.out.printf("File Size: %.2f MB%n", fileSizeInMB);
} else {
System.out.println("File not found.");
}
}
}

93
94

Q4. Write a java program to accept a number from a user, if it is zero then throw user
defined Exception “Number is Zero”. If it is non-numeric then generate an error “Number
is Invalid” otherwise check whether it is palindrome or not.

import java.util.Scanner;
class NumberIsZeroException extends Exception {
public NumberIsZeroException(String message) {
super(message);
}
}

public class setaq4 {

public static boolean isPalindrome(int number) {


int originalNumber = number;
int reverse = 0;
while (number > 0) {
int digit = number % 10;
reverse = reverse * 10 + digit;
number /= 10;
}
return originalNumber == reverse;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
String input = scanner.nextLine();

if (!input.matches("\\d+")) {
throw new NumberFormatException("Number is Invalid.");
}

int number = Integer.parseInt(input);

94
95

if (number == 0) {
throw new NumberIsZeroException("Number is Zero.");
}

if (isPalindrome(number)) {
System.out.println(number + " is a palindrome.");
} else {
System.out.println(number + " is not a palindrome.");
}

} catch (NumberFormatException e) {
System.out.println(e.getMessage());

} catch (NumberIsZeroException e) {
System.out.println(e.getMessage());

} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
} finally {
scanner.close();
}
}
}

95
96

Q5. Write a java program to accept a number from user, If it is greater than 100 then
throw user defined exception “Number is out of Range” otherwise do the addition of
digits of that number. (Use static keyword)

import java.util.Scanner;
class NumberOutOfRangeException extends Exception {
public NumberOutOfRangeException(String message) {
super(message);
}
}

public class setaq5 {

public static int sumOfDigits(int number) {


int sum = 0;
while (number > 0) {
sum += number % 10;
number /= 10;
}
return sum;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
int number = scanner.nextInt();

if (number > 100) {


throw new NumberOutOfRangeException("Number is out of Range.");
}

int sum = sumOfDigits(number);


System.out.println("The sum of digits of " + number + " is: " + sum);

96
97

} catch (NumberOutOfRangeException e) {
System.out.println(e.getMessage());

} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
} finally {
scanner.close();
}
}
}

97
98

Set B
Q1. Write a java program to copy the data from one file into another file, while copying
change the case of characters in target file and replaces all digits by ‘*’ symbol.

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class setbq1 {

public static char modifyChar(char ch) {


if (Character.isDigit(ch)) {
return '*';
}
else if (Character.isUpperCase(ch)) {
return Character.toLowerCase(ch);
}
else if (Character.isLowerCase(ch)) {
return Character.toUpperCase(ch);
}
return ch;
}

public static void main(String[] args) {


String sourceFilePath = "source.txt";
String targetFilePath = "target.txt";

try (FileReader fileReader = new FileReader(sourceFilePath);


FileWriter fileWriter = new FileWriter(targetFilePath)) {

int character;

while ((character = fileReader.read()) != -1) {


char modifiedChar = modifyChar((char) character);

98
99

fileWriter.write(modifiedChar);
}

System.out.println("File copied with modifications successfully.");

} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}

99
100

Q2. Write a java program to accept string from a user. Write ASCII values of the
characters from a string into the file.

import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class setbq2 {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();

String filePath = "ascii_output.txt";

try (FileWriter fileWriter = new FileWriter(filePath)) {


for (int i = 0; i < inputString.length(); i++) {
char ch = inputString.charAt(i);
int asciiValue = (int) ch;

fileWriter.write("Character: " + ch + " ASCII: " + asciiValue + "\n");


}

System.out.println("ASCII values have been written to the file successfully.");

} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
} finally {
scanner.close();
}
}
}

100
101

101
102

Q3. Write a java program to accept a number from a user, if it less than 5 then throw
user defined Exception “Number is small”, if it is greater than 10 then throw user defined
exception “Number is Greater”, otherwise calculate its factorial.

import java.util.Scanner;

class NumberIsSmallException extends Exception {


public NumberIsSmallException(String message) {
super(message);
}
}

class NumberIsGreaterException extends Exception {


public NumberIsGreaterException(String message) {
super(message);
}
}

public class setbq3 {

public static int factorial(int number) {


int fact = 1;
for (int i = 1; i <= number; i++) {
fact *= i;
}
return fact;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

try {
System.out.print("Enter a number: ");
int number = scanner.nextInt();

102
103

if (number < 5) {
throw new NumberIsSmallException("Number is small.");
}

if (number > 10) {


throw new NumberIsGreaterException("Number is Greater.");
}

int result = factorial(number);


System.out.println("The factorial of " + number + " is: " + result);

} catch (NumberIsSmallException | NumberIsGreaterException e) {


System.out.println(e.getMessage());

} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
} finally {
scanner.close();
}
}
}

103
104

Q4. Write a java program to display contents of a file in reverse order.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Stack;

public class setbq4 {

public static void main(String[] args) {


String filePath = "example.txt";

try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {


Stack<String> linesStack = new Stack<>();

String line;
while ((line = reader.readLine()) != null) {
linesStack.push(line);
}

System.out.println("File content in reverse order:");


while (!linesStack.isEmpty()) {
System.out.println(linesStack.pop());
}

} catch (IOException e) {
System.out.println("An error occurred while reading the file: " + e.getMessage());
}
}
}

104
105

105
106

Q5. Write a java program to display each word from a file in reverse order.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class setbq5 {

public static String reverseWord(String word) {


return new StringBuilder(word).reverse().toString();
}

public static void main(String[] args) {


String filePath = "example.txt";

try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {


String line;

System.out.println("Each word in reverse order:");

while ((line = reader.readLine()) != null) {


String[] words = line.split("\\s+");

for (String word : words) {


System.out.print(reverseWord(word) + " ");
}
System.out.println();
}

} catch (IOException e) {
System.out.println("An error occurred while reading the file: " + e.getMessage());
}
}
}

106
107

107
108

Set C
Q1.Write a java program to accept list of file names through command line. Delete the
files having extension .txt. Display name, location and size of remaining files.

import java.io.File;

public class setcq1 {

public static void main(String[] args) {


if (args.length == 0) {
System.out.println("Please provide file names as command-line arguments.");
return;
}

for (String fileName : args) {


File file = new File(fileName);

if (file.exists()) {
if (fileName.endsWith(".txt")) {
if (file.delete()) {
System.out.println("Deleted: " + file.getName());
} else {
System.out.println("Failed to delete: " + file.getName());
}
} else {
System.out.println("File Name: " + file.getName());
System.out.println("File Location: " + file.getAbsolutePath());
System.out.println("File Size: " + file.length() + " bytes");
System.out.println();
}
} else {
System.out.println("File does not exist: " + fileName);
}
}
}

108
109

109
110

Q2. Write a java program to display the files having extension .txt from a given directory

import java.io.File;

public class setcq2 {

public static void main(String[] args) {


if (args.length != 1) {
System.out.println("Usage: java SimpleFileLister <directory-path>");
return;
}

File directory = new File(args[0]);

if (directory.isDirectory()) {
File[] files = directory.listFiles();

if (files != null) {
for (File file : files) {
if (file.isFile() && file.getName().endsWith(".txt")) {
System.out.println(file.getName());
}
}
} else {
System.out.println("Error reading directory.");
}
} else {
System.out.println("Not a directory.");
}
}
}

110
111

111
112

Q3.Write a java program to count number of lines, words and characters from a given
file.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class setcq3 {

public static void main(String[] args) {


if (args.length != 1) {
System.out.println("Usage: java FileStats <file-path>");
return;
}

String filePath = args[0];


int lineCount = 0;
int wordCount = 0;
int charCount = 0;

try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {


String line;
while ((line = reader.readLine()) != null) {
lineCount++;
charCount += line.length();

String[] words = line.split("\\s+");


wordCount += words.length;
}

System.out.println("Lines: " + lineCount);


System.out.println("Words: " + wordCount);
System.out.println("Characters: " + charCount);

} catch (IOException e) {

112
113

System.out.println("Error reading file: " + e.getMessage());


}
}
}

113
114

Q4. Write a java program to read the characters from a file, if a character is alphabet
then reverse its case, if not then display its category on the Screen. (whether it is Digit
or Space)

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class setcq4 {

public static void main(String[] args) {


if (args.length != 1) {
System.out.println("Usage: java CharacterProcessor <file-path>");
return;
}

String filePath = args[0];

try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {


int ch;
while ((ch = reader.read()) != -1) {
char character = (char) ch;

if (Character.isLetter(character)) {
if (Character.isUpperCase(character)) {
System.out.print(Character.toLowerCase(character));
} else {
System.out.print(Character.toUpperCase(character));
}
} else {
if (Character.isDigit(character)) {
System.out.println(character + " is a Digit");
} else if (Character.isWhitespace(character)) {
System.out.println("Space");
} else {

114
115

System.out.println(character + " is a Special Character");


}
}
}
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
}
}

115
116

Q5. Write a java program to validate PAN number and Mobile Number. If it is invalid
then throw user defined Exception “Invalid Data”, otherwise display it

import java.util.Scanner;
import java.util.regex.Pattern;

class InvalidDataException extends Exception {


public InvalidDataException(String message) {
super(message);
}
}

public class setcq5 {

public static void validatePAN(String pan) throws InvalidDataException {


String panRegex = "^[A-Z]{5}[0-9]{4}[A-Z]$";
if (!Pattern.matches(panRegex, pan)) {
throw new InvalidDataException("Invalid PAN number");
}
}

public static void validateMobile(String mobile) throws InvalidDataException {


String mobileRegex = "^[0-9]{10}$";
if (!Pattern.matches(mobileRegex, mobile)) {
throw new InvalidDataException("Invalid Mobile number");
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter PAN number: ");


String pan = scanner.nextLine();

System.out.print("Enter Mobile number: ");

116
117

String mobile = scanner.nextLine();

try {
validatePAN(pan);
System.out.println("Valid PAN number: " + pan);

validateMobile(mobile);
System.out.println("Valid Mobile number: " + mobile);

} catch (InvalidDataException e) {
System.out.println(e.getMessage());
} finally {
scanner.close();
}
}
}

117
118

Assignment No. 5: Applet, AWT, Event and Swing Programming


Set A
Q1. Write a program that asks the user's name, and then greets the user by name.
Before outputting the user's name, convert it to upper case letters. For example, if the
user's name is Raj, then the program should respond "Hello, RAJ, nice to meet you!".

import java.util.Scanner;

public class setaq1 {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Please enter your name: ");


String name = scanner.nextLine();

String upperCaseName = name.toUpperCase();

System.out.println("Hello, " + upperCaseName + ", nice to meet you!");

scanner.close();
}
}

118
119

Q2. Write a program that reads one line of input text and breaks it up into words. The
words should be output one per line. A word is defined to be a sequence of letters. Any
characters in the input that are not letters should be discarded. For example, if the user
inputs the line He said, "That's not a good idea." then the output of the program should
be
he
said
thats
not
a
good
idea

import java.util.*;

public class setaq2 {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter a line of text: ");


String input = scanner.nextLine();

Pattern pattern = Pattern.compile("[a-zA-Z]+");


Matcher matcher = pattern.matcher(input);

while (matcher.find()) {
System.out.println(matcher.group());
}

scanner.close();
}
}

119
120

120
121

Q3. Write a program that will read a sequence of positive real numbers entered by the
user and will print the same numbers in sorted order from smallest to largest. The user
will input a zero to mark the end of the input. Assume that at most 100 positive numbers
will be entered.

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

public class setaq3 {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

double[] numbers = new double[100];


int count = 0;

System.out.println("Enter positive real numbers (enter 0 to end):");

while (true) {
double number = scanner.nextDouble();

if (number == 0) {
break;
}

if (number > 0) {
if (count < numbers.length) {
numbers[count++] = number;
} else {
System.out.println("The limit of 100 numbers has been reached.");
break;
}
} else {
System.out.println("Please enter a positive number.");
}

121
122

Arrays.sort(numbers, 0, count);

System.out.println("Numbers in sorted order:");


for (int i = 0; i < count; i++) {
System.out.println(numbers[i]);
}

scanner.close();
}
}

122
123

Q4. Create an Applet that displays the x and y position of the cursor movement using
Mouse and Keyboard. (Use appropriate listener).

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

public class seta extends JFrame implements MouseMotionListener, KeyListener {


private int mouseX = 0;
private int mouseY = 0;
private String keyPressed = "None";

public seta() {
setTitle("Mouse and Keyboard Example");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

JPanel panel = new JPanel() {


@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("Mouse X: " + mouseX, 20, 50);
g.drawString("Mouse Y: " + mouseY, 20, 70);
g.drawString("Key Pressed: " + keyPressed, 20, 90);
}
};

panel.addMouseMotionListener(this);
panel.addKeyListener(this);
panel.setFocusable(true); // To receive keyboard events
add(panel, BorderLayout.CENTER);

setVisible(true);
}

123
124

@Override
public void mouseDragged(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
repaint();
}

@Override
public void mouseMoved(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
repaint();
}

@Override
public void keyPressed(KeyEvent e) {
keyPressed = "Key Code: " + e.getKeyCode();
repaint();
}

@Override
public void keyReleased(KeyEvent e) {
keyPressed = "None";
repaint();
}

@Override
public void keyTyped(KeyEvent e) { }

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> new seta());
}
}

124
125

125
126

Q5. Create the following GUI screen using appropriate layout managers.

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

public class setaq5 {

public static void main(String[] args) {


JFrame frame = new JFrame("Number Addition");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);

JPanel panel = new JPanel();


panel.setLayout(new GridLayout(4, 2, 10, 10));

JLabel firstLabel = new JLabel("First Number:");


JTextField firstText = new JTextField();

JLabel secondLabel = new JLabel("Second Number:");


JTextField secondText = new JTextField();

JLabel resultLabel = new JLabel("Result:");

126
127

JTextField resultText = new JTextField();


resultText.setEditable(false);

panel.add(firstLabel);
panel.add(firstText);
panel.add(secondLabel);
panel.add(secondText);
panel.add(resultLabel);
panel.add(resultText);

JPanel buttonPanel = new JPanel();


buttonPanel.setLayout(new FlowLayout());

JButton addButton = new JButton("Add");


JButton clearButton = new JButton("Clear");
JButton exitButton = new JButton("Exit");

buttonPanel.add(addButton);
buttonPanel.add(clearButton);
buttonPanel.add(exitButton);

addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
double num1 = Double.parseDouble(firstText.getText());
double num2 = Double.parseDouble(secondText.getText());
double sum = num1 + num2;
resultText.setText(Double.toString(sum));
} catch (NumberFormatException ex) {
resultText.setText("Invalid input");
}
}
});

127
128

clearButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
firstText.setText("");
secondText.setText("");
resultText.setText("");
}
});

exitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});

frame.add(panel, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.SOUTH);

frame.setVisible(true);
}
}

128
129

Set B
Q1. Write a java program to implement a simple arithmetic calculator. Perform
appropriate validations.

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

public class setbq1 extends JFrame {


private JTextField textField;
private StringBuilder input = new StringBuilder();
private double num1 = 0;
private String operator = "";

public setbq1() {
setTitle("Simple Calculator");
setSize(250, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

textField = new JTextField();


add(textField, BorderLayout.NORTH);

JPanel panel = new JPanel();


panel.setLayout(new GridLayout(4, 4));

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

129
130

for (String text : buttons) {


JButton button = new JButton(text);
button.addActionListener(new ButtonClickListener());
panel.add(button);
}

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

private class ButtonClickListener implements ActionListener {


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

switch (command) {
case "=":
calculate();
break;
case "+":
case "-":
case "*":
case "/":
if (input.length() > 0) {
num1 = Double.parseDouble(input.toString());
operator = command;
input.setLength(0);
}
break;
default:
input.append(command);
break;
}

130
131

textField.setText(input.toString());
}

private void calculate() {


if (operator.isEmpty() || input.length() == 0) return;
double num2 = Double.parseDouble(input.toString());
double result = 0;

switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 != 0) {
result = num1 / num2;
} else {
JOptionPane.showMessageDialog(null, "Error: Division by zero");
return;
}
break;
}
input.setLength(0);
input.append(result);
operator = "";
textField.setText(input.toString());
}
}

131
132

public static void main(String[] args) {


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

132
133

Q2. Write a java program to implement following. Program should handle appropriate
events.

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

public class setbq2 {

public static void main(String[] args) {


JFrame frame = new JFrame("Menu Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);

JMenuBar menuBar = new JMenuBar();

JMenu fileMenu = new JMenu("File");


JMenu editMenu = new JMenu("Edit");
JMenu searchMenu = new JMenu("Search");

menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(searchMenu);

frame.setJMenuBar(menuBar);

133
134

JPanel buttonPanel = new JPanel();


buttonPanel.setLayout(new GridLayout(5, 1, 10, 10));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30)); //
Padding around buttons

JButton undoButton = new JButton(new ImageIcon("undo_icon.png"));


undoButton.setText("Undo");
JButton redoButton = new JButton(new ImageIcon("redo_icon.png"));
redoButton.setText("Redo");
JButton cutButton = new JButton(new ImageIcon("cut_icon.png"));
cutButton.setText("Cut");
JButton copyButton = new JButton(new ImageIcon("copy_icon.png"));
copyButton.setText("Copy");
JButton pasteButton = new JButton(new ImageIcon("paste_icon.png"));
pasteButton.setText("Paste");

buttonPanel.add(undoButton);
buttonPanel.add(redoButton);
buttonPanel.add(cutButton);
buttonPanel.add(copyButton);
buttonPanel.add(pasteButton);

frame.add(buttonPanel, BorderLayout.CENTER);

undoButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Undo action performed");
}
});

redoButton.addActionListener(new ActionListener() {
@Override

134
135

public void actionPerformed(ActionEvent e) {


JOptionPane.showMessageDialog(frame, "Redo action performed");
}
});

cutButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Cut action performed");
}
});

copyButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Copy action performed");
}
});

pasteButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Paste action performed");
}
});

frame.setVisible(true);
}
}

135
136

136
137

Q3. Write an applet application to draw Temple

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

public class TempleDrawingSwing extends JFrame {

public TempleDrawingSwing() {
setTitle("Temple Drawing");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new TemplePanel());
setVisible(true);
}

private class TemplePanel extends JPanel {


@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

setBackground(Color.cyan);

g.setColor(Color.orange);
g.fillRect(100, 200, 200, 150); // Main body of the temple

g.setColor(Color.red);
int[] xPoints = {100, 200, 300};
int[] yPoints = {200, 100, 200};
g.fillPolygon(xPoints, yPoints, 3);

g.setColor(Color.black);
g.fillRect(170, 250, 60, 100); // Door

g.setColor(Color.gray);
g.fillRect(130, 200, 20, 100); // Left pillar

137
138

g.fillRect(250, 200, 20, 100); // Right pillar

g.setColor(Color.yellow);
g.fillRect(190, 130, 20, 10); // Top decorative block

g.setColor(Color.green);
g.fillRect(150, 280, 20, 20); // Flower pot left
g.fillRect(240, 280, 20, 20); // Flower pot right
}
}

public static void main(String[] args) {


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

138
139

Q4. Write an applet application to display Table lamp. The color of lamp should get
change in random color.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

public class TableLampSwing extends JFrame {


private JPanel lampPanel;
private Color lampColor;
private Random random;

public TableLampSwing() {
setTitle("Table Lamp");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

random = new Random();


lampPanel = new LampPanel();
add(lampPanel, BorderLayout.CENTER);

JButton changeColorButton = new JButton("Change Lamp Color");


changeColorButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
changeLampColor();
lampPanel.repaint();
}
});
add(changeColorButton, BorderLayout.SOUTH);

setVisible(true);

139
140

private void changeLampColor() {


int r = random.nextInt(256);
int g = random.nextInt(256);
int b = random.nextInt(256);
lampColor = new Color(r, g, b);
}

private class LampPanel extends JPanel {


@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

g.setColor(Color.gray);
g.fillRect(150, 250, 100, 20);

g.setColor(Color.darkGray);
g.fillRect(180, 150, 40, 100);

g.setColor(lampColor);
g.fillArc(150, 100, 100, 80, 0, 180);
g.setColor(Color.lightGray);
g.fillRect(150, 180, 100, 10);

g.setColor(Color.yellow);
g.fillOval(190, 200, 30, 30);
}
}

public static void main(String[] args) {


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

140
141

141
142

Q5. Write a java program to design email registration form.( Use maximum Swing
component in form).

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

public class EmailRegistrationForm extends JFrame {

public EmailRegistrationForm() {
setTitle("Email Registration Form");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();

JLabel nameLabel = new JLabel("Name:");


JTextField nameField = new JTextField(20);

JLabel emailLabel = new JLabel("Email:");


JTextField emailField = new JTextField(20);

JLabel passwordLabel = new JLabel("Password:");


JPasswordField passwordField = new JPasswordField(20);

JLabel genderLabel = new JLabel("Gender:");


JRadioButton maleButton = new JRadioButton("Male");
JRadioButton femaleButton = new JRadioButton("Female");
ButtonGroup genderGroup = new ButtonGroup();
genderGroup.add(maleButton);
genderGroup.add(femaleButton);

JLabel countryLabel = new JLabel("Country:");

142
143

String[] countries = {"Select", "USA", "Canada", "UK", "Australia"};


JComboBox<String> countryComboBox = new JComboBox<>(countries);

JLabel termsLabel = new JLabel("Accept Terms:");


JCheckBox termsCheckBox = new JCheckBox("I agree to the terms and
conditions.");

JButton submitButton = new JButton("Submit");


JButton resetButton = new JButton("Reset");

gbc.insets = new Insets(5, 5, 5, 5);

gbc.gridx = 0; gbc.gridy = 0;
add(nameLabel, gbc);
gbc.gridx = 1; gbc.gridy = 0;
add(nameField, gbc);

gbc.gridx = 0; gbc.gridy = 1;
add(emailLabel, gbc);
gbc.gridx = 1; gbc.gridy = 1;
add(emailField, gbc);

gbc.gridx = 0; gbc.gridy = 2;
add(passwordLabel, gbc);
gbc.gridx = 1; gbc.gridy = 2;
add(passwordField, gbc);

gbc.gridx = 0; gbc.gridy = 3;
add(genderLabel, gbc);
gbc.gridx = 1; gbc.gridy = 3;
JPanel genderPanel = new JPanel();
genderPanel.add(maleButton);
genderPanel.add(femaleButton);
add(genderPanel, gbc);

143
144

gbc.gridx = 0; gbc.gridy = 4;
add(countryLabel, gbc);
gbc.gridx = 1; gbc.gridy = 4;
add(countryComboBox, gbc);

gbc.gridx = 0; gbc.gridy = 5;
add(termsLabel, gbc);
gbc.gridx = 1; gbc.gridy = 5;
add(termsCheckBox, gbc);

gbc.gridx = 0; gbc.gridy = 6;
add(submitButton, gbc);
gbc.gridx = 1; gbc.gridy = 6;
add(resetButton, gbc);

submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(EmailRegistrationForm.this, "Registration
Successful!");
}
});

resetButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Reset the form
nameField.setText("");
emailField.setText("");
passwordField.setText("");
genderGroup.clearSelection();
countryComboBox.setSelectedIndex(0);
termsCheckBox.setSelected(false);

144
145

}
});
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
new EmailRegistrationForm().setVisible(true);
});
}
}

145
146

Set C
Q1. Write a java program to accept the details of employee employee eno,ename, sal
and display it on next frame using appropriate even .

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

public class EmployeeDetailsApp {

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> new EmployeeInputFrame().setVisible(true));
}
}

class EmployeeInputFrame extends JFrame {


private JTextField enoField;
private JTextField enameField;
private JTextField salField;

public EmployeeInputFrame() {
setTitle("Employee Details Input");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(4, 2, 5, 5));

JLabel enoLabel = new JLabel("Employee Number:");


enoField = new JTextField();
JLabel enameLabel = new JLabel("Employee Name:");
enameField = new JTextField();
JLabel salLabel = new JLabel("Salary:");
salField = new JTextField();

JButton submitButton = new JButton("Submit");

146
147

add(enoLabel);
add(enoField);
add(enameLabel);
add(enameField);
add(salLabel);
add(salField);
add(new JLabel());
add(submitButton);

submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String eno = enoField.getText();
String ename = enameField.getText();
String sal = salField.getText();

try {
double salary = Double.parseDouble(sal);
new EmployeeDetailsFrame(eno, ename, salary).setVisible(true);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(EmployeeInputFrame.this,
"Invalid salary input. Please enter a numeric value.",
"Input Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
}
}

class EmployeeDetailsFrame extends JFrame {


public EmployeeDetailsFrame(String eno, String ename, double salary) {
setTitle("Employee Details");

147
148

setSize(300, 200);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLayout(new GridLayout(3, 1, 5, 5));

JLabel enoLabel = new JLabel("Employee Number: " + eno);


JLabel enameLabel = new JLabel("Employee Name: " + ename);
JLabel salLabel = new JLabel("Salary: Rs" + String.format("%.2f", salary));

add(enoLabel);
add(enameLabel);
add(salLabel);
}
}

148
149

Q2. Write a java program to display at least five records of employee in JTable.( Eno,
Ename ,Sal).

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;

public class EmployeeTableExample {

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> new EmployeeTableFrame().setVisible(true));
}
}

class EmployeeTableFrame extends JFrame {


public EmployeeTableFrame() {
setTitle("Employee Records");
setSize(600, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

String[] columnNames = {"Employee Number", "Employee Name", "Salary"};

Object[][] data = {
{"E001", "John Doe", 50000},
{"E002", "Jane Smith", 60000},
{"E003", "Alice Johnson", 55000},
{"E004", "Bob Brown", 62000},
{"E005", "Charlie Davis", 47000}
};

DefaultTableModel tableModel = new DefaultTableModel(data, columnNames);


JTable table = new JTable(tableModel);

JScrollPane scrollPane = new JScrollPane(table);

149
150

add(scrollPane, BorderLayout.CENTER);
}
}

150
151

Q4. Write a java Program to change the color of frame. If user clicks on close button
then the position of frame should get change.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Random;

public class ColorChangeFrameExample {

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> new ColorChangeFrame().setVisible(true));
}
}

class ColorChangeFrame extends JFrame {

private JButton colorChangeButton;

public ColorChangeFrame() {
setTitle("Color Change Frame");
setSize(400, 300);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setLocationRelativeTo(null); // Center the frame on the screen

colorChangeButton = new JButton("Change Color");


colorChangeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
changeFrameColor();
}
});

151
152

add(colorChangeButton, BorderLayout.CENTER);

addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
changeFramePosition();
}
});
}

private void changeFrameColor() {


Random rand = new Random();
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();
getContentPane().setBackground(new Color(r, g, b));
}

private void changeFramePosition() {


int x = new Random().nextInt(Toolkit.getDefaultToolkit().getScreenSize().width -
getWidth());
int y = new Random().nextInt(Toolkit.getDefaultToolkit().getScreenSize().height -
getHeight());
setLocation(x, y);
}
}

152
153

153
154

Q4. Write a java program to display following screen.

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

public class CompoundInterestCalculator extends JFrame {

private JTextField principalField, rateField, timeField, totalAmountField,


interestAmountField;
private JButton calculateButton, clearButton, closeButton;

public CompoundInterestCalculator() {
setTitle("Compound Interest Calculator");
setSize(400, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 5, 5, 5);

154
155

JLabel titleLabel = new JLabel("Compound Interest Calculator");


titleLabel.setFont(new Font("Arial", Font.BOLD, 16));
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 3;
gbc.anchor = GridBagConstraints.CENTER;
add(titleLabel, gbc);

JLabel principalLabel = new JLabel("Principal Amount:");


gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 1;
gbc.anchor = GridBagConstraints.WEST;
add(principalLabel, gbc);

principalField = new JTextField();


gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridwidth = 2;
add(principalField, gbc);

JLabel rateLabel = new JLabel("Interest Rate (%):");


gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 1;
add(rateLabel, gbc);

rateField = new JTextField();


gbc.gridx = 1;
gbc.gridy = 2;
gbc.gridwidth = 1;
add(rateField, gbc);

155
156

JLabel timeLabel = new JLabel("Time (Yrs):");


gbc.gridx = 0;
gbc.gridy = 3;
add(timeLabel, gbc);

timeField = new JTextField();


gbc.gridx = 1;
gbc.gridy = 3;
gbc.gridwidth = 2;
add(timeField, gbc);

JLabel totalAmountLabel = new JLabel("Total Amount:");


gbc.gridx = 0;
gbc.gridy = 4;
add(totalAmountLabel, gbc);

totalAmountField = new JTextField();


totalAmountField.setEditable(false);
gbc.gridx = 1;
gbc.gridy = 4;
gbc.gridwidth = 2;
add(totalAmountField, gbc);

JLabel interestAmountLabel = new JLabel("Interest Amount:");


gbc.gridx = 0;
gbc.gridy = 5;
add(interestAmountLabel, gbc);

interestAmountField = new JTextField();


interestAmountField.setEditable(false);
gbc.gridx = 1;
gbc.gridy = 5;
gbc.gridwidth = 2;
add(interestAmountField, gbc);

156
157

calculateButton = new JButton("Calculate");


gbc.gridx = 0;
gbc.gridy = 6;
gbc.gridwidth = 1;
add(calculateButton, gbc);

clearButton = new JButton("Clear");


gbc.gridx = 1;
gbc.gridy = 6;
add(clearButton, gbc);

closeButton = new JButton("Close");


gbc.gridx = 2;
gbc.gridy = 6;
add(closeButton, gbc);

calculateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
calculateInterest();
}
});

clearButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
clearFields();
}
});

closeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {

157
158

System.exit(0);
}
});
}

private void calculateInterest() {


try {
double principal = Double.parseDouble(principalField.getText());
double rate = Double.parseDouble(rateField.getText());
double time = Double.parseDouble(timeField.getText());

double amount = principal * Math.pow(1 + rate / 100, time);


double interest = amount - principal;

totalAmountField.setText(String.format("%.2f", amount));
interestAmountField.setText(String.format("%.2f", interest));

} catch (NumberFormatException ex) {


JOptionPane.showMessageDialog(this, "Please enter valid numbers!", "Input
Error", JOptionPane.ERROR_MESSAGE);
}
}

private void clearFields() {


principalField.setText("");
rateField.setText("");
timeField.setText("");
totalAmountField.setText("");
interestAmountField.setText("");
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
@Override

158
159

public void run() {


new CompoundInterestCalculator().setVisible(true);
}
});
}
}

159

You might also like