Ex No: 1 Sorting Numbers
import [Link].*;
class Sorting1 {
public static void main(String[] args) throws IOException {
int i, j, t, n;
int[] a = new int[100];
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter the number of values:");
n = [Link]([Link]());
if (n > 100 || n <= 0) {
[Link]("Invalid input! Please enter a number between 1 and 100.");
return;
}
[Link]("Enter the values:");
for (i = 0; i < n; i++) {
a[i] = [Link]([Link]());
}
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (a[i] < a[j]) { // Compare for descending order
t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
[Link]("After sorting in descending order:");
for (i = 0; i < n; i++) {
[Link](a[i]);
}
}
}
Output
Enter the number of values:
5
Enter the values:
12
5
20
8
15
After sorting in descending order:
20
15
12
8
5
Ex No: 2 Find and Replace
import [Link].*;
class Demo1 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter string 1:");
String str = [Link]();
[Link]("Enter the string to be searched:");
String search = [Link]();
[Link]("Enter the string to replace:");
String replace = [Link]();
String result = "";
int i = [Link](search);
if (i != -1) {
// Splitting and replacing the substring
result = [Link](0, i) + replace + [Link](i + [Link]());
[Link]("Resultant string after replacement:");
[Link](result);
} else {
[Link]("\"" + search + "\" is not in the given text: " + str);
}
}
}
Output
Enter string 1:
Hello World
Enter the string to be searched:
World
Enter the string to replace:
Hello
Resultant string after replacement:
Hello Hello
Ex No: 3 Calculator
import [Link];
public class Calculator1 {
public static void main(String[] args) {
double num1, num2, ans = 0;
char op;
Scanner reader = new Scanner([Link]);
[Link]("Enter two numbers:");
num1 = [Link]();
num2 = [Link]();
[Link]("Enter an operator (+, -, *, /): ");
op = [Link]().charAt(0);
switch (op) {
case '+':
ans = num1 + num2;
break;
case '-':
ans = num1 - num2;
break;
case '*':
ans = num1 * num2;
break;
case '/':
if (num2 != 0) {
ans = num1 / num2;
} else {
[Link]("Error: Division by zero is not allowed.");
return;
}
break;
default:
[Link]("Error: Enter a correct operator.");
return;
}
[Link]("The result is:");
[Link](num1 + " " + op + " " + num2 + " = " + ans);
}
}
Output
Enter two numbers:
10
5
Enter an operator (+, -, *, /): +
The result is:
10.0 + 5.0 = 15.0
Ex No: 4 Area of Rectangle
import [Link].*;
class Rectangle {
private double length;
private double breadth;
public Rectangle(double length, double breadth) {
[Link] = length;
[Link] = breadth;
}
public double calculateArea() {
return length * breadth;
}
public void displayArea() {
[Link]("The area of the rectangle is: " + calculateArea());
}
public static void main(String[] args) {
Rectangle rect = new Rectangle(10.5, 5.5);
[Link]();
}
}
Output
The area of the rectangle is: 57.75
Ex No: 5 Student’s Percentage and Grade
import [Link].*;
class StudentGrade {
public static void main(String[] args) {
if ([Link] < 5) {
[Link]("Please provide marks for 5 subjects.");
return;
}
double totalMarks = 0;
for (int i = 0; i < 5; i++) {
totalMarks += [Link](args[i]);
}
double percentage = (totalMarks / 500) * 100;
char grade;
if (percentage >= 90) {
grade = 'A';
} else if (percentage >= 80) {
grade = 'B';
} else if (percentage >= 70) {
grade = 'C';
} else if (percentage >= 60) {
grade = 'D';
} else {
grade = 'F';
}
[Link]("Total Marks: " + totalMarks);
[Link]("Percentage: " + percentage + "%");
[Link]("Grade: " + grade);
}
}
Output
java StudentGrade 50 60 70 65 85
Total Marks: 330.0
Percentage: 66.0%
Grade: D
Ex No: 6 Factorial Using Recursion
import [Link];
public class FactorialRecursion {
public static long factorial(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n - 1);
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();
[Link]();
if (num < 0) {
[Link]("Factorial is not defined for negative numbers.");
} else {
[Link]("Factorial of " + num + " is: " + factorial(num));
}
}
}
Output
Enter a number: 5
Factorial of 5 is: 120
Ex No: 7 Draw Circle or Triangle or Square using Polymorphism and Inheritance
import [Link].*;
import [Link].*;
import [Link];
class ShapeDrawer extends JPanel {
private String shapeType;
public ShapeDrawer(String shapeType) {
[Link] = shapeType;
}
protected void paintComponent(Graphics g) {
[Link](g);
[Link]([Link]);
switch ([Link]()) {
case "circle":
[Link](50, 50, 150, 150); // Draw Circle
break;
case "triangle":
int[] xPoints = {125, 50, 200};
int[] yPoints = {50, 200, 200};
[Link](xPoints, yPoints, 3); // Draw Triangle
break;
case "square":
[Link](50, 50, 150, 150); // Draw Square
break;
default:
[Link]("Invalid Shape", 100, 100);
}
}
}
public class ChooseShapeConsole {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Choose a shape to draw:");
[Link]("1. Circle");
[Link]("2. Triangle");
[Link]("3. Square");
[Link]("Enter your choice (1-3): ");
int choice = [Link]();
String shape = "";
switch (choice) {
case 1:
shape = "circle";
break;
case 2:
shape = "triangle";
break;
case 3:
shape = "square";
break;
default:
[Link]("Invalid choice! Exiting...");
[Link](0);
}
JFrame frame = new JFrame("Drawing: " + shape);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](300, 300);
[Link](new ShapeDrawer(shape));
[Link](true);
}
}
Output
Choose a shape to draw:
1. Circle
2. Triangle
3. Square
Enter your choice (1-3): 1
Ex No: 8 Implement Multiple Inheritance Concepts in Java Using Interface
interface Employee {
void work();
}
interface Student {
void study();
}
class WorkingStudent implements Employee, Student {
public void work() {
[Link]("Working as a part-time employee.");
}
public void study() {
[Link]("Studying for exams.");
}
}
public class MultipleInheritanceExample {
public static void main(String[] args) {
WorkingStudent ws = new WorkingStudent();
[Link]();
[Link]();
}
}
Output
Working as a part-time employee.
Studying for exams.
Ex No: 9 Packages
package mypackage;
class MyClass {
void displayMessage() {
[Link]("Hello from MyClass inside mypackage!");
}
}
public class PackageExample {
public static void main(String[] args) {
MyClass obj = new MyClass();
[Link]();
}
}
Output
javac -d . [Link]
java [Link]
Hello from MyClass inside mypackage!
Ex No: 10 Create Threads and Assign Priorities
class MyThread extends Thread {
public MyThread(String name, int priority) {
super(name);
setPriority(priority);
}
public void run() {
[Link](getName() + " started with priority " + getPriority());
for (int i = 1; i <= 5; i++) {
[Link](getName() + " is executing step " + i);
try {
[Link](500);
} catch (InterruptedException e) {
[Link](getName() + " was interrupted.");
}
}
[Link](getName() + " finished execution.");
}
}
public class ThreadPriorityDemo {
public static void main(String[] args) {
MyThread t1 = new MyThread("Thread-1 (Low Priority)", Thread.MIN_PRIORITY);
MyThread t2 = new MyThread("Thread-2 (Medium Priority)", Thread.NORM_PRIORITY);
MyThread t3 = new MyThread("Thread-3 (High Priority)", Thread.MAX_PRIORITY);
[Link]();
[Link]();
[Link]();
}
}
Output
Thread-1 (Low Priority) started with priority 1
Thread-3 (High Priority) started with priority 10
Thread-3 (High Priority) is executing step 1
Thread-2 (Medium Priority) started with priority 5
Thread-2 (Medium Priority) is executing step 1
Thread-1 (Low Priority) is executing step 1
Thread-1 (Low Priority) is executing step 2
Thread-2 (Medium Priority) is executing step 2
Thread-3 (High Priority) is executing step 2
Thread-3 (High Priority) is executing step 3
Thread-1 (Low Priority) is executing step 3
Thread-2 (Medium Priority) is executing step 3
Thread-1 (Low Priority) is executing step 4
Thread-2 (Medium Priority) is executing step 4
Thread-3 (High Priority) is executing step 4
Thread-3 (High Priority) is executing step 5
Thread-1 (Low Priority) is executing step 5
Thread-2 (Medium Priority) is executing step 5
Thread-3 (High Priority) finished execution.
Thread-1 (Low Priority) finished execution.
Thread-2 (Medium Priority) finished execution.
Ex No: 11 Develop an Applet to Play Multiple Audio Clips Using Multithreading
import [Link].*;
import [Link].*;
import [Link].*;
public class AudioPlayerApplet extends Applet implements ActionListener {
private AudioClip clip1, clip2;
private Button playButton, stopButton;
private Thread thread1, thread2;
public void init() {
clip1 = getAudioClip(getCodeBase(), "[Link]");
clip2 = getAudioClip(getCodeBase(), "[Link]");
playButton = new Button("Play Audio");
stopButton = new Button("Stop Audio");
[Link](this);
[Link](this);
add(playButton);
add(stopButton);
}
public void actionPerformed(ActionEvent e) {
if ([Link]() == playButton) {
thread1 = new Thread(() -> [Link]());
thread2 = new Thread(() -> [Link]());
[Link]();
[Link]();
}
else if ([Link]() == stopButton) {
[Link]();
[Link]();
}
}
}
HTML Code
<html>
<body>
<applet code="[Link]" width="300" height="100"></applet>
</body>
</html>
Output
javac [Link]
appletviewer [Link]
Ex No: 12 The Applet Change the Colors According to the Selection
import [Link].*;
import [Link].*;
import [Link];
import [Link];
public class ColorCheckboxApp extends JFrame implements ItemListener {
JCheckBox redCheckBox, greenCheckBox, blueCheckBox;
JPanel panel;
public ColorCheckboxApp() {
redCheckBox = new JCheckBox("Red");
greenCheckBox = new JCheckBox("Green");
blueCheckBox = new JCheckBox("Blue");
[Link](this);
[Link](this);
[Link](this);
panel = new JPanel();
[Link](new Dimension(300, 200));
JPanel checkboxPanel = new JPanel();
[Link](redCheckBox);
[Link](greenCheckBox);
[Link](blueCheckBox);
add(checkboxPanel, [Link]);
add(panel, [Link]);
setTitle("Color Selector");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
int red = [Link]() ? 255 : 0;
int green = [Link]() ? 255 : 0;
int blue = [Link]() ? 255 : 0;
[Link](new Color(red, green, blue));
}
public static void main(String[] args) {
new ColorCheckboxApp();
}
}
Output
Ex No: 13 Retrieve Employee Data from A File
import [Link].*;
class EmployeeDataReader {
public static void main(String[] args) {
String fileName = "[Link]";
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
[Link]("Employee Details:");
[Link]("---------------------------------------------------");
[Link]("%-5s %-15s %-20s %s\n", "ID", "Name", "Designation", "Salary");
[Link]("---------------------------------------------------");
while ((line = [Link]()) != null) {
String[] details = [Link](",");
if ([Link] == 4) {
[Link]("%-5s %-15s %-20s $%s\n",
details[0], details[1], details[2], details[3]);
}
}
[Link]("---------------------------------------------------");
} catch (IOException e) {
[Link]("Error reading file: " + [Link]());
}
}
}
Text File
101,John Doe,Software Engineer,75000
102,Jane Smith,Project Manager,90000
103,Emily Davis,Data Analyst,68000
104,Michael Brown,HR Manager,72000
Output
-----------------------------------------------------------------------------
ID Name Designation Salary
-----------------------------------------------------------------------------
101 John Doe Software Engineer $75000
102 Jane Smith Project Manager $90000
103 Emily Davis Data Analyst $68000
104 Michael Brown HR Manager $72000
-----------------------------------------------------------------------------
Ex No: 14 Retrieve Student Data from a Database
Mysql Code
CREATE DATABASE SchoolDB;
USE SchoolDB;
CREATE TABLE Students (
ID INT PRIMARY KEY,
Name VARCHAR(50),
Course VARCHAR(50),
Marks INT
);
INSERT INTO Students VALUES
(1, 'Alice', 'Math', 85),
(2, 'Bob', 'Science', 90),
(3, 'Charlie', 'English', 88);
Java Program
import [Link].*;
public class RetrieveStudentData {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/SchoolDB";
String user = "root";
String password = "your_password";
String query = "SELECT * FROM Students";
try {
[Link]("[Link]");
Connection con = [Link](url, user, password);
Statement stmt = [Link]();
ResultSet rs = [Link](query);
[Link]("Student Details:");
[Link]("------------------------------------------");
[Link]("%-5s %-10s %-10s %-5s\n", "ID", "Name", "Course", "Marks");
[Link]("------------------------------------------");
while ([Link]()) {
int id = [Link]("ID");
String name = [Link]("Name");
String course = [Link]("Course");
int marks = [Link]("Marks");
[Link]("%-5d %-10s %-10s %-5d\n", id, name, course, marks);
}
[Link]("------------------------------------------");
[Link]();
[Link]();
[Link]();
} catch (ClassNotFoundException e) {
[Link]("JDBC Driver not found: " + [Link]());
} catch (SQLException e) {
[Link]("Database error: " + [Link]());
}
}
}
Output
Student Details:
------------------------------------------
ID Name Course Marks
------------------------------------------
1 Alice Math 85
2 Bob Science 90
3 Charlie English 88
------------------------------------------
Ex No: 15 Develop Applications Involving File Handling
import [Link].*;
import [Link];
public class FileHandlingExample {
public static void main(String[] args) {
String fileName = "[Link]";
createFile(fileName);
writeFile(fileName, "Hello, this is a Java File Handling Example!");
readFile(fileName);
appendToFile(fileName, "\nAppending some more text to the file.");
readFile(fileName);
deleteFile(fileName);
}
public static void createFile(String fileName) {
try {
File file = new File(fileName);
if ([Link]()) {
[Link]("File created: " + [Link]());
} else {
[Link]("File already exists.");
}
} catch (IOException e) {
[Link]("An error occurred while creating the file.");
[Link]();
}
}
public static void writeFile(String fileName, String content) {
try (FileWriter writer = new FileWriter(fileName)) {
[Link](content);
[Link]("Successfully wrote to the file.");
} catch (IOException e) {
[Link]("An error occurred while writing to the file.");
[Link]();
}
}
public static void readFile(String fileName) {
try (Scanner reader = new Scanner(new File(fileName))) {
[Link]("File content:");
while ([Link]()) {
[Link]([Link]());
}
} catch (FileNotFoundException e) {
[Link]("An error occurred while reading the file.");
[Link]();
}
}
public static void appendToFile(String fileName, String content) {
try (FileWriter writer = new FileWriter(fileName, true)) {
[Link](content);
[Link]("Successfully appended to the file.");
} catch (IOException e) {
[Link]("An error occurred while appending to the file.");
[Link]();
}
}
public static void deleteFile(String fileName) {
File file = new File(fileName);
if ([Link]()) {
[Link]("Deleted the file: " + [Link]());
} else {
[Link]("Failed to delete the file.");
}
}
}
Output
File created: [Link]
Successfully wrote to the file.
File content:
Hello, this is a Java File Handling Example!
Successfully appended to the file.
File content:
Hello, this is a Java File Handling Example!
Appending some more text to the file.
Deleted the file: [Link]