SUGUNA COLLEGE OF ARTS AND SCIENCE
(Affiliated to Bharathiar University)
Nehru Nagar, Kalapatti Road, Civil Aerodrome
Coimbatore-641014
BACHELOR OF COMPUTER APPLICATIONS
PROGRAMMING LAB - JAVA
[23P]
NAME :
REGISTER NO :
FIRST YEAR (SECOND SEMESTER)
(2025-2026)
SUGUNA COLLEGE OF ARTS AND SCIENCE
(Affiliated to Bharathiar University)
Nehru Nagar, Kalapatti Road, Civil Aerodrome
Coimbatore-641014
BACHELOR OF COMPUTER APPLICATIONS
This is to certify that a bonafide record of practical work on
"PROGRAMMING LAB – JAVA [23P]" done by Ms.
[REG. NO]: of Bachelor of Computer Applications in the
Computer Laboratory at Suguna College of Arts and Science, Coimbatore.
Staff-In charge Head of the Department
Submitted for the End Semester Practical Examinations held on in the
Department of Computer Science at Suguna College of Arts and Science, Coimbatore.
Internal Examiner External Examiner
CONTENT
[Link] DATE PARTICULARS PAGE NO
1 12/12/25 STRING EXTRACTION
2 19/12/25 MULTIPLE INHERITANCE USING
INTERFACE
3 5/1/26 AN EXCEPTION CREATION
4 10/1/26 MULTITHREADING
5 19/1/26 DRAW SEVERAL SHAPES USING JAVA
APPLET
6 23/1/26 TO CREATE FRAME USING AWT OR
SWING PACKAGES
7 STUDENT MANAGEMENT USING
27/1/26 USER DEFINED PACKAGES
8 31/1/26 CONTROL STATEMENTS
9 3/2/26 IMPLEMENT ABSTRACT CLASS AND
METHODS
10 9/2/26 MOUSE CLICK USING FRAMES
11 11/2/26 DRAW CIRCLE, SQUARE, ELIPSE
12 16/2/26 FILES
Ex. No :1
Date :12/12/25 STRING EXTRACTION
Aim:
To create a java application to extract a portion of a character string and print the
extracted string.
Algorithm:
Step 1: Start the Process.
Step 2: Declare the string and assign the value of the string.
Step 3: Assigning the starting and ending position.
Step 4: Creating the character array.
Step 5: Get the value from the string starting and ending position using getChars()
method.
Step 6: Print the extracted string.
Step 7: Stop the process.
Program:
import [Link]. *;
class P1
{
public static void main (String args[ ]) throws Exception
{
DataInputStream dis =new DataInputStream([Link]);
String S; int start, end;
[Link](“Enter the string:”);
S=[Link]();
[Link](“Enter the starting position:”);
start=[Link]([Link]());
[Link](“Enter the ending position:”);
end=[Link]([Link]());
char buf[] =new char[end-start];
[Link](start,end,buf,0);
[Link](“Extracted String is);
[Link](buf);
}
}
Output:
C:\jdk1.3\bin>javac [Link]
C:\jdk1.3\bin>java [Link]
Enter the string: Welcome to the java programming
Enter the starting position:0
Enter the ending position:9
Extracted string is Welcome to
Result:
Thus, the above program was successfully executed and verified.
Ex No: 2 MULTIPLE INHERITANCE USING INTERFACE
Date:19/12/25
Aim:
To create a java application to implement the concept of multiple inheritance using
interface.
Algorithm:
Step 1: Start the Process.
Step 2: Create class Student.
Step 3: Create class Test extends the class Student.
Step 4: Create interface Sports.
Step 5: Create class Result which extends class Test and implements interface Sports.
Step 6: Create object reference for Result class
Step 7: Pass roll number and marks as arguments.
Step 8: Display the student data
Step 9: Stop the process.
.
Program:
import [Link].*;
class Student
{
int rollnumber;
void getnumber(int n)
{
rollnumber =n; }
void putnumber( )
{
[Link]("Roll No:" +rollnumber);
}
}
class Test extends Student
{
float part1,part2;
void getmarks(float m1, float m2)
{ part1 =m1; part2 =m2;
}
void putmarks( )
{
[Link]("\t\t MARKS OBTAINED");
[Link]("\t\t ******************");
[Link]("\n");
[Link]("\t Mark 1 =" +part1);
[Link]("\n");
[Link]("\t Mark 2 =" +part2);
[Link]("\n");
}
}
interface Sports
{
float sportswt =7.0F;
void putwt( );
}
class Result extends Test implements Sports
{
float total;
public void putwt( )
{
[Link]("Sportswt =" +sportswt)
}
void display( )
{
total =part1+part2+sportswt;
putnumber( );
putmarks( );
putwt( );
[Link]("Total Score =" +total);
}
}
class P2
{
public static void main(String args[ ])
{
Result s1 =new Result( );
[Link](1234);
[Link](23.5F, 33.0F);
[Link]();
}
}
Output:
C:\jdk1.3\bin>javac [Link]
C:\jdk1.3\bin>java P2
Roll No:1234
MARKS OBTAINED
***************
Mark1=235
Mark2= 330
Sportswt=7.0
Total Score=63.5
Result :
Thus, the above program was successfully executed and verified.
.
Ex No:3
Date:5/1/26 AN EXCEPTION CREATION
Aim:
To create a java application for create an exception called payout –of –bounds and throw
the exception.
Algorithm:
Step 1: Start the Process.
Step 2: Create two class variables (i)name and (ii) basic pay
Step 3: Write a method display() to display the employee details
Step 4: Give values to class variables.
Step 5: check if the employee basic pay is less than or equal to 1000, then it throw
defined exception.
Step 6: Else calculate the employee salary and execute the methods display().
Step 7 : Stop the Process
Program:
import [Link].*;
// Custom Exception
class Pay extends Exception {
int basic;
Pay(int a) {
basic = a;
[Link]("\n\t\tBasic salary entered: " + basic);
[Link]("\t\tBasic salary is less than 1000, so payslip will not be displayed.");
}
}
// Employee class
class p3 {
String name;
int bp, hra, ma, pf, lic, gp, np;
p3(String n, int b) {
name = n;
bp = b;
}
void display() throws Pay {
if (bp <= 1000)
throw new Pay(bp);
[Link]("\n\t\tEMPLOYEE PAYSLIP");
[Link]("\t\t********************");
ma = bp * 5 / 100;
hra = bp * 10 / 100;
gp = bp + hra + ma;
pf = bp * 10 / 100;
lic = bp * 20 / 100;
np = gp - (pf + lic);
[Link]("\tNAME: " + name);
[Link]("\tBASIC SALARY: " + bp);
[Link]("\tMEDICAL ALLOWANCE: " + ma);
[Link]("\tHOUSE RENT ALLOWANCE: " + hra);
[Link]("\tGROSS PAY: " + gp);
[Link]("\tPROVIDENT FUND: " + pf);
[Link]("\tLIC: " + lic);
[Link]("\tNET AMOUNT: " + np);
}
public static void main(String arg[]) {
p3 x, y;
[Link]("\n\t\tCHECK PAY OUT OF BOUNDS EXCEPTION");
x = new p3("Shiva", 10000);
y = new p3("Shakthi", 900);
try {
[Link]();
[Link]();
} catch (Pay b) {
// Exception already handled in constructor
}
}
}
Output:
CHECK PAY OUT OF BOUNDS EXCEPTION
EMPLOYEE PAYSLIP
********************
NAME: Shiva
BASIC SALARY: 10000
MEDICAL ALLOWANCE: 500
HOUSE RENT ALLOWANCE: 1000
GROSS PAY: 11500
PROVIDENT FUND: 1000
LIC: 2000
NET AMOUNT: 8500
Basic salary entered: 900
Basic salary is less than 1000, so payslip will not be displayed.
Result:
Thus, the above program was successfully executed and verified.
Ex No: 4
Date:10/1/26 MULTITHREADING
Aim:
Implement the concept of multithreading with the use of any three multiplication tables
and assign three different priorities to them.
Algorithm:
Step 1: Start the Process.
Step 2: Create three threads by inheriting the Thread class
Step 3: Declare an integer variable to store the multiplication table number.
Step 4: Initialize the variable using a constructor.
Step5: Override the run() method.
Step 6 : Inside the run() method:
Display the thread name and its priority.
Use a loop from 1 to 10 to print the multiplication table.
Pause execution using [Link]() for clarity.
Step 7 :In the main() method:
Create three thread objects with different table numbers.
Assign different priorities to each thread (minimum, normal, maximum).
Step 8 : Start all three threads using the start() method.
Step 9 :Threads execute concurrently based on priority and CPU scheduling.
Step 10 :Stop the program.
Program:
import [Link].*;
class A extends Thread
{
public void run()
{
for (int i = 1; i <= 5; i++)
{
[Link](i + "*"+5+ "="+(i * 5));
}
[Link]("END OF THE 1st THREAD");
}
}
class B extends Thread
{
public void run()
{
for (int j = 1; j <= 7; j++)
{
[Link](j + "*" +7+ "=" +(j * 7));
}
[Link]("END OF THE 2st THREAD");
}
}
class C extends Thread
{
public void run()
{
for (int k = 1; k <= 13; k++)
{
[Link](k + "*" +13+ "=" +(k * 13));
}
[Link]("END OF THE 3st THREAD");
}
}
public class list4
{
public static void main(String args[])throws IOException
{
A ThreadA=new A();
B ThreadB=new B();
C ThreadC=new C();
[Link](Thread.MAX_PRIORITY);
[Link](Thread.NORM_PRIORITY);
[Link](Thread.MIN_PRIORITY);
[Link]();
[Link]();
[Link]();
}
}
Output:
D:\jdk1.8.0_111\bin>javac [Link]
D:\jdk1.8.0_111\bin>java list4
1*5=5
1*7=7
2*5=10
1*13=13
2*7=14
2*13=26
3*5=15
3*13=39
3*7=21
4*13=52
4*5=20
5*13=65
4*7=28
6*13=78
5*5=25
7*13=91
5*7=35
8*13=104
END OF THE 1st THREAD
9*13=117
6*7=42
7*7=49
END OF THE 2st THREAD
10*13=130
11*13=143
12*13=156
13*13=169
END OF THE 3st THREAD
Result:
Thus, the above program was successfully executed and verified.
Ex No: 5
Date:19/1/26 DRAW SEVERAL SHAPES USING JAVA APPLET
Aim:
To write a Java applet program to draw several shapes such as line, rectangle, oval,and
circle in the created applet window using the Graphics class.
Algorithm: Drawing Several Shapes Using Java Applet
1. Start
2. Import required packages [Link].* and [Link].*.
3. Create a class that extends the Applet class.
4. Override the paint(Graphics g) method.
5. Use Graphics class methods to draw different shapes such as line, rectangle,oval,
and circle.
[Link] different colors for each shape using the Color class.
7. Display all shapes in the applet window.
8. Stop
Program:
import [Link];
import [Link];
import [Link];
/*
<applet code="DrawShapesApplet" width="500"
height="400">
</applet>
*/
public class DrawShapesApplet extends Applet {
public void paint(Graphics g) {
// Draw a line
[Link]([Link]);
[Link](20, 20, 200, 20);
// Draw a rectangle
[Link]([Link]);
[Link](20, 50, 150, 80);
// Draw a filled rectangle
[Link]([Link]);
[Link](200, 50, 150, 80);
// Draw an oval
[Link]([Link]);
[Link](20, 160, 150, 80);
// Draw a filled oval (circle)
[Link]([Link]);
[Link](200, 160, 80, 80);
// Draw a rounded rectangle
[Link]([Link]);
[Link](20, 270, 150, 80, 30, 30);
}
Output:
Result:
Thus, the above program was successfully executed and verified.
Ex No:6
Date:23/1/26 TO CREATE FRAME USING AWT OR SWING PACKAGES
Aim:
To design and develop a Java application using Swing components
(JFrame, JTextField, JButton, and JLabel) that displays specific user details in text fields
upon a button click.
Algorithm:
Step1: Import Libraries: Include [Link].* for GUI component and [Link].* for
handling button clicks.
Step2: Initialize Components: Create a JFrame and define four JTextField objects for Name,
Street, City, and Pin Code.
Step3: Layout Management: Use a layout manager (e.g., GridLayout) to arrange labels and
text fields in a structured table-like format
.
Step4: Add Action Listener: Attach an ActionListener to the "My Details"
button.
Step5: Define Event Logic: Inside the action listener, use the setText() method to assign
specific strings to each text field
Step6: Display: Set the frame size, visibility, and default close operation
Program:
import [Link].*;
import [Link].*;
import [Link].*;
public class DetailsFrame extends JFrame implements ActionListener {
// Component declarations
JTextField txtName, txtStreet, txtCity, txtPin;
JButton btnDetails;
public DetailsFrame() {
// Frame Setup
setTitle(“User Address Form”);
setSize(400,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 2, 10, 10)); // 5 rows, 2 columns
// Initialize Text Fields
txtName = new JTextField();
txtStreet = new JTextField();
txtCity = new JTextField();
txtPin = new JTextField();
// Initialize Button
btnDetails = new JButton(“My Details”);
[Link](this);
// Adding components to the frame (Table-like structure)
add(new JLabel(“Name:”));
add(txtName);
add(new JLabel(“Street:));
add(txtStreet);
add(new JLabel(“City:”));
add(txtCity);
add(new JLabel(“Pin Code:”));
add(txtPin);
add(new JLabel(“Action:”));
add(btnDetails);
setVisible(true);
}
// Handle button click
@Override
public void actionPerformed(ActionEvent e) {
if ([Link]() == btnDetails) {
[Link](“John Doe”);
[Link](“123 Maple Avenue”);
[Link](“New York”);
[Link](“10001”);
}
}
public static void main(String[] args) {
new DetailsFrame();
}
}
Output:
Result:
Thus, the above program was successfully executed and verified.
EX NO:7 STUDENT MANAGEMENT USING USER
Date:27/1/26 DEFINED PACKAGES
Aim:
To develop a Student Management System using a user-defined package in Java to
add, display, and search student records.
Algorithm:
Step 1: Start the program.
Step 2: Create an ArrayList to store student records.
Step 3: Display the menu options (Add, Display, Search, Exit).
Step 4: Read the user’s choice.
Step 5: If the choice is Add, enter student details and store them in the list.
Step 6: If the choice is Display, show all stored student records.
Step 7: If the choice is Search, enter student ID and check if it exists in the list.
Step 8: If found, display the student details; otherwise, show "Student not
found".
Step 9: If the choice is Exit, stop the program.
Step 10: End the program
Java Student Management System using a user-defined package.
This example includes:
A user-defined package: studentmanagement
A Student class
A StudentManagement class (main program)
Basic operations: Add, Display, Search student
Program:
import [Link];
import [Link];
// Student class
class Student {
private int id;
private String name;
private String course;
private double marks;
// Constructor
public Student(int id, String name, String course, double marks) {
[Link] = id;
[Link] = name;
[Link] = course;
[Link] = marks;
}
// Getter
public int getId() {
return id;
}
// Display method
public void displayStudent() {
[Link]("ID: " + id);
[Link]("Name: " + name);
[Link]("Course: " + course);
[Link]("Marks: " + marks);
[Link]("--------------------------");
}
}
// Main class
public class Ex7 {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
Scanner sc = new Scanner([Link]);
int choice;
do {
[Link]("\n===== Student Management System =====");
[Link]("1. Add Student");
[Link]("2. Display All Students");
[Link]("3. Search Student by ID");
[Link]("4. Exit");
[Link]("Enter your choice: ");
choice = [Link]();
switch (choice) {
case 1:
[Link]("Enter ID: ");
int id = [Link]();
[Link]();
[Link]("Enter Name: ");
String name = [Link]();
[Link]("Enter Course: ");
String course = [Link]();
[Link]("Enter Marks: ");
double marks = [Link]();
Student s = new Student(id, name, course, marks);
[Link](s);
[Link]("Student Added Successfully!");
break;
case 2:
if ([Link]()) {
[Link]("No students available.");
} else {
for (Student st : students) {
[Link]();
}
}
break;
case 3:
[Link]("Enter ID to search: ");
int searchId = [Link]();
boolean found = false;
for (Student st : students) {
if ([Link]() == searchId) {
[Link]();
found = true;
break;
}
}
if (!found) {
[Link]("Student not found.");
}
break;
case 4:
[Link]("Exiting program...");
break;
default:
[Link]("Invalid choice!");
}
} while (choice != 4);
[Link]();
}
}
Output:
===== Student Management System =====
1. Add Student
2. Display All Students
3. Search Student by ID
4. Exit
Enter your choice: 1
Enter ID: 101
Enter Name: Sajith
Enter Course: BCA
Enter Marks: 95
Student Added Successfully!
Result:
Thus, the above program was successfully executed and verified.
Ex No:8
Date:31/1/26 CONTROL STATEMENTS
Program 1: To Find the Day of a Week
Aim:
To write a Java program using control statements to display the day of the
week based on a given number.
Algorithm:
1. Start the program.
2. Input a number (1–7).
3. Use switch statement to match the number.
4. Display the corresponding day.
5. If number is not between 1 and 7, display "Invalid input"
6. Stop the program.
Program:
import [Link];
public class Dayofweek
{
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
[Link]("enter a number(1-7):");
int day=[Link]();
switch (day)
{
case 1:
[Link]("sunday");
break;
case 2:
[Link]("monday");
break;
case 3:
[Link]("tuesday");
break;
case 4:
[Link]("wednesday");
break;
case 5:
[Link]("thursday");
break;
case 6:
[Link]("friday");
break;
case 7:
[Link]("saturday");
break;
default:
[Link]("invalid input");
}
[Link]();
}
}
Output:
Program 2: To Check Armstrong Number
Aim:
To write a Java program using control statements to check whether a given number is
an Armstrong number or not.
Algorithm:
1. Start the program.
2. Input a number.
3. Store the number in a temporary variable.
Initialize sum = 0.
While number > 0:
Find remainder (number % 10).
Add cube of remainder to sum.
Divide number by 10.
Compare sum with original number.
If equal → Armstrong number.
Else → Not Armstrong number.
Stop the program.
import [Link];
public class ArmstrongNumber
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link](“Enter a number:”);
int num = [Link]();
int original = num;
int sum = 0;
int remainder;
while(num>0)
{
remainder = num % 10;
sum += remainder * remainder * remainder;
num /= 10;
}
if(sum == original)
[Link](original +”is an Armstrong number.”);
else
[Link](original +”is not an Armstrong number.”);
[Link]();
}
}
Output:
Result:
Thus, the above program was successfully executed and verified.
Ex No:9
Date:3/2/26 IMPLEMENT ABSTRACT CLASS AND METHODS
Aim:
To write a Java program to implement an abstract class and abstract method for
student management, demonstrating abstraction in Java
Algorithm:
[Link] the program.
[Link] an abstract class StudentAbstract with:
Abstract method display()
Abstract method calculateGrade()
[Link] a subclass Student that extends StudentAbstract and implements the abstract
methods.
Input student details: ID, Name, Marks.
Implement display() to show student details.
Implement calculateGrade() to compute the grade based on marks.
Create an object of the subclass.
Call display() and calculateGrade() methods.
End the program
Programs:
import [Link];
// Abstract Class
abstract class StudentAbstract {
int id;
String name;
double marks;
// Constructor
StudentAbstract(int id, String name, double marks) {
[Link] = id;
[Link] = name;
[Link] = marks;
}
// Abstract methods
abstract void display();
abstract void calculateGrade();
}
// Subclass implementing abstract methods
class Student extends StudentAbstract {
Student(int id, String name, double marks) {
super(id, name, marks);
}
// Implement display method
void display() {
[Link](“\n Student ID:”+ id);
[Link](“Student Name:”+ name);
[Link](“Marks:”+ marks);
}
// Implement calculateGrade method
void calculateGrade() {
String grade;
if (marks>= 85)
grade = “Excellent”;
else if (marks >= 70)
grade = “Good”;
else if (marks >= 50)
grade =”Average”;
else
grade = “Poor”;
[Link](“Grade:”+ grade);
}
}
// Main Class
public class AbstractDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link](“Enter Student ID: “);
int id = [Link]();
[Link](); // consume newline
[Link](“Enter Student Name:”);
String name = [Link]();
[Link](“Enter Marks:”);
double marks = [Link]();
// Create Student object
Student s = new Student(id, name, marks);
// Call methods
[Link]();
[Link]();
[Link]();
Output:
Result:
Thus, the above program was successfully executed and verified.
Ex:No:10
Date:9/2/26 MOUSE CLICK USING FRAMES
Program: Mouse Events in Java
Aim:
To create a Java program using AWT that responds to mouse events on a frame,
and displays corresponding messages for each mouse action.
Algorithm:
Start the program.
Import the necessary packages: [Link].* for GUI components and
[Link].* for handling mouse events.
Create a class that extends Frame (or JFrame) and implements the MouseListener
interface.
Declare a Label (or JLabel) to display messages.
Create a constructor for the class:
Initialize the frame size and layout.
Add the label to the frame
.
Register the frame as a mouse listener using addMouseListener(this).
Make the frame visible.
Override the MouseListener methods:
mouseClicked(MouseEvent me) – display “Mouse Clicked” message.
mousePressed(MouseEvent me) – display “Mouse Pressed” message.
mouseReleased(MouseEvent me) – display “Mouse Released” message.
mouseEntered(MouseEvent me) – display “Mouse Entered” message.
mouseExited(MouseEvent me) – display “Mouse Exited” message.
Write the main method to create an object of the class.
End the program.
Program:
import [Link].*;
import [Link].*;
public class MouseEventDemo extends Frame implements MouseListener
{
Label label; // Label to display messages
// Constructor
public MouseEventDemo() {
// Create a label
label = new Label("Click or move your mouse inside the frame",
[Link]);
add(label);
// Set frame layout and size
setSize(400, 300);
setLayout(new BorderLayout());
// Add MouseListener to the frame
addMouseListener(this);
// Make frame visible
setVisible(true);
// Handle closing the window
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
[Link](0);
}
});
}
// MouseListener methods
public void mouseClicked(MouseEvent me) {
[Link]("Mouse Clicked at (" + [Link]() + ", " +
[Link]() + ")");
}
public void mousePressed(MouseEvent me) {
[Link]("Mouse Pressed at (" + [Link]() + ", " +
[Link]() + ")");
}
public void mouseReleased(MouseEvent me) {
[Link]("Mouse Released at (" + [Link]() + ",
" + [Link]() + ")");
}
public void mouseEntered(MouseEvent me) {
[Link]("Mouse Entered the Frame");
}
public void mouseExited(MouseEvent me) {
[Link]("Mouse Exited the Frame");
// Main method
public static void main(String[] args) {
new MouseEventDemo();
}
}
Output:
Click or move your mouse inside the frame
Mouse Entered the Frame
Mouse Clicked at (120,150)
Mouse Pressed at (120,150)
Mouse Released at (120,150)
Mouse Exited the Frame
Result:
Thus, the above program was successfully executed and verified.
Ex no:11 DRAW CIRCLE, SQUARE, ELIPSE
Date:11/2/26
Aim :
To create a Java program that draws different shapes (circle, square, ellipse, and
rectangle) at the positions where the mouse is clicked on the frame.
Algorithm :
1. Start the program.
2. Import necessary packages: [Link].* and [Link].*.
3. Create a class that extends Frame and implements MouseListener
4. Declare variables to store the mouse click coordinates (x and y) and the shape
to draw.
5. Create a constructor:
Set the frame size and layout.
6. Register the frame as a MouseListener.
Make the frame visible.
Add a WindowListener to handle closing the frame.
7. Implement mouseClicked(MouseEvent e):
Store the mouse click coordinates.
Randomly select a shape to draw (circle, square, ellipse, rectangle)
Call repaint() to update the frame.
8. Override paint(Graphics g):
Use the Graphics object to draw the selected shape at the mouse click position.
9. Implement other MouseListener methods as empty (if not used).
10. Write the main method to create the frame object.
11. End the program.
Program :
import [Link].*;
import [Link].*;
import [Link];
public class DrawShapesOnClick extends Frame implements MouseListener
{
int x = -50, y = -50; // Initial coordinates
String shape = ""; // Shape to draw
Random rand = new Random();
// Constructor
public DrawShapesOnClick() {
setTitle("Draw Shapes on Mouse Click");
setSize(600, 400);
setLayout(null);
addMouseListener(this);
setVisible(true);
// Handle closing the window
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
[Link](0);
}
});
}
// MouseListener method
public void mouseClicked(MouseEvent me) {
x = [Link]();
y = [Link]();
// Randomly select a shape
int choice = [Link](4);
switch (choice) {
case 0: shape = "Circle"; break;
case 1: shape = "Square"; break;
case 2: shape = "Ellipse"; break;
case 3: shape = "Rectangle"; break;
}
repaint(); // Call paint method
}
public void paint(Graphics g) {
[Link]([Link]);
switch (shape) {
case "Circle":
[Link](x - 25, y - 25, 50, 50); // Circle with radius 25
break;
case "Square":
[Link](x - 25, y - 25, 50, 50); // Square with side 50
break;
case "Ellipse":
[Link](x - 40, y - 20, 80, 40); // Ellipse
break;
case "Rectangle":
[Link](x - 40, y - 20, 80, 40); // Rectangle
break;
}
}
// Other MouseListener methods (not used)
public void mousePressed(MouseEvent me) {}
public void mouseReleased(MouseEvent me) {}
public void mouseEntered(MouseEvent me) {}
public void mouseExited(MouseEvent me) {}
// Main method
public static void main(String[] args) {
new DrawShapesOnClick();
}
}
Output:
Result:
Thus, the above program was successfully executed and verified.
EX NO:12
Date:16/2/26 FILES
Aim:
To write a Java program that opens an existing file and appends text to it
without overwriting the existing content .
Algorithm:
1. Start the program.
2. Import necessary packages: [Link].* and [Link].
3. Create a class for the program.
4. Inside the main method:
5. Create a File object for the existing file.
6. Create a FileWriter object in append mode (FileWriter(file,
true)).
7. Wrap FileWriter with BufferedWriter for efficient writing.
8. Use a Scanner to take text input from the user.
9. Write the input text to the file using [Link]().
[Link] the BufferedWriter and FileWriter.
[Link] a message indicating that text has been appended successfully.
[Link] the program.
Program:
import [Link].*;
import [Link];
public class AppendToFile {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the file name (with path if needed): ");
String fileName = [Link]();
[Link]("Enter text to append to the file: ");
String textToAppend = [Link]();
try {
// Open the file in append mode
FileWriter fw = new FileWriter(fileName, true); // true = append mode
BufferedWriter bw = new BufferedWriter(fw);
// Write the text to the file
[Link](textToAppend);
[Link](); // Move to next line
// Close the writers
[Link]();
[Link]();
[Link]("Text appended successfully to the file.");
} catch (IOException e) {
[Link]("An error occurred: " + [Link]());
}
[Link]();
}
}
Output:
Result:
Thus, the above program was successfully executed and verified.
Aim:
To create a Java program that draws different shapes (circle, square, ellipse, and rectangle)
at the positions where the mouse is clicked on the frame.
Algorithm:
.
1. Start the program.
2. Import necessary packages: [Link].* and [Link].*.
3. Create a class that extends Frame and implements MouseListener.
4. Declare variables to store the mouse click coordinates (x and y) and the shape to draw.
5. Create a constructor:
o Set the frame size and layout.
6. Register the frame as a MouseListener.
o Make the frame visible.
o Add a WindowListener to handle closing the frame.
7. Implement mouseClicked(MouseEvent e):
o Store the mouse click coordinates.
o Randomly select a shape to draw (circle, square, ellipse, rectangle).
o Call repaint() to update the frame.
8. Override paint(Graphics g):
o Use the Graphics object to draw the selected shape at the mouse click position.
9. Implement other MouseListener methods as empty (if not used).
10. Write the main method to create the frame object.
11. End the program.
Program:
import [Link].*;
import [Link].*;
import [Link];
public class DrawShapesOnClick extends Frame implements MouseListener
{
int x = -50, y = -50; // Initial coordinates
String shape = ""; // Shape to draw
Random rand = new Random();
// Constructor
public DrawShapesOnClick() {
setTitle("Draw Shapes on Mouse Click");
setSize(600, 400);
setLayout(null);
addMouseListener(this);
setVisible(true);
// Handle closing the window
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
[Link](0);
}
});
}
// MouseListener method
public void mouseClicked(MouseEvent me) {
x = [Link]();
y = [Link]();
// Randomly select a shape
int choice = [Link](4);
switch (choice) {
case 0: shape = "Circle"; break;
case 1: shape = "Square"; break;
case 2: shape = "Ellipse"; break;
case 3: shape = "Rectangle"; break;
}
repaint(); // Call paint method
}
public void paint(Graphics g) {
[Link]([Link]);
switch (shape) {
case "Circle":
[Link](x - 25, y - 25, 50, 50); // Circle with radius 25
break;
case "Square":
[Link](x - 25, y - 25, 50, 50); // Square with side 50
break;
case "Ellipse":
[Link](x - 40, y - 20, 80, 40); // Ellipse
break;
case "Rectangle":
[Link](x - 40, y - 20, 80, 40); // Rectangle
break;
}
}
// Other MouseListener methods (not used)
public void mousePressed(MouseEvent me) {}
public void mouseReleased(MouseEvent me) {}
public void mouseEntered(MouseEvent me) {}
public void mouseExited(MouseEvent me) {}
// Main method
public static void main(String[] args) {
new DrawShapesOnClick();
}
}
Output:
Result:
Thus, the above program was successfully executed and verified.
Ex No: 12
Date:
Aim:
To write a Java program that opens an existing file and appends text to it without overwriting
the existing content.
Algorithm:
1. Start the program.
2. Import necessary packages: [Link].* and [Link].
3. Create a class for the program.
4. Inside the main method:
o Create a File object for the existing file.
o Create a FileWriter object in append mode (FileWriter(file, true)).
o Wrap FileWriter with BufferedWriter for efficient writing.
o Use a Scanner to take text input from the user.
o Write the input text to the file using [Link]().
o Close the BufferedWriter and FileWriter.
5. Display a message indicating that text has been appended successfully.
6. End the program.
Program:
import [Link].*;
import [Link];
public class AppendToFile
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter the file name (with path if needed): ");
String fileName = [Link]();
[Link]("Enter text to append to the file: ");
String textToAppend = [Link]();
try
{
// Open the file in append mode
FileWriter fw = new FileWriter(fileName, true); // true = append mode
BufferedWriter bw = new BufferedWriter(fw);
// Write the text to the file
[Link](textToAppend);
[Link](); // Move to next line
// Close the writers
[Link]();
[Link]();
[Link]("Text appended successfully to the file.");
}
catch (IOException e)
{
[Link]("An error occurred: " + [Link]());
}
[Link]();
}
}
Output:
Result:
Thus, the above program was successfully executed and verified.