Practical Java Final
Practical Java Final
1
2
INDEX
2
3
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;
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;
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;
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.*;
if (isArmstrong(num)) {
armstrongNumbers.add(num);
}
}
scanner.close();
}
while (num != 0) {
9
10
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
13
14
14
15
Set C
Q1. Write a java program to count the frequency of each character in a given string.
import java.util.*;
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.
17
18
import java.util.*;
18
19
scanner.close();
}
}
19
20
import java.util.Scanner;
20
21
scanner.close();
}
}
21
22
Q5. Write a java program to display alternate character from a given string.
import java.util.Scanner;
scanner.close();
}
}
22
23
import java.util.Scanner;
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
import java.util.Scanner;
scanner.close();
}
24
25
Q3. Write a Java program to calculate area of Circle, Triangle & Rectangle.(Use Method
Overloading)
import java.util.Scanner;
25
26
scanner.close();
}
26
27
Q4. Write a Java program to Copy data of one object to another Object.
class setaq4 {
private String name;
private int age;
person2.copyFrom(person1);
System.out.println("Person 2 details after copying:");
person2.display();
}
}
27
28
28
29
import java.util.Scanner;
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";
}
30
31
scanner.close();
}
}
31
32
32
33
import java.util.Scanner;
class Product {
private int pid;
private String pname;
private double price;
33
34
System.out.println("\nProduct Details:");
double totalAmount = 0;
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;
@Override
public String toString() {
return "Roll No: " + rollno + ", Name: " + name + ", Percentage: " + per;
}
36
37
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 setbq4() {
this.number = 0;
}
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: ");
}
}
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;
class Result {
private double total;
private double percentage;
40
41
scanner.close();
}
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();
}
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;
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;
}
45
46
46
47
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;
49
50
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();
50
51
int n = scanner.nextInt();
scanner.nextLine();
acceptBookDetails(n);
scanner.close();
}
}
51
52
import java.util.Scanner;
class Shape {
protected double radius;
52
53
}
}
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();
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
@Override
public double area() {
return 4 * Math.PI * radius * radius;
}
}
54
55
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();
}
@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.");
}
}
}
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 setaq4() {
this.rollno = 0;
this.name = "Unknown";
count++;
displayCount();
}
@Override
public String toString() {
return "Student[Roll No: " + rollno + ", Name: " + name + "]";
}
58
59
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;
scanner.close();
Collections.reverse(numbers);
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)
@Override
double calc_area() {
return 4 * Math.PI * radius * radius;
}
@Override
double calc_volume() {
return (4.0 / 3) * Math.PI * Math.pow(radius, 3);
}
}
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;
}
}
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;
}
65
66
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);
@Override
public void display() {
super.display();
System.out.println("Bonus: " + bonus);
}
67
68
managers[i].accept();
}
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;
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;
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));
}
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"};
}
class Outdoor {
private String[] players;
public Outdoor() {
this.players = new String[]{"PlayerA", "PlayerB", "PlayerC"};
}
73
74
indoorGame.display();
outdoorGame.display();
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.*;
citySTD.put("Mumbai", "022");
citySTD.put("Delhi", "011");
citySTD.put("Bangalore", "080");
citySTD.put("Chennai", "044");
citySTD.put("Kolkata", "033");
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.*;
78
79
colors.addAll(indexYellow, newColors);
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;
@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
@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();
}
}
81
82
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--;
}
}
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();
}
@Override
public double area() {
return length * width;
}
}
@Override
public double area() {
return super.area();
84
85
}
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
85
86
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;
87
88
fibonacci.generate(n);
cube.generate(n);
square.generate(n);
scanner.close();
}
}
88
89
import java.util.Scanner;
int count = 0;
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.*;
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
import java.io.File;
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);
}
}
if (!input.matches("\\d+")) {
throw new NumberFormatException("Number is Invalid.");
}
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);
}
}
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;
int character;
98
99
fileWriter.write(modifiedChar);
}
} 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;
} 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;
try {
System.out.print("Enter a number: ");
int number = scanner.nextInt();
102
103
if (number < 5) {
throw new NumberIsSmallException("Number is small.");
}
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
} finally {
scanner.close();
}
}
}
103
104
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Stack;
String line;
while ((line = reader.readLine()) != null) {
linesStack.push(line);
}
} 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;
} 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;
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;
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;
} catch (IOException e) {
112
113
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;
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
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;
116
117
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
import java.util.Scanner;
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.*;
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;
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);
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 seta() {
setTitle("Mouse and Keyboard Example");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
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) { }
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;
126
127
panel.add(firstLabel);
panel.add(firstText);
panel.add(secondLabel);
panel.add(secondText);
panel.add(resultLabel);
panel.add(resultText);
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 setbq1() {
setTitle("Simple Calculator");
setSize(250, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
};
129
130
add(panel, BorderLayout.CENTER);
setVisible(true);
}
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());
}
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
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;
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(searchMenu);
frame.setJMenuBar(menuBar);
133
134
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
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
import javax.swing.*;
import java.awt.*;
public TempleDrawingSwing() {
setTitle("Temple Drawing");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new TemplePanel());
setVisible(true);
}
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.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
}
}
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 TableLampSwing() {
setTitle("Table Lamp");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setVisible(true);
139
140
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);
}
}
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 EmailRegistrationForm() {
setTitle("Email Registration Form");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
142
143
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
}
});
}
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 EmployeeInputFrame() {
setTitle("Employee Details Input");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(4, 2, 5, 5));
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);
}
}
});
}
}
147
148
setSize(300, 200);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLayout(new GridLayout(3, 1, 5, 5));
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.*;
Object[][] data = {
{"E001", "John Doe", 50000},
{"E002", "Jane Smith", 60000},
{"E003", "Alice Johnson", 55000},
{"E004", "Bob Brown", 62000},
{"E005", "Charlie Davis", 47000}
};
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 ColorChangeFrame() {
setTitle("Color Change Frame");
setSize(400, 300);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setLocationRelativeTo(null); // Center the frame on the screen
151
152
add(colorChangeButton, BorderLayout.CENTER);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
changeFramePosition();
}
});
}
152
153
153
154
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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
155
156
156
157
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);
}
});
}
totalAmountField.setText(String.format("%.2f", amount));
interestAmountField.setText(String.format("%.2f", interest));
158
159
159