Assignment No 1
• Set A:
1. Write a java Program to check whether given number is Prime or Not.
public class Prime {
public static void main(String[] args) { Scanner
sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();
boolean isPrime =
true; if (num <= 1)
{ isPrime = false; } else
{
for (int i = 2; i <= [Link](num); i++) {
if (num % i == 0) { isPrime = false;
break;}}}
if (isPrime) {
[Link](num + " is a Prime Number.");
} else {
[Link](num + " is NOT a Prime Number.");} [Link]();}}
2. Write a java Program to display all the perfect numbers between 1 to n.
public class Perfect { public static
void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the value of n: ");
int n = [Link]();
[Link]("Perfect numbers between 1 and " + n + " are:");
for (int num = 1; num <= n; num++) { int sum = 0; for (int i = 1; i <=
num / 2; i++) {
if (num % i == 0) { sum += i;}}
if (sum == num && num != 0)
{ [Link](num);}}
[Link]();}}
3. Write a java Program to accept employee name from a user and display it in reverse order.
public class Reverse { public static
void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter Employee Name: ");
String empName = [Link]();
String reversedName = new StringBuilder(empName).reverse().toString();
[Link]("Employee Name in Reverse Order: " + reversedName);
[Link](); }}
5. Write a java program to display the vowels from a given string.
public class Vowels { public static
void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();
[Link]("Vowels in the string: ");
str = [Link](); for
(int i = 0; i < [Link](); i++)
{ char ch = [Link](i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
[Link](ch + " "); }}
[Link](); }}
• Set B:
1. Write a java program to accept n city names and display them in ascending order.
public class Cname { public static
void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of cities: ");
int n = [Link]();
[Link](); // consume the newline
String[] cities = new String[n];
for (int i = 0; i < n; i++) {
[Link]("Enter city " + (i + 1) + ": ");
cities[i] = [Link](); }
[Link](cities);
[Link]("\nCities in Ascending Order:");
for (String city : cities)
{ [Link](city);
} [Link](); }}
2. Write a java program to accept n numbers from a user store only Armstrong numbers in an array and
display it.
public class Armstrong { static boolean
isArmstrong(int num) { int sum = 0,
temp = num, digits = 0; while (temp >
0) {
digits++; temp /= 10; }
temp = num; while (temp > 0) { int digit =
temp % 10; sum += [Link](digit, digits);
temp /= 10; } return sum == num; } public static
void main(String[] args) {
Scanner sc = new Scanner([Link]); [Link]("Enter
number of elements: ");
int n = [Link](); int[] numbers = new int[n]; int[] armstrong = new
int[n]; // store Armstrong numbers int count = 0; [Link]("Enter
" + n + " numbers:");
for (int i = 0; i < n; i++) { numbers[i] =
[Link](); if (isArmstrong(numbers[i])) {
armstrong[count++] = numbers[i]; } }
[Link]("\nArmstrong numbers are:");
if (count == 0) {
[Link]("No Armstrong numbers found.");
} else {
for (int i = 0; i < count; i++) {
[Link](armstrong[i] + " "); } } [Link]();
}}
3. Write a java program to search given name into the array, if it is found then display its index
otherwise display appropriate message.
public class Search { public static void
main(String[] args) {
Scanner sc = new Scanner([Link]); [Link]("Enter
number of names: ");
int n = [Link](); [Link]();
String[] names = new String[n];
for (int i = 0; i < n; i++) {
[Link]("Enter name " + (i + 1) + ": ");
names[i] = [Link](); }
[Link]("\nEnter name to search: ");
String searchName = [Link]();
int index = -1; for (int i = 0; i < n; i++) {
if (names[i].equalsIgnoreCase(searchName)) { // case-insensitive
index = i; break; } }
if (index == -1) {
[Link]("Name not found in the array.");
} else { [Link]("Name found at index: " + index); } [Link]();}}
4. Write a java program to display following pattern:
45
345
2345
12345
public class Pattern { public static
void main(String[] args) {
int n = 5; for (int i =
n; i >= 1; i--) { for (int j =
i; j <= n; j++) {
[Link](j + " "); }
[Link](); // new line after each row } }}
5. Write a java program to display following pattern:
01
010 1010 public class ZeroOne {
public static void main(String[] args) {
int n = 4; for (int i =
1; i <= n; i++) { for (int
j = 1; j <= i; j++) {
[Link]((i + j) % 2 + " "); }
[Link](); } }}
• Set C:
1. Write a java program to count the frequency of each character in a given string.
public class Char { public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();
HashMap<Character, Integer> freqMap = new HashMap<>();
for (int i = 0; i < [Link](); i++) { char ch = [Link](i); if (ch != '
') { [Link](ch, [Link](ch, 0) + 1); }
} [Link]("\nCharacter Frequencies:");
for (char key : [Link]()) {
[Link](key + " → " + [Link](key)); }
[Link](); }}
2. Write a java program to display each word in reverse order from a string array.
public class ReverseString{
public static void main(String[] args){
String words[]= {"Java", "Programming", "is" , "Fun"};
[Link]("Each word in reverse order:"); for(String
word : words){ String rev= "";
for(int i=[Link]() -1; i>=0; i--){ rev += [Link](i); }
[Link](rev);
}}}
3. Write a java program for union of two integer array.
public class Union{ public static void main(String[] args){ int arr1[]= {1, 2, 3 , 4, 5};
int arr2[]={4, 5, 6, 7, 8}; [Link]("Union of two arrays: "); for(int i=0;
i<[Link]; i++){ [Link](arr1[i] + " "); } for(int i=0; i< [Link]; i++)
{ boolean found =false; for(int j=0; j<[Link]; j++){ if(arr2[i] ==arr1[j]){ found
=true; break; } } if(!found){
[Link](arr2[i] +" "); } } } }
4. Write a java program to display transpose of given matrix.
public class TranposeMatrix{ public
static void main(String[] args){ int
matrix[][]={ {1, 2, 3}, {4, 5, 6}};
int rows=[Link]; int cols=matrix[0].length;
[Link]("original Matrix:"); for(int i=0;
i<rows; i++){ for(int j=0; j<cols; j++)
{ [Link](matrix[i][j] +" "); }
[Link](); }
[Link]("\nTranspose of Matrix: ");
for(int i=0; i<cols; i++){ for(int j=0; j<rows; j++){
[Link](matrix[j][i]+ " "); }
[Link](); } } }
5. Write a java program to display alternate character from a given string.
public class AlternateCharacter{ public
static void main(String[] args){
String str= "HELLOJAIPRAKASH";
[Link]("Alternate characters are: "); for(int
i=0; i<[Link](); i+=2){
[Link]([Link](i) + " ");
}}}
Assignment No 2
• Set A:
1. Write a Java program to calculate power of a number using recursion.
public class PowerRecursion{ static int power(int base, int
exp){ if(exp==0) return 1; return base*power(base, exp-
1); } public static void main(String[] args){ int base =2,
exponent=5; int result= power(base, exponent);
[Link](base+ " ^ "+ exponent+ " = "+ result); } }
2. Write a Java program to display Fibonacci series using function.
public class Fibonacci{ static void
printFibonacci(int n){ int a=0, b=1;
[Link]("Fibonacci Series: "); for (int
i=1; i<=n; i++){ [Link](a + " "); int
next = a+b; a=b; b=next; } } public static void
main(String[] args){ int n=10; printFibonacci(n);
}}
3. Write a Java program to calculate area of Circle, Triangle & Rectangle.(Use Method Overloading)
public class Areas{
double area(double radius){ return 3.14159*radius*radius; } double area(double
length, double breadth){ return length* breadth; } double area(double base, double
height, boolean isTriangle){ return 0.5 * base * height; } public static void main(String[]
args){
Areas obj= new Areas(); double circleArea= [Link](5.0);
double rectangleArea= [Link](4.0, 6.0);
Double triangleArea= [Link](5.0, 10.0, true);
[Link]("Area of circle= " + circleArea);
[Link]("Area of Rectangle = " + rectangleArea); [Link]("Area
of Triangle= " +triangleArea); } }
[Link] a Java program to Copy data of one object to another Object.
class CopyData{ String name; int age;
CopyData(String n, int a){ name=n;
age=a; }
CopyData(CopyData s){ [Link] =
[Link]; [Link] = [Link]; } void
display(){
[Link]("Name: "+ name + ", Age: "+age); } } public
class copyObject{ public static void main(String[] args){
CopyData s1 = new CopyData ("Kimaya", 20);
CopyData s2 = new CopyData (s1);
[Link]("original Object: "); [Link]();
[Link]("Copied Object:"); [Link]();
} }
5. Write a Java program to calculate factorial of a number using recursion.
public class Factorial{ static int
factorial(int n){ if (n==0 || n==1)
{ return 1; } else { return n*
factorial(n-1); } } public static void
main(String[] args){ int num=5; int
result=factorial(num);
[Link]("Factorial of " + num +" is: "+ result); } }
• Set B:
1. 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).
class Person { int pid; String pname;
int age; String gender; Person()
{ [Link] = 0; [Link] =
"Unknown"; [Link] = 0;
[Link] = "Not Specified"; }
Person(int pid, String pname, int age, String gender)
{ [Link] = pid; [Link] = pname;
[Link] = age; [Link] = gender; }
void display() {
[Link]("ID: " + [Link] + ", Name: " + [Link] +
", Age: " + [Link] + ", Gender: " + [Link]); }}
public class PersonDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Person persons[] = new Person[2];
for (int i = 0; i < 2; i++) {
[Link]("\nEnter details for Person " + (i + 1) + ":");
[Link]("Enter ID: "); int pid = [Link]();
[Link]();
[Link]("Enter Name: ");
String pname = [Link]();
[Link]("Enter Age: "); int age =
[Link](); [Link]();
[Link]("Enter Gender: "); String gender =
[Link](); persons[i] = new Person(pid, pname, age, gender); }
[Link](); [Link]("\n--- Person Details ---"); for (Person
p : persons) {
[Link](); } }}
2..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) class Product { int pid;
String pname; double price;
Product(int pid, String pname, double price)
{ [Link] = pid; [Link] = pname;
[Link] = price; } void display() {
[Link]("Product ID: " + pid + ", Name: " + pname + ", Price: " + price); }}
public class ProductArray { public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of products: "); int n
= [Link](); Product[] products = new Product[n];
double total = 0; for (int i = 0; i < n; i++) {
[Link]("\nEnter details of product " + (i + 1));
[Link]("Enter Product ID: ");
int pid = [Link](); [Link]();
[Link]("Enter Product Name: "); String pname = [Link]();
[Link]("Enter Product Price: "); double price = [Link](); products[i]
= new Product(pid, pname, price); total += price;
} [Link]("\n--- Product Details ---");
for (Product p : products) { [Link](); }
[Link]("\nTotal Amount: " + total);
[Link](); }}
3. Define a class Student(rollno,name,per). Create n objects of the student class and Display it using
toString().(Use parameterized constructor)
import [Link]; class Student{ int rollno;
String name; double per;
Student(int rollno, String name, double per) { [Link] = rollno; [Link] = name;
[Link] = per; } public String toString() { return "Roll No: " + rollno + ", Name: " +
name + ", Percentage: " + per; } } public class StudentDemo { public static void
main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of students: "); int n = [Link](); [Link]();
Student students[] = new Student[n]; for (int i = 0; i < n; i++) {
[Link]("\nEnter details for Student " + (i + 1));
[Link]("Roll No: "); int rollno = [Link]();
[Link]();
[Link]("Name: ");
String name = [Link]();
[Link]("Percentage: "); double per = [Link](); students[i]
= new Student(rollno, name, per); }
[Link]("\n--- Student Details ---"); for (int i = 0; i < n; i++) {
[Link](students[i]); } }}
4. 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.
Class MyNumber{ private int
num; MyNumber() {
[Link] = 0; }
MyNumber(int num) { [Link] = num; }
boolean isNegative() { return num < 0; } boolean
isPositive() { return num > 0; } }
public class MyNumberDemo {
public static void main(String[] args) { if ([Link] == 0) {
[Link]("Please pass a number as command line argument."); return; }
int value = [Link](args[0]);
MyNumber obj = new MyNumber(value);
[Link]("Number: " + value); if ([Link]()) {
[Link]("It is Positive");
} else if ([Link]()) {
[Link]("It is Negative");
} else { [Link]("It is Zero"); } }}
• Set C :
1. . 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 [Link]; class Student { int rno;
String name; int mark1, mark2;
Student(int rno, String name, int mark1, int mark2) { [Link] = rno; [Link] = name;
this.mark1 = mark1; this.mark2 = mark2;
} class Result { int total; double percentage; Result() {
total = mark1 + mark2; percentage = total / 2.0; } void
display() { [Link]("\n--- Mark Sheet ---");
[Link]("Roll No: " + rno);
[Link]("Name : " + name);
[Link]("Mark1 : " + mark1);
[Link]("Mark2 : " + mark2);
[Link]("Total : " + total);
[Link]("Percentage: " + percentage + "%"); } } } public
class StudentDemos{ public static void main(String[] args) {
Scanner sc = new Scanner([Link]); [Link]("Enter Roll No: "); int rno =
[Link](); [Link](); [Link]("Enter Name: ");
String name = [Link](); [Link]("Enter Mark1: "); int m1 = [Link]();
[Link]("Enter Mark2: "); int m2 = [Link]();
Student s = new Student(rno, name, m1, m2);
[Link] res = [Link] Result(); [Link](); }}
2. 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 [Link]; import [Link]; class Employee {
String name;
Employee(String name) { [Link] = name; } public
static void sortEmployees(Employee[] arr) {
[Link](arr, (e1, e2) -> [Link]([Link])); }
void display() { [Link](name); } } public class
EmployeeDemo { public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of employees: "); int n = [Link](); [Link]();
Employee[] employees = new Employee[n];
for (int i = 0; i < n; i++) {
[Link]("Enter name of employee " + (i + 1) + ": "); String name = [Link]();
employees[i] = new Employee(name); }
[Link](employees);
[Link]("\nEmployees in Ascending Order:"); for (Employee e : employees)
{ [Link](); } }}
3. 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 [Link]; class Player
{ int pid; String pname; int
totalRuns; int inningsPlayed; int
notOutTimes; double average;
Player(int pid, String pname, int totalRuns, int inningsPlayed, int notOutTimes) {
[Link] = pid; [Link] = pname; [Link] = totalRuns;
[Link] = inningsPlayed; [Link] = notOutTimes;
calculateAverage();} void calculateAverage() { int outs = inningsPlayed -
notOutTimes; if (outs > 0) { average = (double) totalRuns / outs; } else {
average = totalRuns; // If never out, treat average = totalRuns } } void
display() { [Link]("Player ID: " + pid);
[Link]("Player Name: " + pname);
[Link]("Total Runs: " + totalRuns);
[Link]("Innings Played: " + inningsPlayed);
[Link]("Not Out Times: " + notOutTimes);
[Link]("Batting Average: " + average); }} public
class CricketPlayerMaxAverage {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of players: ");int n = [Link]();
[Link](); Player[] players = new Player[n]; for (int i = 0; i <
n; i++) {
[Link]("\nEnter details for player " + (i + 1) + ":");
[Link]("Player ID: "); int pid = [Link](); [Link]();
[Link]("Player Name: "); String pname = [Link]();
[Link]("Total Runs: "); int totalRuns = [Link]();
[Link]("Innings Played: "); int inningsPlayed = [Link]();
[Link]("Not Out Times: "); int notOutTimes = [Link]();
players[i] = new Player(pid, pname, totalRuns, inningsPlayed, notOutTimes); }
Player maxAvgPlayer = players[0]; for (int i = 1; i < n; i++) { if
(players[i].average > [Link]) {maxAvgPlayer = players[i]; } }
[Link]("\nPlayer with Maximum Average:");
[Link](); [Link](); }}
4. Write a java program to accept details of ‘n’ books. And Display the quantity of given book.
import [Link];
class Book {
int id;
String name; String author; int quantity;
Book(int id, String name, String author, int quantity) {
[Link] = id; [Link] = name; [Link] =
author; [Link] = quantity; } void
display() {
[Link]("ID: " + id + ", Name: " + name +
", Author: " + author + ", Quantity: " + quantity); }}
public class BookDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]); [Link]("Enter
number of books: ");
int n = [Link](); [Link]();
Book[] books = new Book[n];
for (int i = 0; i < n; i++) {
[Link]("\nEnter details for Book " + (i + 1));
[Link]("Book ID: "); int id = [Link]();
[Link]();
[Link]("Book Name: ");
String name = [Link]();
[Link]("Author: ");
String author = [Link](); [Link]("Quantity: ");
int qty = [Link](); books[i] = new Book(id, name, author, qty); }
[Link]("\n--- Book Details ---"); for (Book b : books) {
[Link](); } [Link]();
[Link]("\nEnter Book Name to search quantity: ");
String searchName = [Link](); boolean found = false;
for (Book b : books) { if
([Link](searchName)) {
[Link]("Quantity of \"" + [Link] + "\" = " + [Link]);
found = true; break; } } if (!found) {
[Link]("Book not found!");
} [Link](); } }
Assignment No 3
• Set A:
1. Write a java program to calculate area of Cylinder and circle.(use super keyword).
class Circle{ double radius; Circle(double radius){ [Link]=radius;
} double area(){ return [Link]* radius*
radius; } } class Cylinder extends
Circle{ double height;
Cylinder(double radius, double height){ super(radius); [Link]= height;
} double area(){ return (2*[Link]())
+(2*[Link]*radius* height); } } public class
Main{ public static void main(String[] args){
Circle c=new Circle(5);
[Link]("Area of Circle: "+ [Link]());
Cylinder cy= new Cylinder(5, 10);
[Link]("Surface Area of Cylinder: "+ [Link]()); } }
[Link] an Interface Shape with abstract method area(). Write a java program to calculate an area of
Circle and Sphere. (use final Keyword)
interface Shape{ double area(); }
class Circle implements Shape{ final double PI= 3.14; double radius; Circle(double radius){
[Link]=radius; } public double area(){ return PI*radius*radius; } } class Sphere
implements Shape{ final double PI= 3.14; double radius;
Sphere(double radius){ [Link]= radius; }
public double area(){ return 4*PI*radius*radius; } }
public class Mou{ public static void main(String[]
args){
Circle c= new Circle(5);
[Link]("Area of Circle: "+[Link]());
Sphere s= new Sphere(5);
[Link]("Surface Area of sphere: "+[Link]()); } }
3. Define an interface “Integer” with a abstract method check(). Write a java program to check
whether a given number is positive or negative.
interface Integer{ void check(int num); } class NumberCheck implements
Integer{ public void check(int num){ if(num>0){
[Link](num + " is Positive");
} else if (num<0){
[Link](num + " is Negative");
} else {
[Link]("Number is Zero"); } } }
public class Number{ public static void
main(String[] args){
Scanner sc= new Scanner([Link]);
[Link]("Enter a number: "); int n= [Link](); NumberCheck
obj= new NumberCheck(); [Link](n);
[Link](); } }
[Link] a class Student with attributes rollno and name. Define default and parameterized
constructor. Override the to String() method. Keep the count of Objects created. Create object using
parameterized constructor and Display the object count after each object is created.
class Student{ int rollno; String name; static int count=0; Student(){
rollno=0;
name="Unknown"; count++; }
Student(int rollno, String name){ [Link]= rollno; [Link]=name; count++; }
public String toString(){ return "Roll No: " + rollno + ", Name: "+ name; } static
void displayCount(){
[Link]("Total Object Created: " + count); } }
public class Attributes{ public static void main(String[]
args){
Student s1= new Student(1, "Jaiprakash");
[Link](s1);
[Link]();
Student s2= new Student(2, "Ritesh");
[Link](s2); [Link]();
Student s3= new Student(3, "Radha");
[Link](s3);
[Link](); } }
5. 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.
public class Meena { public static
void main(String[] args) {
Scanner sc = new Scanner([Link]);
ArrayList<Integer> numbers = new ArrayList<>();
[Link]("Enter how many integers you want to store: "); int n = [Link]();
[Link]("Enter " + n + " integers:"); for (int i = 0; i < n; i++)
{ [Link]([Link]()); }
[Link]("\nOriginal List: " + numbers);
[Link](numbers);
[Link]("Reversed List: " + numbers); [Link](); }}
• Set B:
1. 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 void
calc_area(); abstract void calc_volume(); }
class Sphere extends Shape{ double radius;
Sphere(double r){ radius=r; } void
calc_area(){ double
area=4*[Link]*radius*radius;
[Link]("Sphere Surface Area=" + area); } void calc_volume(){ double
volume=(4.0/3.0)*[Link]*radius*radius*radius; [Link]("Sphere Volum
" +volume); } } class Cone extends Shape{ double radius, height; Cone(double r,
double h){ radius= r; height=h; } void calc_area(){
double slantHeight= [Link](radius*radius + height*height); double area=
[Link]*radius*(radius+ slantHeight);
[Link]("Cone Surface Area= " +area); } void
calc_volume(){
double volume=(1.0/3.0)* [Link]*radius*radius*height;
[Link]("Cone Volume = " +volume); } } public class
Areass{ public static void main(String[] args){ Sphere s= new Sphere(5);
s.calc_area(); s.calc_volume();
[Link](); Cone c= new Cone(3, 7); c.calc_area();
c.calc_volume(); } }
2. 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 [Link]; class Employee{ private
int id; private String name; private String
department; private double salary; Employee()
{ id= 0; name=""; department=""; salary=0.0; }
Employee(int id, String name, String dept, double salary){ [Link]=id;
[Link]=name; [Link]= dept;
[Link]=salary; } void accept(){
Scanner sc= new Scanner([Link]);
[Link]("Enter Employee ID: "); id= [Link](); [Link]();
[Link]("Enter Employee Name: "); name= [Link]();
[Link]("Enter Department: "); department=[Link]();
[Link]("Enter Salary: "); salary=[Link](); } void display(){
[Link]("ID: " +id);
[Link]("Name: " +name);
[Link]("Department: " +department);
[Link]("Salary: " +salary); }
double getSalary(){ return salary; } }
class Manager extends Employee{ private double bonus;
Manager(){ super(); bonus=0.0; }
Manager(int id, String name, String dept, double salary, double bonus){
super(id, name, dept, salary); [Link]= bonus; } void accept()
{ [Link]();
Scanner sc= new Scanner([Link]); [Link]("Enter Bonus: "); bonus=
[Link]();
} void display(){ [Link]();
[Link]("Bonus: " +bonus);
[Link]("Total Salary: " + (getSalary() + bonus)); }
double getTotalSalary(){ return getSalary() + bonus; } } public
class EmployeeTest{ public static void main(String[] args){
Scanner sc= new Scanner([Link]); [Link]("Enter number of managers: ");
int n= [Link]();
Manager[] managers= new Manager[n]; for(int i=0; i<n; i++){
[Link]("\nEnter details of Manager " + (i+1)); managers[i] = new Manager();
managers[i].accept();
} int maxIndex=0; for(int i=1; i<n; i++){ if(managers[i].getTotalSalary()>
managers[maxIndex].getTotalSalary()){ maxIndex=i; } } [Link]("\nManager
with Highest Total Salary: "); managers[maxIndex].display(); } }
3. 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.
public class LinkedList { public static void
main(String[] args) { LinkedList<String> list
= new LinkedList<>(); [Link]("CPP");
[Link]("Java"); [Link]("Python");
[Link]("PHP");
[Link]("List contents using Iterator:");
Iterator<String> itr = [Link](); while
([Link]()) {
[Link]([Link] }
[Link]("\nList contents in Reverse using ListIterator:");
ListIterator<String> listItr = [Link]([Link]()); while
([Link]()) {
[Link]([Link]()); }}}
4. 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 [Link].*; public class
EmployeeHashTable{
public static void main(String[] args){
Hashtable<String, Double> employees= new Hashtable<>();
[Link]("Raj", 50000.0); [Link]("Reema", 60000.0); [Link]("Raju", 55000.0);
[Link]("Rakesh", 80000.0); [Link]("Employee Details:"); for([Link]<String,
Double> entry : [Link]()){
[Link]("Name: " + [Link]() + ", Salary: " + [Link]()); }
Scanner sc= new Scanner([Link]);
[Link]("\nEnter employee name to search: ");
String name= [Link](); if([Link](name)){
[Link](name + "'s Salary= " +[Link](name));
} else{
[Link]("Employee not found."); } } }
• Set C:
1. 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.
public class CityHash { public
static void main(String[] args){
Hashtable<String, String> cities = new Hashtable<>();
[Link]("Mumbai", "022"); [Link]("Pune",
"020"); [Link]("Chennai", "044");
[Link]("Kolkata", "033"); [Link]("Delhi", "011");
[Link]("City Details: ");
for([Link]<String, String> entry : [Link]())
[Link]("City: " + [Link]() + ", STD Code: " + [Link]()); }
Scanner sc= new Scanner([Link]);
[Link]("\nEnter city name to search: ");
String city= [Link](); if([Link](city))
[Link](city + "'s STD Code = " + [Link](city)); } else{
[Link]("City not found. "); } } }
[Link] a Linked List containing name: red, blue, yellow and orange. Then extend yourprogram
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 [Link].*; public class
LinkedListColors{ public static
void main(String[] args){
LinkedList<String> colors = new LinkedList<>();
[Link]("red"); [Link]("orange");
[Link]("yellow"); [Link]("blue");
[Link]("Displaying using Iterator: ");
Iterator<String> it= [Link](); while([Link]())
{
[Link]([Link]()); }
[Link]("\nDisplaying in Reverse using ListIterators:"); ListIterator<String> listIt=
[Link]([Link]()); while([Link]()){
[Link]([Link]()); }
List<String> moreColors = new
ArrayList<>(); [Link]("pink");
[Link]("green"); int index=
[Link]("yellow");
[Link](index, moreColors);
[Link]("\nList after inserting pink & green between blue & yellow: ");
for(String color : colors){
[Link](color);
}}}
3. 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.
abstract class Staff {
String name; String address; Staff(String name, String address) {
[Link] = name; [Link] = address; } abstract void
display();} class FullTimeStaff extends Staff { String
department;double salary;
FullTimeStaff(String name, String address, String department, double salary)
{ super(name, address); [Link] = department;
[Link] = salary; } @Override void display() {
[Link]("Full Time Staff:");
[Link]("Name: " + name + ", Address: " + address +
", Department: " + department + ", Salary: " + salary); }}
class PartTimeStaff extends Staff { int
numberOfHours; double ratePerHour;
PartTimeStaff(String name, String address, int numberOfHours, double ratePerHour) {
super(name, address); [Link] = numberOfHours; [Link] =
ratePerHour; } @Override void display() { [Link]("Part Time Staff:");
[Link]("Name: " + name + ", Address: " + address +
", Hours: " + numberOfHours + ", Rate/hr: " + ratePerHour +
", Total Pay: " + (numberOfHours * ratePerHour)); }} public class
StaffDemo { public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of staff members: ");
int n = [Link](); [Link](); Staff[]
staffArray = new Staff[n]; for (int i = 0; i < n; i+
+) {
[Link]("\nEnter details for Staff " + (i + 1));
[Link]("Enter 1 for FullTimeStaff, 2 for PartTimeStaff: ");
int choice = [Link](); [Link]();
[Link]("Enter Name: "); String name = [Link]();
[Link]("Enter Address: ");
String address = [Link](); if (choice == 1) {
[Link]("Enter Department: ");
String dept = [Link](); [Link]("Enter Salary: ");
double salary = [Link](); staffArray[i] = new
FullTimeStaff(name, address, dept, salary); } else
{ [Link]("Enter Number of Hours: "); int hours =
[Link]();
[Link]("Enter Rate per Hour: "); double rate =
[Link](); staffArray[i] = new PartTimeStaff(name, address,
hours, rate); } } [Link]("\n--- Staff Details ---");
for (Staff s : staffArray) { [Link]();
[Link](); } [Link](); }}
4. 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 [Link]; interface
Shape { double area();} class
Rectangle implements Shape
{ double length, breadth;
Rectangle(double length, double breadth)
{ [Link] = length; [Link] = breadth; }
@Override public double area() {
return length * breadth; }} class
Square extends Rectangle
{ Square(double side)
{ super(side, side); }
@Override public
double area() { return
length * length; }}
class Circle implements Shape
{ double radius; Circle(double radius)
[Link] = radius; }
@Override public double area()
{ return [Link] * radius * radius; }}
public class ShapeDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter length and breadth of rectangle: ");
double l = [Link](); double b = [Link]();
Rectangle rect = new Rectangle(l, b);
[Link]("Enter side of square: ");
double s = [Link]();
Square sq = new Square(s);
[Link]("Enter radius of circle: ");
double r = [Link](); Circle c = new Circle(r);
[Link]("\n--- Areas of Shapes ---");
[Link]("Rectangle Area: " + [Link]());
[Link]("Square Area: " + [Link]());
[Link]("Circle Area: " + [Link]()); [Link]();
}
Assignment No 4
• Set A:
1. Write a java program to count the number of integers from a given list.(Use command
line arguments).
public class CountIntegers { public
static void main(String[] args) { int
count = [Link];
[Link]("Total number of integers entered: " + count);
if (count > 0) {
[Link]("The integers are:");
for (String num : args) {
[Link](num + " "); } } }}
2. Write a java program to check whether given candidate is eligible for voting or not.
Handle user defined as well as system defined Exception.
class NotEligibleException extends
Exception{ public NotEligibleException(String
message){ super(message); }} public class
VotingEligibility{ public static void
main(String[] args){ Scanner sc= new
Scanner([Link]); try{
[Link]("Enter Candidate name: ");
String name= [Link]();
[Link]("Enter age: "); String input= [Link](); int age=
[Link](input); if(age<18){ throw new NotEligibleException("Candidate is not
eligible for voting (Age must be 18+)."); }
[Link]("\u2705 " + name + " is eligible to vote!");
} catch (NumberFormatException e){
[Link]("\u274C Invalid input! Please enter a valid number for age.");
} catch (NotEligibleException e){
[Link]("\u274C " +[Link]());
} catch (Exception e){
[Link]("\u274C Unexcepted error: " + [Link]());
} finally{ [Link]();
}}
3. Write a java program to calculate the size of a file.
public class SizeCalculator { public static
void main(String[] args) { Scanner sc
= new Scanner([Link]);
[Link]("Enter the file path: ");
String filePath = [Link]();
File file = new File(filePath); if
([Link]() && [Link]())
{ long fileSizeBytes =
[Link]();
[Link]("File Name: " + [Link]());
[Link]("Size in Bytes: " + fileSizeBytes);
[Link]("Size in KB: " + (fileSizeBytes / 1024.0));
[Link]("Size in MB: " + (fileSizeBytes / (1024.0 * 1024)));
} else { [Link]("The specified file does not exist or is not a valid file.");
}
[Link](); }}
4. 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.
class NumberIsZeroException extends Exception{
public NumberIsZeroException(String message)
{ super(message); } } public class
PalindromeCheck{
public static void main(String[]args){
Scanner sc= new Scanner([Link]);
try{ [Link]("Enter a number: "); String
input= [Link](); int number=
[Link](input); if(number== 0){ throw new
NumberIsZeroException("Number is Zero");
} int original = number; int reversed=0; while(number>0){ int digit=
number%10; reversed= reversed * 10 + digit; number /= 10;
} if(original == reversed){
[Link]("\u2705 " + original + "is a Palindrome.");
} else {
[Link]("\u274C " + original + " is NOT a Palindrome.");
} } catch (NumberFormatException e){
[Link]("\u274C Number is Invalid (please enter digits only!");
} catch (NumberIsZeroException e){
[Link]("\u274C " +[Link]());
} catch (Exception e){
[Link]("\u274C Unexcepted Error: " + [Link]()); } finally { [Link](); }
}}
5. 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)
class NumberOutOf extends Exception { public
NumberOutOfRangeException(String message) {
super(message); }} public class
DigitAddition { public static int
sumOfDigits(int num) {
int sum = 0; while (num > 0) { sum +=
num % 10; num /= 10; } return sum; }
public static void main(String[] args) { Scanner
sc = new Scanner([Link]); try
{ [Link]("Enter a number: ");
int num = [Link](); if (num > 100) {
throw new NumberOutOfRangeException("Number is out of Range"); }
int sum = sumOfDigits(num);
[Link]("Sum of digits of " + num + " = " + sum); }
catch (NumberOutOfRangeException e) {
[Link]("User Defined Exception: " + [Link]()); }
catch (Exception e) { [Link]("System Exception: Invalid Input!"); }
finally { [Link]("Program execution completed."); }
[Link](); }}
• Set B:
1. 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.
public class FileCopyCaseChange
{ public static void main(String[] args)
{ String sourceFile = "[Link]";
String targetFile = "[Link]"; try (
FileReader fr = new FileReader(sourceFile);
FileWriter fw = new FileWriter(targetFile)
){ int ch;
while ((ch = [Link]()) != -1) {
char c = (char) ch; if
([Link](c)) {
[Link]('*'); }
else if ([Link](c))
{ [Link]([Link](c)); } else if
([Link](c))
{ [Link]([Link](c)); } else
{ [Link](c); // copy other characters as is } }
[Link]("File copied successfully with modifications!"); }
catch (IOException e) {
[Link]("Error while copying file: " + [Link]()); }}}
2. Write a java program to accept string from a user. Write ASCII values of the characters from
a string into the file.
public class
WriteAsciiToFile{ public static void
main(String[] args){ Scanner sc=
new
Scanner([Link]);
String fileName= "ascii_output.txt";
[Link]("Enter a string: "); String
input=[Link](); try( FileWriter fw= new
FileWriter(fileName); BufferedWriter bw= new
BufferedWriter(fw); ){
for(int i=0; i<[Link]();
i++){ char ch=
[Link](i); int ascii=
(int) ch; [Link](ch + " : "
+ ascii); [Link](); }
[Link]("ASCII values written successfully to " + fileName);
} catch (IOException e){
[Link]("Error writing to file: " + [Link]());
}}}
3. 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.
class NumberIsSmallException extends Exception
{ public NumberIsSmallException(String message) {
super(message);}}
class NumberIsGreaterException extends Exception {
public NumberIsGreaterException(String message) {
super(message); }} public class FactorialException {
public static long factorial(int num) { long fact =
1;
for (int i = 1; i <= num; i++) { fact *= i;
} return fact; } public static void
main(String[] args) { Scanner sc = new
Scanner([Link]); try
{ [Link]("Enter a number: ");
int num = [Link](); if (num < 5) {
throw new NumberIsSmallException("Number is small");
} else if (num > 10) {
throw new NumberIsGreaterException("Number is greater");
} else { long fact = factorial(num);
[Link]("Factorial of " + num + " is: " + fact); }
} catch (NumberIsSmallException e) {
[Link]("User Defined Exception: " + [Link]());
} catch (NumberIsGreaterException e) {
[Link]("User Defined Exception: " + [Link]());
} catch (Exception e) {
[Link]("Invalid input! Please enter an integer.");
} finally {
[Link]("Program execution completed.");
} [Link](); }}
4. Write a java program to display contents of a file in reverse order.
public class ReverseFileContent
{ public static void main(String[] args)
Scanner sc = new Scanner([Link]);
[Link]("Enter file name (with path if required): ");
String fileName = [Link]();
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
List<String> lines = new ArrayList<>();
String line; while ((line = [Link]()) != null)
{ [Link](line); } [Link]();
[Link]("\nContents of the file in reverse order:");
for (int i = [Link]() - 1; i >= 0; i--) {
[Link]([Link](i)); }
} catch (IOException e) { [Link]("Error: " + [Link]()); } [Link](); }}
5. Write a java program to display each word from a file in reverse order.
public class ReverseWordsInFile
{ public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the file name (with path if needed): ");
String fileName = [Link]();
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line;
[Link]("\nEach word in reverse order:");
while ((line = [Link]()) != null) {
String[] words = [Link]("\\s+"); for
(String word : words) {
String reversedWord = new StringBuilder(word).reverse().toString();
[Link](reversedWord + " "); }
[Link](); } [Link](); } catch
(IOException e) {
[Link]("Error: " + [Link]()); }
[Link](); }}
• Set B:
1. 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.
public class FileFilterDemo { public
static void main(String[] args) {
if ([Link] == 0) {
[Link]("Please provide file names as command-line arguments.");
return; }
[Link]("Processing files...");
for (String fileName : args) { File
file = new File(fileName); if (!
[Link]()) {
[Link]("File does not exist: " + fileName); continue; }
if ([Link](".txt")) { if ([Link]()) {
[Link]("Deleted .txt file: " + fileName);
} else {
[Link]("Failed to delete: " + fileName); }
} else {
[Link]("\nFile Name: " + [Link]());
[Link]("File Location: " + [Link]());
[Link]("File Size: " + [Link]() + " bytes"); } } }}
2. Write a java program to display the files having extension .txt from a given directory.
public class ListTxtFiles { public static
void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter directory path: ");
String dirPath = [Link]();
File dir = new File(dirPath); if (!
[Link]() || ![Link]())
{ [Link]("Invalid
directory!");
[Link](); return; }
FilenameFilter txtFilter = new FilenameFilter()
{ @Override public boolean accept(File dir, String name) {
return [Link]().endsWith(".txt"); } };
File[] txtFiles = [Link](txtFilter); if ([Link] ==
0) {
[Link]("No .txt files found in the directory.");
} else { [Link](".txt files in directory " + dirPath + ":");
for (File file : txtFiles) {
[Link]([Link]()); } } [Link](); }}
3. Write a java program to count number of lines, words and characters from a given file.
public class FileStatistics { public
static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the file name (with path if needed): ");
String fileName = [Link]();
File file = new File(fileName);
if (![Link]() || ![Link]()) {
[Link]("File does not exist or is invalid!");
[Link](); return; }
int lineCount = 0;
int wordCount = 0;
int charCount = 0;
try (BufferedReader br =
new
BufferedReader(new
FileReader(file))) {
String line; while
((line = [Link]()) !=
null)
{ lineCount++;
String[] words = [Link]().split("\\s+");
if ([Link]().length() > 0)
{ wordCount += [Link]; }
charCount += [Link]();
} [Link]("\nFile Statistics for: " + fileName);
[Link]("Number of Lines: " + lineCount);
[Link]("Number of Words: " + wordCount);
[Link]("Number of Characters: " + charCount);
} catch (IOException e) {
[Link]("Error reading file: " + [Link]()); }
[Link](); }}
4. 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)
public class CharacterCategory
{ public static void main(String[] args)
Scanner sc = new Scanner([Link]);
[Link]("Enter file name (with path if needed): ");
String fileName = [Link]();
File file = new File(fileName); if
(![Link]() || ![Link]()) {
[Link]("File does not exist or is invalid!");
[Link](); return; }
try (FileReader fr = new FileReader(file)) {
int ch;
[Link]("\nProcessing file characters:\n");
while ((ch = [Link]()) != -1) { char c = (char) ch;
if ([Link](c)) { if
([Link](c)) {
[Link](c + " -> " + [Link](c));
} else {
[Link](c + " -> " + [Link](c)); }
} else if ([Link](c)) {
[Link](c + " -> Digit");
} else if ([Link](c)) {
[Link]("'" + c + "' -> Space");
} else { [Link](c + " -> Other Character");} } }
} catch (IOException e) {
[Link]("Error reading file: " + [Link]()); }
[Link](); }}
5. 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.
class InvalidDataException extends Exception {
public InvalidDataException(String message) {
super(message); } } public class
ValidatePanAndMobile { public static void
main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter PAN Number: ");
String pan = [Link]();
[Link]("Enter Mobile Number: ");
String mobile = [Link](); if (!
[Link]("[A-Z]{5}[0-9]{4}[A-Z]{1}")) {
throw new InvalidDataException("Invalid Data: PAN number format is wrong");
} if () {
throw new InvalidDataException("Invalid Data: Mobile number format is
wrong"); } [Link]("\n✅ PAN Number: " + pan);
[Link]("✅ Mobile Number: " + mobile);
} catch (InvalidDataException e) {
[Link]("❌ Exception: " + [Link]());
} }}
Assignment No 5
• Set A:
1. 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!".
public class Greeting { public static
void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter your name: ");
String name = [Link]();
String upperName = [Link]();
[Link]("Hello, " + upperName + ", nice to meet you!");
[Link](); }}
2. 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
public class WordBreaker {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a line of text:");
String line = [Link](); line =
[Link]("[^a-zA-Z]", " "); String[]
words = [Link]().split("\\s+");
[Link]("\nWords:"); for
(String word : words)
{ [Link](word); }
[Link](); }}
3. 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.
public class SortPositive { public static
void main(String[] args) { Scanner sc =
new Scanner([Link]); double[]
numbers = new double[100];
int count = 0;
[Link]("Enter positive real numbers (enter 0 to finish):");
while (true) { double num = [Link]();
if (num == 0) { break;
} if (num < 0) {
[Link]("Only positive numbers are allowed. Try again.");
continue; }
if (count < 100) {
numbers[count] = num;
count++; } else {
[Link]("Maximum limit of 100 numbers reached.");
break; } }
[Link](numbers, 0, count);
[Link]("\nNumbers in sorted order:");
for (int i = 0; i < count; i++) {
[Link](numbers[i] + " "); }
[Link](); } }
4. Create an Applet that displays the x and y position of the cursor movement using Mouse and
Keyboard. (Use appropriate listener).
public class MouseKeyPositionApp extends JFrame implements MouseMotionListener,
KeyListener { int x = 0, y = 0;
String msg = "Move mouse or press key to see coordinates."; public
MouseKeyPositionApp() {
setTitle("Mouse & Keyboard Position Tracker");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addMouseMotionListener(this);
addKeyListener(this); setFocusable(true);
setVisible(true); } public void paint(Graphics g)
{ [Link](g);
[Link](new Font("Arial", [Link], 16));
[Link](msg, 20, 100);
} @Override
public void mouseMoved(MouseEvent e) {
x=[Link](); y
= [Link]();
msg = "Mouse
Moved: X = " +
x + ", Y = " + y;
repaint(); } @Override
public voidmouseDragged(MouseEvent
e) { x = [Link](); y = [Link](); msg = "Mouse Dragged: X = " + x + ", Y = " + y;
repaint(); } @Override public void keyPressed(KeyEvent e) { msg = "Key Pressed:
" + [Link]() + " | Last Mouse Position: X = " + x + ", Y = " + y;
repaint(); }
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public static void main(String[] args) {
new MouseKeyPositionApp(); }}
[Link] the following GUI screen using appropriate layout managers.
public class NumberAdditionGUI extends JFrame implements ActionListener {
JTextField txtFirst, txtSecond, txtResult;
JButton btnAdd, btnClear, btnExit;
public NumberAdditionGUI()
{ setTitle("Number Addition");
setSize(350, 200);
setDefaultCloseOperation(JFrame.EXIT_ON
_CLOSE); setLocationRelativeTo(null);
JPanel panelFields = new JPanel(new GridLayout(3, 2, 5,
5)); [Link](new JLabel("First Number:"));
txtFirst = new JTextField(); [Link](txtFirst);
[Link](new JLabel("Second Number:"));
txtSecond = new JTextField();
[Link](txtSecond); [Link](new
JLabel("Result:"));
txtResult = new JTextField();
[Link](false);
[Link](txtResult);
JPanel panelButtons = new JPanel(new
FlowLayout()); btnAdd = new JButton("Add");
btnClear = new JButton("Clear");
[Link](btnAdd);
[Link](btnClear);
JPanel panelExit = new JPanel(new FlowLayout([Link])); btnExit
= new JButton("Exit"); [Link](btnExit);
setLayout(new BorderLayout(10, 10)); add(panelFields, [Link]);
add(panelButtons, [Link]); add(panelExit, BorderLayout.PAGE_END);
[Link](this); [Link](this);
[Link](this); [Link](e ->
calculateSum());
setVisible(true); }
public void actionPerformed(ActionEvent e)
{ if ([Link]() == btnAdd) {
calculateSum();
} else if ([Link]() == btnClear) { clearFields();
} else if ([Link]() == btnExit) {
[Link](0); } }
private void calculateSum() {
try { String first =
[Link]().trim(); String second =
[Link]().trim(); if ([Link]()
|| [Link]()) {
[Link](this, "Please enter both numbers!", "Input Error",
JOptionPane.WARNING_MESSAGE); return;
} double num1 = [Link](first); double num2 =
[Link](second); double sum = num1 + num2;
[Link]([Link](sum));
} catch (NumberFormatException ex) {
[Link](this, "Invalid number format!", "Error",
JOptionPane.ERROR_MESSAGE); } }
private void clearFields()
{ [Link]("");
[Link]("");
[Link]("");
[Link](); } public
static void main(String[] args) {
new NumberAdditionGUI(); }}
• Set B:
1. Write a java program to implement a simple arithmetic calculator. Perform appropriate
validations.
public class SimpleCalculator extends JFrame implements ActionListener {
private JTextField display; private String operator = ""; private
double num1 = 0, num2 = 0; private boolean startNewNumber = false;
public SimpleCalculator() { setTitle("Simple
Calculator"); setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
display = new JTextField(); [Link](false);
[Link]([Link]);
[Link](new Font("Arial", [Link], 20));
JPanel panel = new JPanel(new GridLayout(4, 4, 5, 5));
String[] buttons = { "7", "8", "9", "+",
"4", "5", "6", "-",
"1", "2", "3", "*",
"C", "0", "=", "/" }; for (String text :
buttons) { JButton btn = new JButton(text);
[Link](new Font("Arial", [Link], 18));
[Link](this); [Link](btn);
} setLayout(new BorderLayout(5, 5));
add(display, [Link]); add(panel,
[Link]);
setVisible(true); }
public void actionPerformed(ActionEvent e) {
String command = [Link]();
if ([Link]("[0-
9]")) { if (startNewNumber)
{ [Link]("");
startNewNumber = false; }
[Link]([Link]() + command); }
else if ([Link]("[+\\-*/]")) {
try { num1 =
[Link]([Link]());
operator = command;
[Link]([Link]() + " " + operator + " ");
startNewNumber = false;
} catch (NumberFormatException ex) {
[Link](this, "Enter a valid number first!"); }
} else if ([Link]("=")) {
try { String[] parts = [Link]().split(" "); if ([Link]
>= 3) { num2 = [Link](parts[2]); }
double result = calculate(num1, num2, operator);
[Link](num1 + " " + operator + " " + num2 + " = " + result);
operator = ""; startNewNumber = true;
} catch (NumberFormatException ex) {
[Link](this, "Invalid calculation!"); } }
else
([Link]("C")) {
[Link](""); operator
= ""; num1 =
num2 = 0; } }
private double calculate(double a, double b, String
op) { switch (op) { case "+": return a + b;
case "-": return a - b; case "*": return a * b;
case "/": if (b == 0) {
[Link](this, "Cannot divide by zero!");
return 0; } return a / b; default: return 0; } }
public static void main(String[] args) { new SimpleCalculator();
}}
2. Write a java program to implement following. Program should handle appropriate
events.
public class MenuDemoWithSearch extends JFrame implements ActionListener {
JMenuItem undo, redo, cut, copy, paste, exit,
searchItem; JTextArea textArea; public
MenuDemoWithSearch() { setTitle("Menu Example
with Separate Search Menu"); setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); textArea = new
JTextArea(); [Link](new Font("Arial",
[Link], 16));
add(new JScrollPane(textArea), [Link]);
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File"); exit =
new JMenuItem("Exit");
[Link](this);
[Link](exit);
JMenu editMenu = new
JMenu("Edit"); undo = new
JMenuItem("Undo"); redo = new
JMenuItem("Redo"); cut = new
JMenuItem("Cut"); copy = new
JMenuItem("Copy"); paste = new JMenuItem("Paste");
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](undo);
[Link](redo);
[Link]();
[Link](cut);
[Link](copy);
[Link](paste);
JMenu searchMenu = new JMenu("Search"); searchItem
= new JMenuItem("Find...");
[Link](this);
[Link](searchItem);
[Link](fileMenu); [Link](editMenu);
[Link](searchMenu);
setJMenuBar(menuBar);
setVisible(true); }
@Override public void actionPerformed(ActionEvent e)
{ Object source = [Link]();
if (source == cut) {
[Link](); } else
if (source == copy) {
[Link](); }
else if (source == paste) {
[Link](); }
else if (source ==
searchItem) { searchText();
} else if
(source == undo) {
[Link](this, "Undo operation performed!");
} else if (source == redo) { [Link](this, "Redo operation
performed!");
} else if (source == exit) { [Link](0); } }
private void searchText() {
String keyword = [Link](this, "Enter text to search:");
if (keyword != null && ![Link]()) { String content
= [Link](); int index = [Link](keyword); if
(index >= 0) { [Link]();
[Link](index, index + [Link]());
[Link](this, "Found at position: " + index);
} else {
[Link](this, "Text not found!"); } }
} public static void main(String[] args) { new MenuDemoWithSearch(); }}
3. Write an applet application to draw Temple.
public class TempleSwing extends JPanel {
@Override protected void paintComponent(Graphics g) { [Link](g);
setBackground([Link]);
[Link]([Link]);
[Link](100, 300, 300, 100);
[Link]([Link]);
[Link](120, 250, 30, 50);
[Link](350, 250, 30, 50);
[Link](200, 250, 30, 50);
[Link]([Link]); int[] xPoints = {100, 250, 400}; int[] yPoints = {300, 180, 300};
[Link](xPoints, yPoints, 3); [Link]([Link]);
[Link](230, 350, 40, 50);
[Link]([Link]);
[Link](150, 320, 20, 20);
[Link](330, 320, 20, 20); }
public static void main(String[] args) {
JFrame frame = new JFrame("Temple
Drawing"); TempleSwing panel = new TempleSwing();
[Link](panel); [Link](500, 500);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true); }}
4. Write an applet application to display Table lamp. The color of lamp should get change in random
color.
public class TableLampSwing extends JPanel {
Random rand = new Random();
@Override protected void paintComponent(Graphics g) { [Link](g);
setBackground([Link]);
Color lampColor = new Color([Link](256), [Link](256), [Link](256));
[Link]([Link]);
[Link](180, 350, 40, 50);
[Link]([Link]);
[Link](195, 250, 10, 100);
[Link](lampColor);
int[] xPoints = {150, 250, 250, 150};
int[] yPoints = {250, 250, 150, 150};
[Link](xPoints, yPoints, 4);
[Link]([Link]);
[Link](xPoints, yPoints, 4); }
public static void main(String[] args) {
JFrame frame = new JFrame("Table Lamp");
TableLampSwing panel = new TableLampSwing();
[Link](panel); [Link](400, 500);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
new Timer(1000, e -> [Link]()).start(); }}
5. Write a java program to design email registration form.( Use maximum Swing component
in form).
public class EmailRegistrationForm extends JFrame implements ActionListener {
JLabel lblTitle, lblName, lblEmail, lblPassword, lblGender, lblCountry, lblTerms;
JTextField txtName, txtEmail;
JPasswordField txtPassword;
JRadioButton rbMale, rbFemale, rbOther; JComboBox<String> cbCountry;
JCheckBox chkTerms; JButton
btnSubmit; public
EmailRegistrationForm()
{ setTitle("Email Registration
Form"); setSize(500, 550);
setLayout(null);
setDefaultCloseOperation(JFrame.
EXIT_ON_CLOSE);
setLocationRelativeTo(null);
lblTitle = new JLabel("Email
Registration Form");
[Link](new Font("Arial",
[Link], 20));
[Link](120, 20, 300, 30);
add(lblTitle); lblName = new JLabel("Full Name:"); [Link](50,
80, 100, 25); add(lblName); txtName = new JTextField();
[Link](160, 80, 250, 25); add(txtName);
lblEmail = new JLabel("Email:"); [Link](50, 130, 100,
25); add(lblEmail); txtEmail = new JTextField();
[Link](160, 130, 250, 25);
add(txtEmail); lblPassword = new
JLabel("Password:");
[Link](50, 180, 100, 25);
add(lblPassword); txtPassword =
new JPasswordField();
[Link](160, 180, 250,
25); add(txtPassword); lblGender = new JLabel("Gender:");
[Link](50, 230, 100, 25); add(lblGender); rbMale =
new JRadioButton("Male"); [Link](160, 230, 70, 25);
rbFemale = new JRadioButton("Female"); [Link](240, 230, 80, 25);
rbOther = new JRadioButton("Other"); [Link](330, 230, 70,
25);
ButtonGroup genderGroup = new ButtonGroup();
[Link](rbMale); [Link](rbFemale);
[Link](rbOther);
add(rbMale);
add(rbFemale);
add(rbOther);
lblCountry = new JLabel("Country:");
[Link](50, 280, 100, 25);
add(lblCountry);
String[] countries = {"Select", "India", "USA", "UK", "Australia", "Other"};
cbCountry = new JComboBox<>(countries); [Link](160,
280, 150, 25); add(cbCountry); chkTerms = new
JCheckBox("I accept the Terms and Conditions");
[Link](50, 330, 300, 25);
add(chkTerms);
btnSubmit = new JButton("Register");
[Link](180, 380, 120, 30);
[Link](this);
add(btnSubmit);
setVisible(true); }
@Override public void actionPerformed(ActionEvent e) { if ([Link]() == btnSubmit)
{
String name = [Link]();
String email = [Link]();
String password = new String([Link]());
String gender = [Link]() ? "Male" : [Link]() ? "Female" :
[Link]() ? "Other" : "";
String country = (String) [Link](); boolean termsAccepted
= [Link]();
if ([Link]() || [Link]() || [Link]() || [Link]() ||
[Link]("Select")) {
[Link](this, "Please fill all fields correctly!", "Error",
JOptionPane.ERROR_MESSAGE);
} else if (!termsAccepted) {
[Link](this, "You must accept Terms and Conditions!",
"Error", JOptionPane.ERROR_MESSAGE); } else {
[Link](this, "Registration Successful!\nName: " + name + "\
nEmail: " + email
+ "\nGender: " + gender + "\nCountry: " + country, "Success",
JOptionPane.INFORMATION_MESSAGE); } } } public static
void main(String[] args) {
new
EmailRegistrationForm(); }}
• Set C:
1. Write a java program to accept the details of employee employee eno,ename, sal and display it
on next frame using appropriate even .
public class EmployeeDetailsForm extends JFrame implements ActionListener {
JLabel lblEno, lblEname, lblSal;
JTextField txtEno, txtEname, txtSal; JButton btnSubmit; public
EmployeeDetailsForm() { setTitle("Employee Details Form"); setSize(400,
300); setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); lblEno = new JLabel("Employee No:");
[Link](50, 50, 100, 25); add(lblEno);
txtEno = new JTextField();
[Link](160, 50, 150, 25);
add(txtEno); lblEname = new JLabel("Employee
Name:"); [Link](50, 100, 100,
25); add(lblEname); txtEname = new
JTextField(); [Link](160, 100, 150,
25); add(txtEname);
lblSal = new JLabel("Salary:");
[Link](50, 150, 100, 25);
add(lblSal); txtSal = new
JTextField();
[Link](160, 150, 150,
25); add(txtSal); btnSubmit =
new JButton("Submit");
[Link](130, 200, 100,
30);
[Link](this);
add(btnSubmit);
setVisible(true); } @Override
public void actionPerformed(ActionEvent e) {
String eno = [Link]();
String ename = [Link](); String
sal = [Link]();
if ([Link]() || [Link]() || [Link]()) {
[Link](this, "Please fill all fields!", "Error",
JOptionPane.ERROR_MESSAGE); return; } JFrame
displayFrame = new JFrame("Employee Details");
[Link](350, 200); [Link](new
GridLayout(4, 1)); [Link](null);
[Link](new JLabel("Employee No: " + eno));
[Link](new JLabel("Employee Name: " + ename));
[Link](new JLabel("Salary: " + sal)); JButton closeBtn
= new JButton("Close");
[Link](ev ->
[Link]());
[Link](closeBtn);
[Link](true); } public static void
main(String[] args) {
new EmployeeDetailsForm(); }}
2. Write a java program to display at least five records of employee in JTable.( Eno, Ename ,Sal).
public class EmployeeTable extends JFrame { public
EmployeeTable() { setTitle("Employee Records");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
String[] columns = {"Employee No", "Employee Name", "Salary"};
Object[][] data = { {"E001", "Jaiprakash", 50000},
{"E002", "ritesh", 60000},
{"E003", "Amlesh", 55000},
{"E004", "Ganesh", 70000},
{"E005", "David", 65000} };
JTable table = new JTable(data, columns); [Link](true);
JScrollPane scrollPane = new JScrollPane(table); add(scrollPane, [Link]);
setVisible(true); }
public static void main(String[] args) { new EmployeeTable(); }}
3. Write a java Program to change the color of frame. If user clicks on close button then the position
of frame should get change.
public class FrameColorPosition extends JFrame implements ActionListener, WindowListener
{ JButton btnChangeColor;
Random rand = new
Random(); public
FrameColorPosition()
{ setTitle("Change Frame Color &
Position"); setSize(400, 300);
setLayout(new FlowLayout());
setLocationRelativeTo(null);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(this); btnChangeColor = new
JButton("Change
Color");
[Link](this); add(btnChangeColor);
setVisible(true); }
@Override public void actionPerformed(ActionEvent e) {
Color randomColor = new Color([Link](256), [Link](256),
[Link](256)); getContentPane().setBackground(randomColor); } @Override
public void windowClosing(WindowEvent
e) { int x = [Link](500); int y
= [Link](500); setLocation(x, y);
[Link](this, "Frame position changed instead of closing!"); }
public void windowOpened(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e)
{} public void windowActivated(WindowEvent e)
{} public void windowDeactivated(WindowEvent
e) {} public static void main(String[] args) {
new FrameColorPosition(); }}
4. Write a java program to display following screen.
public class CompoundInterestCalculator extends JFrame implements ActionListener {
rincipal, lblRate, lblTime, lblTotal, lblInterest;
JTextField txtPrincipal, txtRate, txtTime, txtTotal,
txtInterest; JButton btnCalculate, btnClear, btnClose;
public CompoundInterestCalculator()
{ setTitle("Compound Interest
Calculator"); setSize(400, 300);
setLayout(null);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
lblPrincipal = new JLabel("Principal Amount:"); [Link](30,
30, 120, 25);
add(lblPrincipal); lblRate = new
JLabel("Interest Rate (%):");
[Link](30, 70, 120, 25);
add(lblRate); lblTime = new JLabel("Time
(Yrs):"); [Link](30, 110, 120,
25);
add(lblTime); lblTotal = new
JLabel("Total Amount:");
[Link](30, 150, 120, 25); add(lblTotal); lblInterest =
new JLabel("Interest Amount:"); [Link](30, 190,
120, 25); add(lblInterest); txtPrincipal = new JTextField();
[Link](160, 30, 180, 25); add(txtPrincipal);
txtRate = new JTextField(); [Link](160, 70, 180, 25);
add(txtRate); txtTime = new JTextField(); [Link](160,
110, 180, 25);
add(txtTime); txtTotal = new JTextField(); [Link](160, 150, 180,
25); [Link](false); add(txtTotal);
txtInterest = new JTextField();
[Link](160, 190, 180, 25);
[Link](false); add(txtInterest);
btnCalculate = new JButton("Calculate");
[Link](30, 230, 100, 30);
[Link](this);
add(btnCalculate); btnClear = new
JButton("Clear"); [Link](150, 230,
80, 30); [Link](this);
add(btnClear);
btnClose = new JButton("Close"); [Link](250, 230, 80, 30);
[Link](this); add(btnClose);
setVisible(true);
} @Override public void actionPerformed(ActionEvent e) { if ([Link]() ==
btnCalculate) { try { double principal =
[Link]([Link]()); double rate =
[Link]([Link]()); double time =
[Link]([Link]());
double total = principal * [Link]((1 + rate / 100), time); double
interest = total - principal;
[Link]([Link]("%.2f", total));
[Link]([Link]("%.2f", interest));
} catch (NumberFormatException ex) {
[Link](this, "Please enter valid numbers!", "Error",
JOptionPane.ERROR_MESSAGE); }
} else if ([Link]() == btnClear) {
[Link]("");
[Link]("");
[Link]("");
[Link]("");
[Link](""); } else if
([Link]() == btnClose) {
dispose(); } }
public static void main(String[] args) {
new CompoundInterestCalculator(); }}
5. Write an applet application to display smiley and sad face.
import [Link].*; import [Link].*; public
class SmileySadSwing extends JPanel
{ public void paintComponent(Graphics g) {
[Link](g);
[Link]([Link]); [Link](50, 50, 150, 150);
[Link]([Link]); [Link](90, 100, 20, 20);
[Link](140, 100, 20, 20); [Link](90, 120, 80, 50, 0, -180);
[Link]("Smiley Face", 85, 220); [Link]([Link]);
[Link](300, 50, 150, 150); [Link]([Link]);
[Link](340, 100, 20, 20); [Link](390, 100, 20, 20);
[Link](340, 140, 80, 50, 0, 180); [Link]("Sad Face", 345, 220); }
public static void main(String[] args) {
JFrame frame = new JFrame("Smiley and Sad Face");
SmileySadSwing panel = new SmileySadSwing();
[Link](panel);
[Link](550, 350);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true); }}