0% found this document useful (0 votes)
18 views83 pages

Java Programming Exercises and Solutions

Uploaded by

kakadesayali469
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views83 pages

Java Programming Exercises and Solutions

Uploaded by

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

43k

Chapter 1
Q1. Write a ‘java’ program to display characters from ‘A’ to ‘Z’.
Ans:
public class Atoz{
public static void main(String[] args){
int i;
for(i=65;i<=90;i++)
{
[Link](" "+[Link]((char)i));
}}}
Output:

Q2. Write a ‘java’ program to display all the vowels from a given string.
Ans:
public class vowel{
public static void main(String[] args){
char ch;
String str="hello everyone ! nice to meet you";
[Link]("vowels are= ");
for(int i=0;i<[Link]();i++)
{
ch=[Link](i);
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'||ch=='A'||ch=='E'||ch=='I'||ch=='
O'||ch=='U')
{
[Link](" "+ch);
}}}}
Output:

Q3. Write a ‘java’ program to check whether given number is Armstrong


or not. use static keyword.
Ans:
import [Link];
class arm {
static int temp;
public static void main(String[] args) {
int r, sum = 0, n;
Scanner s = new Scanner([Link]);
[Link]("Enter number = ");

1
43k

n = [Link]();
temp = n;
while (n != 0) {
r = n % 10;
sum = sum + (r * r * r);
n = n / 10; //
}
if (temp == sum) {
[Link](temp + " is an Armstrong number");
} else {
[Link](temp + " is not an Armstrong number");
}}}
Output:

Q4. Write a ‘java’ program to display alternate character from a given


string.
Ans:
class alternate{
public static void main(String[] args){
char ch;
String str=" HELLO BYE! ";
[Link]("alternate characters are= ");
for(int i=0;i<[Link]();i=i+2)
{
ch=[Link](i);
[Link](" "+ch);
}}}
Output:

Q5. Write a ‘java’ program to display following pattern:


5
4 5
3 4 5
2 3 4 5
1 2 3 4 5
Ans:
public class pattern1{
public static void main(String[] args){

2
43k

int i,j;
for(i=5;i>=1;i--){
for(j=i;j<=5;j++){
[Link](j +" ");
}
[Link]();
}}}
Output:

Q6. Write a ‘java’ program to display transpose of given matrix.


Ans:
class transpose{
public static void main(String[] args){
int i, j;
int array[][] = {{1,3,4},{2,4,3},{3,4,5}};
[Link]("Original Matrix is :");
for(i = 0; i < 3; i++){
for(j = 0; j < 3; j++){
[Link](array[i][j]+" "); }
[Link](" "); }
[Link]("Transpose of Matrix is :");
for(i = 0; i < 3; i++) { for(j = 0; j < 3; j++) { [Link](array[j][i]+" ");
} [Link](" "); }}}
Output:

Q7. Write a ‘java’ program to display following pattern:


1
0 1
0 1 0
1 0 1 0
Ans:
class pattern2 {
public static void main(String[] args){
int i,j,k=1;
for(i=1; i<=4; i++){
for(j=1; j<=i; j++){
if(k%2==1)
{
[Link](1 + " ");

3
43k

}
else{
[Link](0 + " ");
}
k++;
}
[Link]();
}}}
Output:

Q8. Write a ‘java’ program to count the frequency of each character in


given string.
Ans:
import [Link];
class frequency {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();
// Count frequency of each character
for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
// Skip if this character is already counted before
if ([Link](ch) != i) {
continue;
}
int count = 0;
for (int j = 0; j < [Link](); j++) {
if ([Link](j) == ch) {
count++;
}}
[Link](ch + " = " + count);
} }}
Output:

4
43k

Q9. Write a menu driven java program using command line argument
for the following:
1. Addition
2. Subtraction
3. Multiplication
4. Division
Ans: import [Link];
public class arithe {
public static void main(String[] args){
int a,b,n;
Scanner s=new Scanner([Link]);
[Link]("Enter 1 : Additon" + '\n' + "Enter 2 : Substraction" + '\n'
+ "Enter 3 : Multiplication" + '\n' + "Enter 4 : Division");
a = [Link](args[0]);
b = [Link](args[1]);
[Link]("enter your choice=");
n=[Link]();
switch(n){
case 1:
[Link](a + " + " + b + " = " + (a+b));
break;
case 2:
[Link](a + " - " + b + " = " + (a-b));
break;
case 3:
[Link](a + " * " + b + " = " + (a*b));
break;
case 4:
[Link](a + " / " + b + " = " + (a/b));
break;
}}}

Output:

5
43k

Q10. Write a ‘java’ program to display each String in reverse order from
a string array.
Ans:
class reverse{
public static void main(String args[]){
String str[] = {"swarup", "nila", "Mahesh"};
for(int i=[Link]-1; i>=0; i--){
[Link](str[i] + ' ');
}}}
Output:

Q11. Write a ‘java’ program that asks the user 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!”.
Ans:
import [Link];
public class greetuser {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Ask the user for their name
[Link]("Enter your name: ");
String name = [Link]();
// Convert to uppercase
String upperName = [Link]();
// Greet the user
[Link]("Hello, " + upperName + ", nice to meet you!");
}}
Output:

Q12. Write a ‘java’ program to search given name into the array , if it is
found then display its index otherwise display appropriate message.
Ans: import [Link];
public class SearchNameInArray {

6
43k

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
[Link]("Enter number of names: ");
int n = [Link]();
[Link](); // consume newline
String[] names = new String[n];
// Accept names
[Link]("Enter " + n + " names:");
for (int i = 0; i < n; i++) {
names[i] = [Link]();
}
[Link]("Enter name to search: ");
String searchName = [Link]();
// Search logic
int index = -1;
for (int i = 0; i < n; i++) {
if (names[i].equals(searchName)) { // exact match only
index = i;
break;
}}
// Display result
if (index != -1) {
[Link]("Name found at index: " + index);
} else {
[Link]("Name not found in the array.");
}}}
Output:

Q13. Write a ‘java’ program to accept ‘n’ numbers through command


line and store only Armstrong numbers into the array and display that
array.

7
43k

Ans: class ArmstrongArray {


public static void main(String[] args) {
int n = [Link]; // total numbers entered in command line
int arr[] = new int[n]; // array to store Armstrong numbers
int k = 0; // index for Armstrong numbers
for (int i = 0; i < n; i++) {
int num = [Link](args[i]); // convert string to int
int temp = num;
int sum = 0;
// check Armstrong (only 3-digit cubes)
while (num != 0) {
int r = num % 10;
sum = sum + (r * r * r);
num = num / 10;
}
if (temp == sum) {
arr[k] = temp;
k++;
}}
[Link]("Armstrong Numbers are:");
for (int i = 0; i < k; i++) {
[Link](arr[i] + " ");
} }}

Q14. Write a ‘java’ program to display Fibonacci series using function.


Ans: import [Link];
class fibbo {
// Function to print Fibonacci series
static void printFibonacci(int n) {
int f1= 0, f2= 1, next;
[Link]("Fibonacci Series: ");
for (int i = 0; i < n; i++) {
[Link](f1+ " ");
next = f1 + f2;
f1 = f2;
f2 = next;
}}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter how many terms you want: ");

8
43k

int n = [Link]();
printFibonacci(n); // function call
}}

Output:

Q15. Write a ‘java’ program to check whether given string is


palindrome or not.
Ans: import [Link];
class palindrome{
static void check(String str) {
String rev = "";
int length = [Link]();
for (int i = length - 1; i >= 0; i--) {
rev = rev + [Link](i);
}
if ([Link](rev)) { [Link](str + " is a Palindrome."); }
else { [Link](str + " is NOT a Palindrome."); } }
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String input = [Link]();
check(input); // function call }}

Output:

==============1st chapter ends============

9
43k

Chapter 2 and 3

Q16. Define an abstract class Shape with abstract methods area () and
volume (). Derive abstract class Shape into two classes Cone and
Cylinder. Write a java Program to calculate area and volume of Cone
and Cylinder.(Use Super Keyword.)
Ans:
import [Link];
abstract class Shape {
double radius, height;
Shape(double r, double h) {
radius = r;
height = h;
}
abstract void area();
abstract void volume();
}
class Cone extends Shape {
Cone(double r, double h) {
super(r, h); // use super keyword
}
void area() {
// Formula: π * r * (r + h) (simplified, not exact)
double area = 3.14 * radius * (radius + height);
[Link]("Area of Cone = " + area);
}
void volume() {
// Formula: (1/3) * π * r^2 * h
double volume = (3.14 * radius * radius * height) / 3;
[Link]("Volume of Cone = " + volume);
}
}
class Cylinder extends Shape {
Cylinder(double r, double h) {
super(r, h); // use super keyword
}
void area() {
// Formula: 2 * π * r * (r + h)
double area = 2 * 3.14 * radius * (radius + height);
[Link]("Area of Cylinder = " + area);

10
43k

}
void volume() {
// Formula: π * r^2 * h
double volume = 3.14 * radius * radius * height;
[Link]("Volume of Cylinder = " + volume);
}
}
class ShapeMain {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Cone
[Link]("Enter radius of Cone: ");
double r1 = [Link]();
[Link]("Enter height of Cone: ");
double h1 = [Link]();
Shape cone = new Cone(r1, h1);
[Link]();
[Link]();
[Link]();
// Cylinder
[Link]("Enter radius of Cylinder: ");
double r2 = [Link]();
[Link]("Enter height of Cylinder: ");
double h2 = [Link]();
Shape cylinder = new Cylinder(r2, h2);
[Link]();
[Link]();
}
}

Q17. Write a java program to accept details of ‘n’ cricket player (pid,
pname, totalRuns, InningsPlayed, NotOuttimes). Calculate the average
of all the players. Display the details of player having maximum
average. (Use Array of Object).
Ans: import [Link];
class Player {
int pid;
String pname;
int totalRuns;
int inningsPlayed;

11
43k

int notOutTimes;
double average;
void calculateAverage() {
int outs = inningsPlayed - notOutTimes;
if (outs > 0)
average = (double) totalRuns / outs;
else
average = totalRuns; // if player never got out
}
void display() {
[Link]("Player ID: " + pid);
[Link]("Player Name: " + pname);
[Link]("Total Runs: " + totalRuns);
[Link]("Innings Played: " + inningsPlayed);
[Link]("Not Out Times: " + notOutTimes);
[Link]("Average: " + average);
[Link]("----------------------");
}
}
public class Cp{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of players: ");
int n = [Link]();
Player[] players = new Player[n];
// Accept details
for (int i = 0; i < n; i++) {
players[i] = new Player();
[Link]("\nEnter details for Player " + (i + 1));
[Link]("Enter Player ID: ");
players[i].pid = [Link]();
[Link](); // consume newline
[Link]("Enter Player Name: ");
players[i].pname = [Link]();
[Link]("Enter Total Runs: ");
players[i].totalRuns = [Link]();
[Link]("Enter Innings Played: ");
players[i].inningsPlayed = [Link]();
[Link]("Enter Not Out Times: ");
players[i].notOutTimes = [Link]();

12
43k

players[i].calculateAverage();
}
// Find player with maximum average
Player maxPlayer = players[0];
for (int i = 1; i < n; i++) {
if (players[i].average > [Link]) {
maxPlayer = players[i];
} }
[Link]("\n--- All Players Details ---");
for (int i = 0; i < n; i++) {
players[i].display();
}
// Display player with maximum average
[Link]("\n--- Player with Maximum Average ---");
[Link]();
}
}

Q18. Write a Java program to calculate power of a number using


recursion.
Ans: import [Link];
public class Powerrecu {
// Recursive function to calculate power
static int power(int base, int exp) {
if (exp == 0) {
return 1; // base case
} else {
return base * power(base, exp - 1); // recursive step
}}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter base number: ");
int base = [Link]();
[Link]("Enter exponent: ");
int exp = [Link]();
int result = power(base, exp);
[Link](base + " ^ " + exp + " = " + result);
}}

13
43k

Q19. Write a java program to calculate sum of digits of a given number


using recursion.
Ans:
import [Link];
public class SumOfDigitsRecursion {
// Recursive function to calculate sum of digits
static int sumOfDigits(int num) {
if (num == 0) {
return 0; // base case
} else {
return (num % 10) + sumOfDigits(num / 10); // recursive step
}}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int number = [Link]();
int result = sumOfDigits(number);
[Link]("Sum of digits of " + number + " = " + result);
}}
Output:

Q20. Write a java program to accept n employee names from user. Sort
them in ascending order and Display them.(Use array of object and
Static keyword)
Ans:
import [Link];
class Employee {
String name;
static Scanner sc = new Scanner([Link]); // static keyword used
// Method to accept employee name
void acceptName() {
[Link]("Enter Employee Name: ");
name = [Link]();
}
// Method to display employee name
void displayName() {
[Link](name);
}}
public class EmployeeSort {
public static void main(String[] args) {

14
43k

Scanner sc = new Scanner([Link]);


[Link]("Enter number of employees: ");
int n = [Link]();
[Link](); // consume newline

Employee[] emp = new Employee[n];


// Accept employee names
for (int i = 0; i < n; i++) {
emp[i] = new Employee();
emp[i].acceptName();
}
// Sorting names (simple bubble sort)
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (emp[i].[Link](emp[j].name) > 0) {
// Swap names
String temp = emp[i].name;
emp[i].name = emp[j].name;
emp[j].name = temp;
}}}
// Display sorted names
[Link]("\nEmployees in Ascending Order:");
for (int i = 0; i < n; i++) {
emp[i].displayName();
}}}
Output:

Q21. Define a class Product (pid, pname, price, qty). Write a function to
accept the product details, display it and calculate total amount. (use
array of Objects)
Ans:
import [Link];
class Product {
int pid;
String pname;
double price;
int qty;
// function to accept product details
void acceptDetails(Scanner sc) {
[Link]("Enter Product ID: ");

15
43k

pid = [Link]();
[Link](); // consume newline
[Link]("Enter Product Name: ");
pname = [Link]();
[Link]("Enter Price: ");
price = [Link]();
[Link]("Enter Quantity: ");
qty = [Link]();
}
// function to display details and total amount
void displayDetails() {
double total = price * qty;
[Link]("\nProduct ID: " + pid);
[Link]("Product Name: " + pname);
[Link]("Price: " + price);
[Link]("Quantity: " + qty);
[Link]("Total Amount: " + total);
}
}
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];
// accept details
for (int i = 0; i < n; i++) {
[Link]("\nEnter details for Product " + (i + 1));
products[i] = new Product();
products[i].acceptDetails(sc);
}
// display details
[Link]("\n--- Product Details ---");
for (int i = 0; i < n; i++) {
products[i].displayDetails();
}
}
}
Output:

16
43k

Q22. Create a package TYBBACA with two classes as class Student


(Rno, SName, Per) with a method disp() to display details of N Students
and class Teacher (TID, TName, Subject) with a method disp() to
display the details of teacher who is teaching Java subject. (Make use
of finalize() method and array of Object)
Ans:
[Link]
package TYBBACA;
public class student {
public int rno;
public String nm;
public float per;

public student(int r, String name, float p) {


rno = r;
nm = name;
per = p;
}

public void disp() {


[Link]("==========");
[Link]("STUDENT DETAILS");
[Link]("roll no= " + rno);
[Link]("name= " + nm);
[Link]("persentage= " + per);
}

// finalize method added


@Override
protected void finalize() throws Throwable {
[Link]("Student object with Roll No " + rno + " is
destroyed");
[Link]();
}
}
[Link]
package TYBBACA;
public class teacher {
public int tid;
public String tname, sub;

17
43k

public teacher(int id, String n, String subject) {


tid = id;
tname = n;
sub = subject;
}
public void show() {
[Link]("=========");
[Link]("TEACHER DETAILS");
[Link]("tid= " + tid);
[Link]("tname= " + tname);
[Link]("sub= " + sub);
}
// finalize method
@Override
protected void finalize() throws Throwable {
[Link]("Teacher object with ID " + tid + " is destroyed");
[Link]();
}}
[Link]
import [Link];
import [Link];
import [Link];

class main1 {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);

[Link]("How many students? ");


int n = [Link]();
[Link](); // consume leftover newline

student s1[] = new student[n];

// === Student Block ===


for (int i = 0; i < n; i++) {
[Link]("\n== STUDENT BLOCK ==");
[Link]("Enter roll no: ");
int rno = [Link]();
[Link]("Enter percentage: ");
float per = [Link]();

18
43k

[Link](); // consume newline


[Link]("Enter name of student: ");
String nm = [Link]();

s1[i] = new student(rno, nm, per);


}

// Display Students
for (int i = 0; i < n; i++) {
s1[i].disp();
}

[Link]("\nHow many teachers? ");


int m = [Link]();
[Link]();

teacher t1[] = new teacher[m];

// === Teacher Block ===


for (int i = 0; i < m; i++) {
[Link]("\n== TEACHER BLOCK ==");
[Link]("Enter teacher id: ");
int tid = [Link]();
[Link](); // consume newline
[Link]("Enter teacher name: ");
String tname = [Link]();
[Link]("Enter subject: ");
String sub = [Link]();

// store subject
t1[i] = new teacher(tid, tname, sub);
}
// Display Teachers
for (int i = 0; i < m; i++) {
t1[i].show();
}
[Link]("\nTeachers who teach Java:");
for (int i = 0; i < m; i++) {
if (t1[i].[Link]("java")) {
t1[i].show();

19
43k

} }
// Suggest garbage collection to call finalize
s1 = null;
t1 = null;
[Link]();
}}
Output:

Q23. 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.
Ans:
[Link] :
package Series;
public class Fibonacci {
public void printSeries(int n) {
int a = 0, b = 1, c;
[Link]("Fibonacci Series:");
for (int i = 1; i <= n; i++) {
[Link](a + " ");
c = a + b;
a = b;
b = c;
}
[Link]();
}}

[Link]
package Series;

public class Cube {


public void printSeries(int n) {
[Link]("Cube Series:");
for (int i = 1; i <= n; i++) {
[Link]((i * i * i) + " ");
}
[Link]();

20
43k

}}
[Link]
package Series;

public class Square {


public void printSeries(int n) {
[Link]("Square Series:");
for (int i = 1; i <= n; i++) {
[Link]((i * i) + " ");
}
[Link]();
}}
[Link]
import [Link];
import [Link];
import [Link];
import [Link];

class MainSeries {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of terms (n): ");
int n = [Link]();
Fibonacci f = new Fibonacci();
Cube c = new Cube();
Square s = new Square();
[Link](n);
[Link](n);
[Link](n);
}}
Output:

Q24. Define an Interface Shape with abstract method area(). Write a


java program to calculate an area of Circle and Sphere.(use final
keyword) .
Ans:
import [Link];
interface Shape {
void area(); // abstract method
}

21
43k

class Circle implements Shape {


final double r; // radius cannot change
Circle(double radius) {
r = radius;
}
public void area() {
double a = 3.14 * r * r; // area of circle = πr²
[Link]("Area of Circle = " + a);
}}
class Sphere implements Shape {
final double r; // radius cannot change
Sphere(double radius) {
r = radius;
}
public void area() {
double a = 4 * 3.14 * r * r; // surface area of sphere = 4πr²
[Link]("Surface Area of Sphere = " + a);
}}
class MainShape {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
final double r;
[Link]("Enter radius: ");
r = [Link]();
Shape c = new Circle(r);
Shape s = new Sphere(r);
[Link]();
[Link]();
}}
Output:

Q25. 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.
Ans:
import [Link].*;
public class ReverseArrayListIterator {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

22
43k

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


[Link]("Enter number of integers: ");
int n = [Link]();
// Accept n integers
for (int i = 0; i < n; i++) {
[Link]("Enter integer " + (i + 1) + ": ");
[Link]([Link]());
}

// Using ListIterator to traverse in reverse


[Link]("\nArrayList in reverse order:");
ListIterator<Integer> it = [Link]([Link]());
while ([Link]()) {
[Link]([Link]() + " ");
}
[Link]();
}
}
Output:

Q25 Write a Java program to calculate area of Circle, Triangle &


Rectangle.(Use Method Overloading) .
Ans:
import [Link];
class AreaCalculator {

// Circle
public double area(int radius) {
return 3.14 * radius * radius;
}
// Rectangle
public double area(double length, double width) {
return length * width;
}
// Triangle
public double area(int base, double height) {
return 0.5 * base * height;
}}
public class MainArea {
public static void main(String[] args) {

23
43k

Scanner sc = new Scanner([Link]);


AreaCalculator calc = new AreaCalculator();

// Circle
[Link]("Enter radius of circle (int): ");
int r = [Link]();
[Link]("Area of Circle: " + [Link](r));

// Rectangle
[Link]("\nEnter length of rectangle (double): ");
double l = [Link]();
[Link]("Enter width of rectangle (double): ");
double w = [Link]();
[Link]("Area of Rectangle: " + [Link](l, w));

// Triangle
[Link]("\nEnter base of triangle (int): ");
int b = [Link]();
[Link]("Enter height of triangle (double): ");
double h = [Link]();
[Link]("Area of Triangle: " + [Link](b, h));
}}
Output:

Q26. Write a java program to count the number of integers from a given
list. (Use Command line arguments).
Ans:
import [Link].*;
public class list_cnt{
public static void main(String[] args)
{
int count=0;
List<String> l=new ArrayList<>();
for(int i=0;i<[Link];i++)
{
[Link](args[i]);
}
for(int i=0;i<[Link]();i++)
{
String s=[Link](i);

24
43k

try{
int j=[Link](s);
count++;
}
catch(NumberFormatException e){}
}
[Link](count+"Integer present in list");
}}

Q27 . Construct a Linked List containing name: CPP, Java, Python and
PHP. Then
extend your java 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.
[25 M]
Ans:
import [Link];
import [Link];
import [Link];

public class LinkedListExample {


public static void main(String[] args) {

// ----- Step 1: Create LinkedList and add elements -----


LinkedList<String> languages = new LinkedList<>();
[Link]("CPP");
[Link]("Java");
[Link]("Python");
[Link]("PHP");

// ----- Step 2: Display contents using Iterator -----


[Link]("Contents of the list using Iterator:");
Iterator<String> it = [Link]();
while([Link]()) {
[Link]([Link]());
}

// ----- Step 3: Display contents in reverse using ListIterator -----

25
43k

[Link]("\nContents of the list in reverse using


ListIterator:");
ListIterator<String> lit = [Link]([Link]()); // start
from end
while([Link]()) {
[Link]([Link]());
}
}
}

===================End======================

26
43k

Chapter 4
Q28. Write a ‘java’ program to copy only non-numeric data from one file
to another file.
Ans:
import [Link].*;
class file_nonnum1 {
public static void main(String[] args) throws IOException {
char ch;
FileReader fr = new FileReader("[Link]");
FileWriter fw = new FileWriter("[Link]");
int c;
while ((c = [Link]()) != -1) {
ch = (char) c;
if (![Link](ch)) {
[Link](ch);
}}
[Link]();
[Link]();
[Link]("Non-numeric characters copied successfully!");
}
}
Output:

Q29. 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.
Ans:
import [Link].*;
class file_cmd{
public static void main(String[] args)
{
for(int i=0;i<[Link];i++)
{
File f=new File(args[i]);
if([Link]())
{
String nm=[Link]();
if([Link](".txt"))
{
[Link]();

27
43k

[Link]("file is deleted " +f);


}
else
{
[Link]("File name = "+nm+"\n File Location =
"+[Link]()+"\n File Size = "+[Link]()+"bytes");
}}
else
{
[Link](args[i]+" is not in folder");
}}}}

Output:

Q30. Write a java program to accept a number from user, if it zero then
throw user defined Exception “Number Is Zero”, otherwise calculate
the sum of first and last digit of that number. (Use static keyword).
Ans: import [Link];
class NumberIsZeroException extends Exception {
NumberIsZeroException() {
[Link]("Number Is Zero");
}}
public class NumberSum {
static int sumFirstLast(int num) {
int last = num % 10;
int first = num;
while (first >= 10) {
first = first / 10;
}
return first + last; }
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();
try { if (num == 0) {
throw new NumberIsZeroException(); // throwing our own
exception
} else {
int sum = sumFirstLast(num);
[Link]("Sum of first and last digit: " + sum);

28
43k

}
} catch (NumberIsZeroException e) {} }}

Output:

Q31. Write a java program to display the files having extension .txt from
a given directory.
Ans:
import [Link];
class file_dire
{
public static void main(String[] args)
{
File f=new File("Path");
String[] fileList=[Link]();
for(String str : fileList)
{
if([Link](".txt"))
{
[Link](str);
}}}}
Output:

Q32. Write a java program to display ASCII values of the characters


from a file.
Ans:
import [Link].*;
class ascii{
public static void main(String[] args)throws IOException
{
char ch;
FileReader fr=new FileReader("[Link]");
int c;
while((c=[Link]())!=-1)
{
ch=(char)c;
if([Link](ch)==false && ([Link](c)==false))
{
[Link]("ASSCII"+ch+" : "+c);
}
29
43k

}
[Link]();
}}
Output:

Q33. 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.
Ans:
import [Link].*;
import [Link].*;
public class hash_city {
public static void main(String[] args) {
Hashtable<String, Integer> h1 = new Hashtable<>();
Scanner s = new Scanner([Link]);
try {
[Link]("Enter how many records you want: ");
int n = [Link]();
[Link](); // consume leftover newline
for (int i = 0; i < n; i++) {
[Link]("Enter city name: ");
String cname = [Link]();
[Link]("Enter STD code: ");
int std = [Link]();
[Link](); // consume leftover newline
[Link](cname, std);
}
[Link]("\nEnter city name to search: ");
String nm = [Link]();
if ([Link](nm)) {
int val = [Link](nm);
[Link]("STD code for " + nm + " : " + val);
} else {
[Link]("City not found");
}
} catch (Exception e) {
[Link]("Error: " + e);
}}}
Output:

30
43k

Q34. 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.
Ans: import [Link].*; // for IOException and InputStreamReader
import [Link].*; // for Scanner
class InvalidDataException extends Exception {
InvalidDataException() {
[Link]("Invalid Data");
}}
public class PAN {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner([Link]);
[Link]("Enter PAN Number: ");
String pan = [Link]();
[Link]("Enter Mobile Number: ");
String mobile = [Link]();
try {
// PAN: 5 letters + 4 digits + 1 letter (like ABCDE1234F)
// Mobile: 10 digits starting with 6-9
if (![Link]("[A-Z]{5}[0-9]{4}[A-Z]{1}") ||
![Link]("[6-9][0-9]{9}")) {
throw new InvalidDataException();
} else {
[Link]("PAN Number: " + pan);
[Link]("Mobile Number: " + mobile);
}
} catch (InvalidDataException e) { } }}
Output:

Q 35 . 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.

31
43k

Ans:
import [Link].*; // Import I/O classes (FileReader, FileWriter, etc.)

public class FileCopyCaseChange {


public static void main(String args[]) throws IOException {

// ----- Step 1: Create Reader and Writer -----


// Input file to read from ([Link])
// Output file to write to ([Link])
FileReader fr = new FileReader("[Link]");
FileWriter fw = new FileWriter("[Link]");

int ch; // variable to store each character

// ----- Step 2: Read source file character by character -----


while ((ch = [Link]()) != -1) { // read() returns -1 when end of file is
reached
char c = (char) ch;

// ----- Step 3: Replace digits by '*' -----


if ([Link](c)) {
c = '*';
}
// ----- Step 4: Change case -----
else if ([Link](c)) {
c = [Link](c);
} else if ([Link](c)) {
c = [Link](c);
}

// ----- Step 5: Write modified character to target file -----


[Link](c);
}

// ----- Step 6: Close files -----


[Link]();
[Link]();

[Link]("File copied successfully with case changes and


digits replaced!");

32
43k

}
}

Q 36. Write a java program for the following: [25 M] 1. To create a file. 2.
To rename a file. 3. To delete a file. 4. To display path of a file.
Ans:
import [Link].*;
import [Link];
public class FileOperations {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
File file = null;

try {
// Ask file name only once
[Link]("Enter the file name to create: ");
String fname = [Link]();
file = new File(fname);

if ([Link]()) {
[Link]("File created successfully: " + [Link]());
} else {
[Link]("File already exists.");
}

int choice;
do {
[Link]("\n===== FILE OPERATIONS MENU =====");
[Link]("1. Rename the File");
[Link]("2. Delete the File");
[Link]("3. Display File Path");
[Link]("4. Exit");
[Link]("Enter your choice: ");
choice = [Link]();
[Link](); // clear buffer

switch (choice) {
case 1:
[Link]("Enter new name for the file: ");
String newname = [Link]();

33
43k

File newFile = new File(newname);


if ([Link](newFile)) {
[Link]("File renamed successfully to: " +
newname);
file = newFile; // update reference
} else {
[Link]("Rename failed!");
}
break;

case 2:
if ([Link]()) {
[Link]("File deleted successfully.");
} else {
[Link]("File deletion failed!");
}
break;

case 3:
[Link]("File absolute path: " +
[Link]());
break;

case 4:
[Link]("Exiting program...");
break;

default:
[Link]("Invalid choice! Try again.");
}
} while (choice != 4);

} catch (IOException e) {
[Link]("Error: " + [Link]());
}

[Link]();
}
}

34
43k

Q 37 . 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. [15 M]
Ans:
import [Link];

// Single-class simple program


public class PalindromeCheck {

// User-defined exception for zero


static class ZeroNumberException extends Exception {
ZeroNumberException(String msg) {
super(msg);
}
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
String input = [Link]();

try {
int num = 0;

// Check if input is numeric


try {
num = [Link](input);
} catch (NumberFormatException e) {
throw new Exception("Number is Invalid"); // Non-numeric input
}

// Check if zero
if (num == 0) {
throw new ZeroNumberException("Number is Zero");
}

// Check palindrome
int original = num;

35
43k

int reverse = 0;
while (num != 0) {
int digit = num % 10;
reverse = reverse * 10 + digit;
num /= 10;
}

if (original == reverse)
[Link]("The number " + original + " is a palindrome.");
else
[Link]("The number " + original + " is not a
palindrome.");

} catch (ZeroNumberException e) {
[Link]([Link]()); // User-defined exception
} catch (Exception e) {
[Link]([Link]()); // Non-numeric input
}

[Link]();
}
}
Q38 . Write a java program to check whether given file is hidden or not.
If not then display its path, otherwise display appropriate message. [15
M]
Ans:
import [Link].*;
import [Link];

public class CheckHiddenFile {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Ask user for file name or path


[Link]("Enter the file name (or path): ");
String fname = [Link]();

// Create File object


File file = new File(fname);

36
43k

// Check if file exists first


if ([Link]()) {
// Check if file is hidden
if ([Link]()) {
[Link]("The file '" + [Link]() + "' is hidden.");
} else {
[Link]("The file is not hidden.");
[Link]("File path: " + [Link]());
}
} else {
[Link]("File does not exist!");
}

[Link]();
}
}

Q39 . Write a java program to count number of digits, spaces and


characters from a file.
Ans:
import [Link].*;
import [Link];

public class CountFileContent {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Ask user for the file name


[Link]("Enter the file name: ");
String fname = [Link]();

// Create a File object


File file = new File(fname);

// Check if file exists


if (![Link]()) {
[Link]("File does not exist!");
return;
}

37
43k

int digits = 0, spaces = 0, chars = 0;

try {
FileReader fr = new FileReader(file);
int ch;

// Read character by character


while ((ch = [Link]()) != -1) {
char c = (char) ch;

if ([Link](c))
digits++;
else if ([Link](c))
spaces++;
else
chars++;
}

[Link](); // Close file after reading

// Display results
[Link]("Total Digits: " + digits);
[Link]("Total Spaces: " + spaces);
[Link]("Total Characters: " + chars);

} catch (IOException e) {
[Link]("Error reading file: " + [Link]());
}

[Link]();
}
}

Q 40 . Write a java program to accept a number from user, If it is


greater than 1000 then throw user defined exception “Number is out of
Range” otherwise display the factors of that number. (Use static
keyword) [15 M]
Ans:
import [Link];

38
43k

public class NumberFactorsSingle {

// Static method to display factors


static void displayFactors(int num) {
[Link]("Factors of " + num + " are: ");
for (int i = 1; i <= num; i++) {
if (num % i == 0)
[Link](i + " ");
}
[Link]();
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();

try {
if (num > 1000) {
// Throwing exception directly with message
throw new Exception("Number is out of Range");
} else {
displayFactors(num); // Call static method
}
} catch (Exception e) {
[Link]([Link]()); // Print exception message
}

[Link]();
}
}

Q41 . Write a java program to check whether given candidate is


eligible for voting or not. Handle user defined as well as system defined
Exception. [15 M]
Ans:
import [Link];

public class VotingSimple {


public static void main(String[] args) {

39
43k

Scanner sc = new Scanner([Link]);

try {
[Link]("Enter your age: ");
int age = [Link]();

if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative!");
}
if (age < 18) {
throw new Exception("You are not eligible for voting.");
}

[Link]("You are eligible for voting!");

} catch (IllegalArgumentException e) {
[Link]([Link]()); // system-defined exception
} catch (Exception e) {
[Link]([Link]()); // user-defined message
}

[Link]();
}
}

40
43k

Chapter 5

Q 42 . Create an Applet that displays the x and y position of the cursor


movement using Mouse and Keyboard. (Use appropriate listener) [25
M]
Ans:
import [Link];
import [Link].*;
import [Link].*;

/*
<applet code="[Link]" width="500" height="400">
</applet>
*/

public class MouseKeyboardApplet extends Applet implements


MouseListener, MouseMotionListener, KeyListener {

// Variables to store coordinates and message


int x = 0, y = 0;
String msg = "Move mouse or press a key";

// ----- Init method: called once when applet starts -----


public void init() {
setBackground(Color.LIGHT_GRAY); // Set background color
setForeground([Link]); // Set text color
setFont(new Font("Arial", [Link], 16)); // Set font

// Register mouse and keyboard listeners


addMouseListener(this);
addMouseMotionListener(this);
addKeyListener(this);

// Request focus to capture keyboard input


requestFocus();
}

// ----- MouseListener methods -----


public void mouseClicked(MouseEvent e) {
x = [Link](); // X-coordinate of mouse click

41
43k

y = [Link](); // Y-coordinate of mouse click


msg = "Mouse Clicked at (" + x + ", " + y + ")";
repaint(); // Refresh screen
}

public void mousePressed(MouseEvent e) {}


public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}

// ----- MouseMotionListener methods -----


public void mouseMoved(MouseEvent e) {
x = [Link](); // X-coordinate while moving
y = [Link](); // Y-coordinate while moving
msg = "Mouse Moved at (" + x + ", " + y + ")";
repaint();
}

public void mouseDragged(MouseEvent e) {


// Required method, but we are not using it
}

// ----- KeyListener methods -----


public void keyPressed(KeyEvent e) {
msg = "Key Pressed: " + [Link](); // Show which key is pressed
repaint();
}

public void keyReleased(KeyEvent e) {}


public void keyTyped(KeyEvent e) {}

// ----- Paint method: draws message on screen -----


public void paint(Graphics g) {
[Link](msg, 100, 200);
}
}
Explanation:

Imports
import [Link];

42
43k

import [Link].*;
import [Link].*;
• [Link] → Base class for applets (small programs that
run in a browser or applet viewer).
• [Link].* → Provides GUI tools like Graphics, Color, Font.
• [Link].* → Provides interfaces like MouseListener,
MouseMotionListener, KeyListener to handle events.

Applet Tag
/*
<applet code="[Link]" width="500" height="400">
</applet>
*/
• This HTML-like comment tells the applet viewer which class to run
and the applet size.
• Width = 500 pixels, Height = 400 pixels.

Class Declaration
public class MouseKeyboardApplet extends Applet implements
MouseListener, MouseMotionListener, KeyListener
• Extends Applet → Makes this class a GUI applet.
• Implements three interfaces:
o MouseListener → Detect mouse clicks, presses, enters/exits.
o MouseMotionListener → Detect mouse movements and drags.
o KeyListener → Detect keyboard key presses.

Variables
int x = 0, y = 0;
String msg = "Move mouse or press a key";
• x, y → Store the current mouse coordinates.
• msg → Stores the message to display on screen. Initially prompts
user to move the mouse or press a key.

init() Method
public void init() {
setBackground(Color.LIGHT_GRAY);
setForeground([Link]);
setFont(new Font("Arial", [Link], 16));
addMouseListener(this);
addMouseMotionListener(this);

43
43k

addKeyListener(this);
requestFocus();
}
• init() → Runs once when the applet starts.
• GUI setup:
o setBackground(Color.LIGHT_GRAY) → Sets background color.
o setForeground([Link]) → Sets text color.
o setFont(...) → Sets the font style and size for text.
• Event registration:
o addMouseListener(this) → Enables click, press, enter, exit
events.
o addMouseMotionListener(this) → Enables mouse movement
tracking.
o addKeyListener(this) → Enables keyboard input.
• requestFocus() → Ensures the applet can capture keyboard input.

MouseListener Methods
public void mouseClicked(MouseEvent e) {
x = [Link]();
y = [Link]();
msg = "Mouse Clicked at (" + x + ", " + y + ")";
repaint();
}
• Triggered when mouse is clicked.
• [Link]() and [Link]() → Get x, y coordinates of the click.
• Updates msg with the position.
• repaint() → Calls the paint() method to refresh the screen.
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
• Required empty methods because MouseListener has 5 abstract
methods.
• Not used here but must be implemented.

MouseMotionListener Methods
public void mouseMoved(MouseEvent e) {
x = [Link]();
y = [Link]();
msg = "Mouse Moved at (" + x + ", " + y + ")";

44
43k

repaint();
}

public void mouseDragged(MouseEvent e) {


// Required method, but we are not using it
}
• mouseMoved → Runs continuously as the mouse moves. Updates
(x, y) and message.
• mouseDragged → Must exist for MouseMotionListener, but we don’t
need it here.

KeyListener Methods
public void keyPressed(KeyEvent e) {
msg = "Key Pressed: " + [Link]();
repaint();
}

public void keyReleased(KeyEvent e) {}


public void keyTyped(KeyEvent e) {}
• keyPressed → Triggered when any key is pressed.
• [Link]() → Gets the character of the key pressed.
• Updates msg and calls repaint().
• Other two methods are empty but required by KeyListener.

paint() Method
public void paint(Graphics g) {
[Link](msg, 100, 200);
}
• paint(Graphics g) → Runs whenever repaint() is called.
• [Link](msg, 100, 200) → Draws the message at coordinates
(100, 200).
• Displays the mouse position or key pressed on screen.

How the Program Works


1. Applet starts → init() runs → background color, font, listeners set.
2. Mouse moves → mouseMoved() → (x, y) updated → message
displayed.
3. Mouse clicks → mouseClicked() → message shows click coordinates.
4. Key press → keyPressed() → message shows key pressed.
5. Every event calls repaint() → updates the display in paint().

45
43k

Q43. Write a java program to display Label with text “Dr. D Y Patil
College”, background color Red and font size 20 on the frame.
Ans:
import [Link].*;
import [Link].*;
public class CollegeLabel {
public static void main(String[] args) {
JFrame f = new JFrame("College Label");
JLabel l = new JLabel("Dr. D Y Patil College", [Link]);
[Link](new Font("Arial", [Link], 20)); // font size 20
[Link](true); // make background visible
[Link]([Link]); // red background
[Link]([Link]); // white text
[Link](l);
[Link](400, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}}
Output:

Q44. Design a screen in Java to handle the Mouse Events such as


MOUSE_MOVED and MOUSE_CLICK and display the position of the
Mouse_Click in a TextField. [25 M]
Ans:
// Importing required AWT and Event packages
import [Link].*;
import [Link].*;

// Class extending Frame and implementing MouseListener and


MouseMotionListener interfaces

46
43k

public class MouseEventExample extends Frame implements


MouseListener, MouseMotionListener {

TextField tf; // TextField to display the coordinates

// Constructor
MouseEventExample() {
// Set title of the window
setTitle("Mouse Event Example");

// Create a TextField and set its initial text


tf = new TextField("Click or move the mouse inside the window");
[Link](50, 100, 300, 30); // set position and size (x, y, width,
height)

// Add TextField to the Frame


add(tf);

// Add Mouse Listener and Mouse Motion Listener to the Frame


addMouseListener(this);
addMouseMotionListener(this);

// Set layout to null for absolute positioning


setLayout(null);
setSize(400, 300); // width x height of window
setVisible(true); // make the frame visible

47
43k

// Close the frame when the window is closed


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);
}
});
}

// This method is called when mouse is clicked


public void mouseClicked(MouseEvent e) {
// Get X and Y position of the click
int x = [Link]();
int y = [Link]();
// Display coordinates in the TextField
[Link]("Mouse Clicked at: X=" + x + ", Y=" + y);
}

// This method is called when the mouse is moved (without pressing any
button)
public void mouseMoved(MouseEvent e) {
// Get X and Y position of the mouse movement
int x = [Link]();
int y = [Link]();
// Display current mouse position in the TextField
[Link]("Mouse Moving at: X=" + x + ", Y=" + y);
}

48
43k

// Unused methods (required because we implemented the interfaces)


public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseDragged(MouseEvent e) {}

// Main method
public static void main(String[] args) {
new MouseEventExample(); // create an object and display the frame
}
}
Output:

Explanation:
MOST IMPORTANT PARTS (Required for Program to Work)
These are compulsory — without them, the program will not compile or
run correctly.
Part Why It’s Important
import [Link].*; and import Needed to use AWT
[Link].*; components (Frame, TextField)
and event classes (MouseEvent,
MouseListener,
MouseMotionListener).

49
43k

public class MouseEventExample The class must extend Frame to


extends Frame implements create a window and must
MouseListener, implement these interfaces to
MouseMotionListener handle mouse events.
addMouseListener(this); and These register the window to
addMouseMotionListener(this); actually listen for mouse
events. Without them, no event
(click or move) will be detected.
mouseClicked(MouseEvent e) and These methods define what
mouseMoved(MouseEvent e) happens when a mouse click or
methods move occurs. Without them, the
program would not respond to
those events.
setSize(400, 300); and setSize() sets window size;
setVisible(true); setVisible(true) makes the
window appear on screen.
Without setVisible(true), the
frame will not show at all.
public static void main(String[] args) The entry point — Java starts
execution here. Without this,
the program can’t run.

Q45 . Write a java program to accept directory name in TextField and


display list of files and subdirectories in List Control from that
directory by clicking on Button.
Ans:
import [Link].*;
import [Link].*;
import [Link];

public class DirectoryLister extends Frame implements ActionListener {

TextField tf; // To accept directory path


List fileList; // To display files and subdirectories
Button btn; // Button to trigger listing

// Constructor
DirectoryLister() {

50
43k

setTitle("Directory Lister");
setSize(500, 400);
setLayout(new FlowLayout());

// TextField for directory input


tf = new TextField(30);

// Button to list files


btn = new Button("Show Files");
[Link](this); // Register button click

// List to display files/subdirectories


fileList = new List(15, false); // 15 rows, single selection

// Add components to frame


add(new Label("Enter Directory Path:"));
add(tf);
add(btn);
add(fileList);

setVisible(true);

// Close window properly


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
dispose();
}
});
}

// Handle button click


public void actionPerformed(ActionEvent ae) {
[Link](); // Clear previous list
String dirName = [Link](); // Get directory path
File dir = new File(dirName);

if ([Link]() && [Link]()) {


String[] files = [Link](); // Get list of files & subdirs
for (String f : files) {
[Link](f);

51
43k

}
} else {
[Link]("Invalid Directory!");
}
}

// Main method
public static void main(String[] args) {
new DirectoryLister();
}
}

Q46. Write an applet application to display Table lamp. The color of


lamp should get change randomly. [25 M]
Ans:
import [Link].*;
import [Link].*;
import [Link].*;

/*
<applet code="TableLampApplet" width=400 height=400>
</applet>
*/

public class Table extends Applet implements Runnable {


Thread t; // Thread to change colors automatically
Color lampColor; // Variable to store current lamp color
Random rand = new Random();

public void init() {


// Set initial lamp color to yellow
lampColor = [Link];

// Start a new thread to change color continuously


t = new Thread(this);
[Link]();
}

public void run() {


try {

52
43k

while (true) {
// Generate a random color for the lamp
lampColor = new Color([Link](256), [Link](256),
[Link](256));
repaint(); // Refresh the screen with new color
[Link](1000); // Wait 1 second before changing color again
}
} catch (Exception e) {}
}

public void paint(Graphics g) {


// Set background color
setBackground([Link]);

// ---- LAMP SHADE ----


[Link](lampColor);
[Link](120, 50, 160, 100, 0, 360);
/*
Arc(x=120, y=50, width=160, height=100, startAngle=0, arcAngle=180)
→ Draws the top lamp shade (a half-oval shape).
The color changes randomly every second.
*/

// ---- LAMP NECK ----


[Link]([Link]);
[Link](190, 150, 20, 60);
/*
Rectangle (x=190, y=150, width=20, height=60)
→ Acts as the stand/neck connecting the lamp shade and base.
*/

// ---- LAMP BASE ----


[Link]([Link]);
[Link](150, 210, 100, 30);
/*
Oval(x=150, y=210, width=100, height=30)
→ Represents the flat base of the lamp.
*/

// ---- TABLE ----

53
43k

[Link](new Color(150, 100, 50)); // brown color


[Link](0, 240, 400, 40);
/*
Rectangle (x=0, y=240, width=400, height=40)
→ Represents the wooden table surface on which the lamp stands.
*/

// ---- LAMP WIRE (Optional Decoration) ----


[Link]([Link]);
[Link](210, 230, 300, 260);
/*
Line(x1=210, y1=230, x2=300, y2=260)
→ Represents the wire coming out from the base of the lamp.
*/

// ---- TITLE ----


[Link]([Link]);
[Link](new Font("Arial", [Link], 16));
[Link]("Color Changing Table Lamp", 100, 20);
}
}

Output:

Explanation

Shape / Method Used Coordinates Description


Part & Size

54
43k

Lamp fillArc(120, 50, 160, 100, Draws half- The colorful


Shade 0, 180) oval curved part of
(Top) the lamp that
changes color
randomly.
Lamp fillRect(190, 150, 20, 60) Rectangle The vertical
Neck support joining
(Middle) shade and base.
Lamp fillOval(150, 210, 100, 30) Oval Represents the
Base flat part on
(Bottom) which lamp
stands.
Table fillRect(0, 240, 400, 40) Rectangle Represents the
across table surface.
bottom
Wire drawLine(210, 230, 300, Line Decorative wire
(Optional) 260) coming out from
lamp base.
Random new Random RGB Generates new
Color Color([Link](256), color for the
[Link](256), shade every
[Link](256)) second.
Thread run() + sleep(1000) Runs in Keeps changing
background the lamp color
automatically.

Q 47 . Write a java Program to accept the details of 5 employees (Eno,


Ename, Salary) and display it onto the JTable
Ans:
import [Link].*;
import [Link].*;
import [Link];
import [Link].*;

public class EmployeeTableForm extends JFrame implements


ActionListener {
JTextField tEno, tEname, tSalary;
JButton addButton;
JTable table;

55
43k

DefaultTableModel model;

public EmployeeTableForm() {
super("Employee Details");

// Labels and TextFields


JLabel l1 = new JLabel("Employee No:");
JLabel l2 = new JLabel("Employee Name:");
JLabel l3 = new JLabel("Salary:");

tEno = new JTextField(10);


tEname = new JTextField(10);
tSalary = new JTextField(10);

addButton = new JButton("Add Employee");


[Link](this);

// Table setup
String[] columns = {"Employee No", "Employee Name", "Salary"};
model = new DefaultTableModel(columns, 0);
table = new JTable(model);
JScrollPane sp = new JScrollPane(table);

// Layout for form


JPanel inputPanel = new JPanel();
[Link](new GridLayout(4, 2, 10, 10));
[Link](l1); [Link](tEno);
[Link](l2); [Link](tEname);
[Link](l3); [Link](tSalary);
[Link](new JLabel("")); [Link](addButton);

// Frame Layout
setLayout(new BorderLayout(10, 10));
add(inputPanel, [Link]);
add(sp, [Link]);

setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

56
43k

public void actionPerformed(ActionEvent e) {


// Get data from text fields
String eno = [Link]();
String ename = [Link]();
String salary = [Link]();

// Add row to table


[Link](new Object[]{eno, ename, salary});

// Clear fields for next entry


[Link]("");
[Link]("");
[Link]("");
}

public static void main(String[] args) {


new EmployeeTableForm();
}
}

Q48. Write a java program to display multiplication table of a given


number into the List box by clicking on button. [25 M]
Ans:
import [Link].*; // Import AWT classes for GUI components
import [Link].*; // Import event-handling classes

// Create class extending Frame and implementing ActionListener


public class MultiplicationTableAWT extends Frame implements
ActionListener {

Label l1; // Label to show instruction


TextField t1; // TextField to take user input
Button b1; // Button to trigger action
List list; // List box to display multiplication table

// Constructor
MultiplicationTableAWT() {

57
43k

setTitle("Multiplication Table"); // Title of the window

setLayout(null); // Disable layout manager (so we can set our own


positions)

// ----- Label -----


l1 = new Label("Enter a number:");
// setBounds(x, y, width, height)
// x = 50 → distance from left edge of frame
// y = 50 → distance from top edge of frame
// width = 100 → label width in pixels
// height = 30 → label height in pixels
[Link](50, 50, 100, 30);

// ----- TextField -----


t1 = new TextField();
// x = 170, y = 50 → position next to label
// width = 100, height = 30 → size of the text field
[Link](170, 50, 100, 30);

// ----- Button -----


b1 = new Button("Show Table");
// x = 100, y = 100 → below the text field
// width = 100, height = 30 → size of the button
[Link](100, 100, 100, 30);

// ----- List Box -----


list = new List();
// x = 50, y = 150 → position of list below button
// width = 220, height = 200 → list box area
[Link](50, 150, 220, 200);

// Add components to frame


add(l1);
add(t1);
add(b1);
add(list);

// Register ActionListener to handle button click event


[Link](this);

58
43k

// Set size of frame: width=350, height=400


setSize(350, 400);

// Make frame visible on screen


setVisible(true);

// Add window closing event so program stops when user clicks "X"
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);
}
});
}

// ----- Action performed when button is clicked -----


public void actionPerformed(ActionEvent e) {
// Clear previous list entries
[Link]();

try {
// Read number entered in text field
int n = [Link]([Link]());

// Generate multiplication table from 1 to 10


for (int i = 1; i <= 10; i++) {
// Add each line (e.g., "5 x 2 = 10") to the list box
[Link](n + " x " + i + " = " + (n * i));
}
} catch (NumberFormatException ex) {
// If user enters invalid input (like letters), show error
[Link]("Please enter a valid number!");
}
}

// ----- Main method -----


public static void main(String args[]) {
new MultiplicationTableAWT(); // Create an object and show window
}
}

59
43k

Explanation:
Program Explanation (Step-by-Step)
1. Import Statements
import [Link].*;
import [Link].*;
• [Link].* → gives access to AWT components (Frame, Label, Button,
TextField, List).
• [Link].* → gives access to event-handling classes like
ActionEvent and ActionListener.

2. Class Declaration
public class MultiplicationTableAWT extends Frame implements
ActionListener
• extends Frame → creates a window where components (buttons,
labels, etc.) will appear.
• implements ActionListener → lets the class respond to button clicks.

3. Declaring Components
Label l1;
TextField t1;
Button b1;
List list;
These are the GUI elements:
• Label → displays text like “Enter a number.”
• TextField → allows user to type a number.
• Button → user clicks this to generate the table.
• List → displays the table results line by line.

4. Constructor
Everything inside the constructor sets up the window and its components.
a. Frame Settings
setTitle("Multiplication Table");
setLayout(null);
• setTitle() → sets the title shown on the window bar.
• setLayout(null) → disables automatic layout, so you can manually
place components with setBounds().

b. Label
l1 = new Label("Enter a number:");

60
43k

[Link](50, 50, 100, 30);


• Creates a label with the text “Enter a number.”
• setBounds(x, y, width, height) → positions and sizes the label.
o x=50, y=50 → position on screen.
o width=100, height=30 → size of label.

c. TextField
t1 = new TextField();
[Link](170, 50, 100, 30);
• Creates an empty box where the user types a number.
• Placed next to the label (x=170).

d. Button
b1 = new Button("Show Table");
[Link](100, 100, 100, 30);
• Creates a clickable button with the text “Show Table.”
• When clicked, it will call actionPerformed().

e. List Box
list = new List();
[Link](50, 150, 220, 200);
• Creates a list area where 10 lines of multiplication table will appear.
• Given enough width and height to display all rows.

f. Add Components to Frame


add(l1); add(t1); add(b1); add(list);
Makes all components visible inside the frame.

g. Event Registration
[Link](this);
• Links the button to this class, so when button is clicked →
actionPerformed() runs.

h. Frame Size and Visibility


setSize(350, 400);
setVisible(true);
• setSize() → sets total window size.
• setVisible(true) → makes window appear on screen.

i. Close Button (WindowAdapter)

61
43k

addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);
}
});
• Allows closing the program when user clicks the “X” button on the
window.

5. ActionPerformed() — When Button is Clicked


public void actionPerformed(ActionEvent e) {
[Link](); // clears old data
try {
int n = [Link]([Link]()); // read number
for (int i = 1; i <= 10; i++) {
[Link](n + " x " + i + " = " + (n * i)); // add line to list
}
} catch (NumberFormatException ex) {
[Link]("Please enter a valid number!"); // handle wrong input
}
}
Explanation:
1. Clears the list (so old table disappears).
2. Reads the number typed in the TextField ([Link]()).
3. Converts it from text to number using [Link]().
4. Uses a loop for (i=1 to 10) to multiply the number and add results to
the list.
5. If the user types something invalid (like letters), it shows an error
message.

6. Main Method
public static void main(String args[]) {
new MultiplicationTableAWT();
}
• Entry point of the program.
• Creates an object of the class → constructor runs → window appears.

Q49. Write a java program to accept the details of employee (Eno,


EName, Sal) and display it on next frame using appropriate event
import [Link].*;

62
43k

import [Link].*;
import [Link].*;

public class EmployeeDetails extends JFrame implements ActionListener {


// Declaring components
JLabel l1, l2, l3;
JTextField t1, t2, t3;
JButton b1;

EmployeeDetails() {
// Set title for the first frame
setTitle("Employee Entry Form");
setLayout(null); // manual positioning

// Label for Employee Number


l1 = new JLabel("Employee No:");
[Link](50, 50, 100, 30); // x,y,width,height

// TextField for Employee Number


t1 = new JTextField();
[Link](160, 50, 150, 30);

// Label for Employee Name


l2 = new JLabel("Employee Name:");
[Link](50, 100, 120, 30);

// TextField for Employee Name


t2 = new JTextField();
[Link](160, 100, 150, 30);

// Label for Salary


l3 = new JLabel("Salary:");
[Link](50, 150, 100, 30);

// TextField for Salary


t3 = new JTextField();
[Link](160, 150, 150, 30);

// Button to show details


b1 = new JButton("Show Details");

63
43k

[Link](120, 200, 120, 40);

// Add components to the frame


add(l1); add(t1);
add(l2); add(t2);
add(l3); add(t3);
add(b1);

// Register ActionListener for the button


[Link](this);

// Frame settings
setSize(380, 320);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

// Event Handling (Button click)


public void actionPerformed(ActionEvent e) {
// Read data from text fields
String eno = [Link]();
String name = [Link]();
String sal = [Link]();

// Open new frame to display details


JFrame displayFrame = new JFrame("Employee Details");
[Link](null);

JLabel d1 = new JLabel("Employee No: " + eno);


[Link](50, 50, 250, 30);

JLabel d2 = new JLabel("Employee Name: " + name);


[Link](50, 100, 250, 30);

JLabel d3 = new JLabel("Salary: " + sal);


[Link](50, 150, 250, 30);

[Link](d1);
[Link](d2);
[Link](d3);

64
43k

[Link](350, 250);
[Link](true);
}

// main method
public static void main(String args[]) {
new EmployeeDetails();
}
}

Q50. Write an applet application to display smiley face. [25 M]


Ans;
import [Link];
import [Link].*;

/*
<applet code="[Link]" width="400" height="400">
</applet>
*/

public class SmileyFaceApplet extends Applet {

public void paint(Graphics g) {

// ----- 1. Face (Main Circle) -----


[Link]([Link]); // Set color to Yellow for face
// drawOval(x, y, width, height)
// x=100, y=100 → top-left corner of oval
// width=200, height=200 → size of the face
[Link](100, 100, 200, 200);

// ----- 2. Eyes -----


[Link]([Link]);
// Left Eye
// x=155, y=160 → position of left eye
// width=25, height=25 → size of eye
[Link](155, 160, 25, 25);

65
43k

// Right Eye
// x=220, y=160 → position of right eye
// width=25, height=25 → size of eye
[Link](220, 160, 25, 25);

// ----- 3. Mouth -----


[Link]([Link]);
// drawArc(x, y, width, height, startAngle, arcAngle)
// x=150, y=180 → mouth’s bounding box start position
// width=100, height=80 → arc width and height
// startAngle=180, arcAngle=180 → draws a semi-circle (smile)
[Link](150, 180, 100, 80, 180, 180);

// ----- 4. Nose -----


[Link]([Link]);
// drawLine(x1, y1, x2, y2) – Draw a simple triangle-like nose
[Link](200, 180, 190, 210);
[Link](200, 180, 210, 210);
[Link](190, 210, 210, 210);

// ----- 5. Caption -----


[Link]([Link]);
[Link](new Font("Arial", [Link], 18));
[Link]("Keep Smiling!", 140, 330);
}
}

Q51. Write a java program using AWT to create a Frame with title
“TYBBACA”, background color RED. If user clicks on close button then
frame should close. [15 M]
Ans:
import [Link].*;
import [Link].*;

public class TYBBACAFrame {

public static void main(String[] args) {


// ----- Step 1: Create Frame -----
Frame f = new Frame("TYBBACA"); // Set frame title

66
43k

// ----- Step 2: Set Frame Size -----


[Link](400, 300); // width = 400, height = 300

// ----- Step 3: Set Background Color -----


[Link]([Link]);

// ----- Step 4: Make Frame Visible -----


[Link](true);

// ----- Step 5: Handle Close Button -----


[Link](new WindowAdapter() {
public void windowClosing(WindowEvent we) {
[Link](); // Close the frame when user clicks the close button
}
});
}
}

Q52. Write a java program using applet to draw Temple. [25 M]


Ans:
import [Link];
import [Link].*;
public class TempleApplet extends Applet {

public void paint(Graphics g) {


// ----- Background Setup -----
setBackground(Color.LIGHT_GRAY); // Set background color
[Link]([Link]); // Set drawing color

// ----- Temple Base -----


[Link](Color.DARK_GRAY);
[Link](150, 350, 200, 50); // (x, y, width, height)

// ----- Main Temple Body -----


[Link]([Link]);
[Link](200, 250, 100, 100); // middle part of temple

// ----- Temple Roof (Triangle shape) -----

67
43k

[Link]([Link]);
int x[] = {190, 250, 310}; // x-coordinates of triangle points
int y[] = {250, 180, 250}; // y-coordinates of triangle points
[Link](x, y, 3); // draw roof using triangle

// ----- Door -----


[Link]([Link]);
[Link](235, 300, 30, 50); // door in center

// ----- Pillars -----


[Link](Color.DARK_GRAY);
[Link](180, 280, 20, 70); // left pillar
[Link](300, 280, 20, 70); // right pillar

// ----- Steps -----


[Link]([Link]);
[Link](140, 400, 220, 10); // step 1
[Link](130, 410, 240, 10); // step 2

// ----- Flag on Top -----


[Link]([Link]);
[Link](250, 180, 250, 150); // flag pole
int fx[] = {250, 250, 270}; // flag triangle
int fy[] = {150, 160, 155};
[Link](fx, fy, 3);

// ----- Label -----


[Link]([Link]);
[Link]("Temple", 230, 440);
}
}
Output:

68
43k

Q 53 . Write a java program using Applet for bouncing ball. Ball should
change its color for each bounce.
Ans:
import [Link];
import [Link].*;
import [Link];

public class ColorBounceBall extends Applet implements Runnable {

int x = 200, y = 50; // Ball position


int dy = 3; // Vertical speed
int radius = 30; // Ball size
int ground = 350; // Bottom position for bounce
boolean movingDown = true; // Direction flag
Color ballColor = [Link]; // Initial color
Thread t; // Thread for animation
Random r = new Random(); // For random color change

// ----- Initialize Applet -----


public void init() {
setBackground(Color.LIGHT_GRAY);
t = new Thread(this);
[Link]();
}

// ----- Main animation loop -----


public void run() {
while (true) {
// Move the ball

69
43k

if (movingDown) {
y += dy; // Move downward
if (y >= ground - radius) {
movingDown = false;
changeColor(); // Change color when it hits ground
}
} else {
y -= dy; // Move upward
if (y <= 30) {
movingDown = true;
changeColor(); // Change color when it hits top
}
}

repaint(); // Redraw
try {
[Link](15); // Smooth animation
} catch (InterruptedException e) {}
}
}

// ----- Change ball color randomly -----


void changeColor() {
ballColor = new Color([Link](256), [Link](256), [Link](256));
}

// ----- Draw the ball and ground -----


public void paint(Graphics g) {
[Link](Color.DARK_GRAY);
[Link](0, ground, getWidth(), 20); // Draw ground

[Link](ballColor);
[Link](x, y, radius, radius); // Draw ball
}
}

Q54 . Write a java program for the following:

70
43k

Ans:
import [Link].*;
import [Link].*;

public class CompoundInterestExact extends JFrame implements


ActionListener {
JLabel l1, l2, l3, l4, l5;
JTextField t1, t2, t3, t4, t5;
JButton b1, b2, b3;

public CompoundInterestExact() {
setTitle("Compound Interest Calculator");
setLayout(null);

l1 = new JLabel("Principal Amount");


[Link](30, 30, 150, 25);
add(l1);

t1 = new JTextField();
[Link](180, 30, 120, 25);
add(t1);

l2 = new JLabel("Interest Rate (%)");


[Link](30, 70, 150, 25);
add(l2);

t2 = new JTextField();
[Link](180, 70, 120, 25);
add(t2);

l3 = new JLabel("Time (Yrs)");


[Link](30, 110, 150, 25);
add(l3);
71
43k

t3 = new JTextField();
[Link](180, 110, 120, 25);
add(t3);

l4 = new JLabel("Total Amount");


[Link](30, 150, 150, 25);
add(l4);

t4 = new JTextField();
[Link](180, 150, 120, 25);
add(t4);

l5 = new JLabel("Interest Amount");


[Link](30, 190, 150, 25);
add(l5);

t5 = new JTextField();
[Link](180, 190, 120, 25);
add(t5);

b1 = new JButton("Calculate");
[Link](30, 230, 90, 25);
add(b1);

b2 = new JButton("Clear");
[Link](130, 230, 70, 25);
add(b2);

b3 = new JButton("Close");
[Link](210, 230, 70, 25);
add(b3);

[Link](this);
[Link](this);
[Link](this);

setSize(350, 330);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);

72
43k

public void actionPerformed(ActionEvent e) {


if ([Link]() == b1) {
double p = [Link]([Link]());
double r = [Link]([Link]());
double t = [Link]([Link]());
double a = p * [Link](1 + r / 100, t);
double i = a - p;
[Link]([Link]("%.2f", a));
[Link]([Link]("%.2f", i));
} else if ([Link]() == b2) {
[Link](""); [Link](""); [Link]("");
[Link](""); [Link]("");
} else if ([Link]() == b3) {
dispose();
}
}

public static void main(String[] args) {


new CompoundInterestExact();
}
}

Q55 . Write a java program to design following Frame using Swing. [25
M].

Ans:
import [Link].*;
import [Link].*;
import [Link].*;

73
43k

public class MenuBarDemo extends JFrame implements ActionListener {


JMenuBar menuBar;
JMenu fileMenu, editMenu, searchMenu;
JMenuItem newItem, openItem, exitItem, cutItem, copyItem, pasteItem,
findItem;
JLabel msg;

MenuBarDemo() {
setTitle("Menu Bar Example");
setLayout(null);
setSize(500, 350);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Background color same as screenshot


getContentPane().setBackground(new Color(200, 230, 255)); // light
blue shade

// Create Menu Bar


menuBar = new JMenuBar();
[Link](new Color(51, 102, 204)); // deep blue
[Link]([Link]);

// Menus
fileMenu = new JMenu("File");
[Link]([Link]);
editMenu = new JMenu("Edit");
[Link]([Link]);
searchMenu = new JMenu("Search");
[Link]([Link]);

// File Menu Items


newItem = new JMenuItem("New");
openItem = new JMenuItem("Open");
exitItem = new JMenuItem("Exit");

// Edit Menu Items


cutItem = new JMenuItem("Cut");
copyItem = new JMenuItem("Copy");
pasteItem = new JMenuItem("Paste");

74
43k

// Search Menu Items


findItem = new JMenuItem("Find");

// Add items to Menus


[Link](newItem);
[Link](openItem);
[Link](exitItem);

[Link](cutItem);
[Link](copyItem);
[Link](pasteItem);

[Link](findItem);

// Add Menus to Menu Bar


[Link](fileMenu);
[Link](editMenu);
[Link](searchMenu);

// Add MenuBar to Frame


setJMenuBar(menuBar);

// Label to show selected action


msg = new JLabel("Select any menu item");
[Link](150, 120, 250, 30);
[Link](new Font("Arial", [Link], 14));
add(msg);

// Add Action Listeners


[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);

setVisible(true);
}

75
43k

public void actionPerformed(ActionEvent e) {


String command = [Link]();
if ([Link]("Exit"))
[Link](0);
else
[Link]("You selected: " + command);
}

public static void main(String[] args) {


new MenuBarDemo();
}
}

Q 56 . Write a java program to design a following GUI (Use Swing). [25


M]. For personal information

Ans:
import [Link].*;
import [Link].*;

public class PersonalInfoExact extends JFrame implements ActionListener


{
JLabel l1, l2, l3, l4, l5, l6;
JTextField t1, t2, t3, t4;
JRadioButton male, female;
JCheckBox c1, c2, c3;
JButton b1, b2;
ButtonGroup bg;

public PersonalInfoExact() {
setTitle("Personal Information");
setLayout(null);

l1 = new JLabel("First Name :");

76
43k

[Link](30, 30, 100, 25);


add(l1);

t1 = new JTextField();
[Link](140, 30, 150, 25);
add(t1);

l2 = new JLabel("Last Name :");


[Link](30, 65, 100, 25);
add(l2);

t2 = new JTextField();
[Link](140, 65, 150, 25);
add(t2);

l3 = new JLabel("Address :");


[Link](30, 100, 100, 25);
add(l3);

t3 = new JTextField();
[Link](140, 100, 150, 25);
add(t3);

l4 = new JLabel("Mobile Number :");


[Link](30, 135, 100, 25);
add(l4);

t4 = new JTextField();
[Link](140, 135, 150, 25);
add(t4);

l5 = new JLabel("Gender :");


[Link](30, 170, 100, 25);
add(l5);

male = new JRadioButton("Male");


[Link](140, 170, 70, 25);
add(male);

female = new JRadioButton("Female");

77
43k

[Link](220, 170, 80, 25);


add(female);

bg = new ButtonGroup();
[Link](male);
[Link](female);

l6 = new JLabel("Your Interests :");


[Link](30, 205, 100, 25);
add(l6);

c1 = new JCheckBox("Computer");
[Link](140, 205, 90, 25);
add(c1);

c2 = new JCheckBox("Sports");
[Link](230, 205, 80, 25);
add(c2);

c3 = new JCheckBox("Music");
[Link](310, 205, 70, 25);
add(c3);

b1 = new JButton("Submit");
[Link](100, 240, 90, 25);
add(b1);

b2 = new JButton("Reset");
[Link](200, 240, 90, 25);
add(b2);

[Link](this);
[Link](this);

setSize(420, 340);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public void actionPerformed(ActionEvent e) {

78
43k

if ([Link]() == b2) {
[Link]("");
[Link]("");
[Link]("");
[Link]("");
[Link]();
[Link](false);
[Link](false);
[Link](false);
} else if ([Link]() == b1) {
[Link](this, "Submitted Successfully!");
}
}

public static void main(String[] args) {


new PersonalInfoExact();
}
}

Q 57 . Write a java program using Applet to implement a simple


arithmetic calculator.

Ans:
import [Link].*;
import [Link].*;
import [Link].*;

/*
<applet code="[Link]" width=320 height=440>
</applet>
*/

public class CalApplet extends Applet implements ActionListener {

// ======= Declare UI Components =======

79
43k

TextField display; // For showing input/output


Button b7,b8,b9,b4,b5,b6,b1,b2,b3,b0; // digit buttons
Button add,sub,mul,div,eq,clr; // operator and control buttons

// ======= Variables for calculation =======


double num1=0, num2=0, result=0; // store operands and result
char op; // store operator (+, -, *, /)
boolean startNew=true; // flag to start new input

public void init() {


// Set layout to manual positioning
setLayout(null);
setBackground(new Color(230,230,230)); // light gray background

// ======= Display TextField =======


display = new TextField();
[Link](25, 30, 260, 40); // (x, y, width, height)
[Link](new Font("Arial", [Link], 18)); // set font
add(display);

// ======= Layout button spacing =======


int startX = 25; // left margin
int startY = 90; // top margin
int w = 50; // button width
int h = 40; // button height
int gapX = 65; // space between buttons horizontally
int gapY = 60; // space between buttons vertically

// ======= FIRST ROW (7 8 9 +) =======


b7 = makeButton("7", startX, startY);
b8 = makeButton("8", startX + gapX, startY);
b9 = makeButton("9", startX + 2*gapX, startY);
add = makeButton("+", startX + 3*gapX, startY);

// ======= SECOND ROW (4 5 6 -) =======


b4 = makeButton("4", startX, startY + gapY);
b5 = makeButton("5", startX + gapX, startY + gapY);
b6 = makeButton("6", startX + 2*gapX, startY + gapY);
sub = makeButton("-", startX + 3*gapX, startY + gapY);

80
43k

// ======= THIRD ROW (1 2 3 *) =======


b1 = makeButton("1", startX, startY + 2*gapY);
b2 = makeButton("2", startX + gapX, startY + 2*gapY);
b3 = makeButton("3", startX + 2*gapX, startY + 2*gapY);
mul = makeButton("*", startX + 3*gapX, startY + 2*gapY);

// ======= FOURTH ROW (0 /) =======


b0 = makeButton("0", startX + gapX, startY + 3*gapY);
div = makeButton("/", startX + 3*gapX, startY + 3*gapY);

// ======= FIFTH ROW (= BELOW /) =======


eq = makeButton("=", startX + 3*gapX, startY + 4*gapY);

// ======= SIXTH ROW (Clear Button) =======


clr = makeButton("Clear", startX + 70, startY + 5*gapY);
[Link](new Color(255, 200, 200)); // light red background

// Add all buttons to applet


addAll(b7,b8,b9,b4,b5,b6,b1,b2,b3,b0,add,sub,mul,div,eq,clr);
}

// ======= Helper method to create a styled button =======


Button makeButton(String label, int x, int y) {
Button b = new Button(label); // create button
[Link](x, y, 50, 40); // position & size
[Link](new Font("Arial", [Link], 16));
[Link]([Link]);
[Link](this); // add listener for click
add(b);
return b;
}

// ======= Helper method to add multiple components =======


void addAll(Component... comps) {
for (Component c : comps)
add(c);
}

// ======= Handle button click events =======


public void actionPerformed(ActionEvent e) {

81
43k

String cmd = [Link](); // get text of clicked button

// -------- CLEAR BUTTON --------


if ([Link]("Clear")) {
[Link](""); // clear display
num1=num2=result=0;
op=' ';
startNew=true;
return;
}

// -------- OPERATOR BUTTONS (+, -, *, /) --------


if ([Link]("+") || [Link]("-") || [Link]("*") ||
[Link]("/")) {
try {
num1 = [Link]([Link]()); // store first
number
op = [Link](0); // store operator
startNew = true; // prepare for next number
} catch (Exception ex) {
[Link]("Error");
}
return;
}

// -------- EQUAL BUTTON (=) --------


if ([Link]("=")) {
try {
num2 = [Link]([Link]()); // second number

// Perform operation based on operator


switch (op) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/':
if (num2 != 0)
result = num1 / num2;
else {
[Link]("Div by 0");

82
43k

return;
}
break;
}
[Link]([Link](result)); // show result
startNew = true;
} catch (Exception ex) {
[Link]("Error");
}
return;
}

// -------- DIGIT BUTTONS (0–9) --------


if (startNew) {
// if starting new input, replace old text
[Link](cmd);
startNew = false;
} else {
// append digit to existing number
[Link]([Link]() + cmd);
}
}
}

83

You might also like