Java Programming Exercises and Solutions
Java Programming Exercises and Solutions
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:
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:
2
43k
int i,j;
for(i=5;i>=1;i--){
for(j=i;j<=5;j++){
[Link](j +" ");
}
[Link]();
}}}
Output:
3
43k
}
else{
[Link](0 + " ");
}
k++;
}
[Link]();
}}}
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
7
43k
8
43k
int n = [Link]();
printFibonacci(n); // function call
}}
Output:
Output:
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]();
}
}
13
43k
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
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
17
43k
class main1 {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
18
43k
// Display Students
for (int i = 0; i < n; i++) {
s1[i].disp();
}
// 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:
[Link]
package Series;
20
43k
}}
[Link]
package Series;
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:
21
43k
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
// 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
// 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];
25
43k
===================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]();
[Link]();
[Link]("Non-numeric characters copied successfully!");
}
}
Output:
27
43k
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:
}
[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 ( ||
) {
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.)
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
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
try {
int num = 0;
// 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];
36
43k
[Link]();
}
}
37
43k
try {
FileReader fr = new FileReader(file);
int ch;
if ([Link](c))
digits++;
else if ([Link](c))
spaces++;
else
chars++;
}
// Display results
[Link]("Total Digits: " + digits);
[Link]("Total Spaces: " + spaces);
[Link]("Total Characters: " + chars);
} catch (IOException e) {
[Link]("Error reading file: " + [Link]());
}
[Link]();
}
}
38
43k
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]();
}
}
39
43k
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.");
}
} catch (IllegalArgumentException e) {
[Link]([Link]()); // system-defined exception
} catch (Exception e) {
[Link]([Link]()); // user-defined message
}
[Link]();
}
}
40
43k
Chapter 5
/*
<applet code="[Link]" width="500" height="400">
</applet>
*/
41
43k
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();
}
KeyListener Methods
public void keyPressed(KeyEvent e) {
msg = "Key Pressed: " + [Link]();
repaint();
}
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.
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:
46
43k
// Constructor
MouseEventExample() {
// Set title of the window
setTitle("Mouse Event Example");
47
43k
// 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
// 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
// Constructor
DirectoryLister() {
50
43k
setTitle("Directory Lister");
setSize(500, 400);
setLayout(new FlowLayout());
setVisible(true);
51
43k
}
} else {
[Link]("Invalid Directory!");
}
}
// Main method
public static void main(String[] args) {
new DirectoryLister();
}
}
/*
<applet code="TableLampApplet" width=400 height=400>
</applet>
*/
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) {}
}
53
43k
Output:
Explanation
54
43k
55
43k
DefaultTableModel model;
public EmployeeTableForm() {
super("Employee Details");
// Table setup
String[] columns = {"Employee No", "Employee Name", "Salary"};
model = new DefaultTableModel(columns, 0);
table = new JTable(model);
JScrollPane sp = new JScrollPane(table);
// 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
// Constructor
MultiplicationTableAWT() {
57
43k
58
43k
// Add window closing event so program stops when user clicks "X"
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);
}
});
}
try {
// Read number entered in text field
int n = [Link]([Link]());
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
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.
g. Event Registration
[Link](this);
• Links the button to this class, so when button is clicked →
actionPerformed() runs.
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.
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.
62
43k
import [Link].*;
import [Link].*;
EmployeeDetails() {
// Set title for the first frame
setTitle("Employee Entry Form");
setLayout(null); // manual positioning
63
43k
// Frame settings
setSize(380, 320);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
[Link](d1);
[Link](d2);
[Link](d3);
64
43k
[Link](350, 250);
[Link](true);
}
// main method
public static void main(String args[]) {
new EmployeeDetails();
}
}
/*
<applet code="[Link]" width="400" height="400">
</applet>
*/
65
43k
// Right Eye
// x=220, y=160 → position of right eye
// width=25, height=25 → size of eye
[Link](220, 160, 25, 25);
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].*;
66
43k
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
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];
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) {}
}
}
[Link](ballColor);
[Link](x, y, radius, radius); // Draw ball
}
}
70
43k
Ans:
import [Link].*;
import [Link].*;
public CompoundInterestExact() {
setTitle("Compound Interest Calculator");
setLayout(null);
t1 = new JTextField();
[Link](180, 30, 120, 25);
add(t1);
t2 = new JTextField();
[Link](180, 70, 120, 25);
add(t2);
t3 = new JTextField();
[Link](180, 110, 120, 25);
add(t3);
t4 = new JTextField();
[Link](180, 150, 120, 25);
add(t4);
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
Q55 . Write a java program to design following Frame using Swing. [25
M].
Ans:
import [Link].*;
import [Link].*;
import [Link].*;
73
43k
MenuBarDemo() {
setTitle("Menu Bar Example");
setLayout(null);
setSize(500, 350);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Menus
fileMenu = new JMenu("File");
[Link]([Link]);
editMenu = new JMenu("Edit");
[Link]([Link]);
searchMenu = new JMenu("Search");
[Link]([Link]);
74
43k
[Link](cutItem);
[Link](copyItem);
[Link](pasteItem);
[Link](findItem);
setVisible(true);
}
75
43k
Ans:
import [Link].*;
import [Link].*;
public PersonalInfoExact() {
setTitle("Personal Information");
setLayout(null);
76
43k
t1 = new JTextField();
[Link](140, 30, 150, 25);
add(t1);
t2 = new JTextField();
[Link](140, 65, 150, 25);
add(t2);
t3 = new JTextField();
[Link](140, 100, 150, 25);
add(t3);
t4 = new JTextField();
[Link](140, 135, 150, 25);
add(t4);
77
43k
bg = new ButtonGroup();
[Link](male);
[Link](female);
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);
}
78
43k
if ([Link]() == b2) {
[Link]("");
[Link]("");
[Link]("");
[Link]("");
[Link]();
[Link](false);
[Link](false);
[Link](false);
} else if ([Link]() == b1) {
[Link](this, "Submitted Successfully!");
}
}
Ans:
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="[Link]" width=320 height=440>
</applet>
*/
79
43k
80
43k
81
43k
82
43k
return;
}
break;
}
[Link]([Link](result)); // show result
startNew = true;
} catch (Exception ex) {
[Link]("Error");
}
return;
}
83