0% found this document useful (0 votes)
14 views

J

The document contains multiple Java programming exercises, each demonstrating different concepts such as sorting numbers, finding and replacing strings, performing calculations, and using recursion. It also covers topics like drawing shapes with polymorphism, implementing multiple inheritance using interfaces, managing threads, and creating applets for audio playback and color selection. Additionally, it includes examples of reading employee data from a file and retrieving student data from a database.

Uploaded by

afmrah
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)
14 views

J

The document contains multiple Java programming exercises, each demonstrating different concepts such as sorting numbers, finding and replacing strings, performing calculations, and using recursion. It also covers topics like drawing shapes with polymorphism, implementing multiple inheritance using interfaces, managing threads, and creating applets for audio playback and color selection. Additionally, it includes examples of reading employee data from a file and retrieving student data from a database.

Uploaded by

afmrah
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
You are on page 1/ 23

Ex No: 1 Sorting Numbers

import java.io.*;
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(System.in));
System.out.println("Enter the number of values:");
n = Integer.parseInt(br.readLine());
if (n > 100 || n <= 0) {
System.out.println("Invalid input! Please enter a number between 1 and 100.");
return;
}
System.out.println("Enter the values:");
for (i = 0; i < n; i++) {
a[i] = Integer.parseInt(br.readLine());
}
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;
}
}
}
System.out.println("After sorting in descending order:");
for (i = 0; i < n; i++) {
System.out.println(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 java.io.*;
class Demo1 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter string 1:");
String str = br.readLine();
System.out.println("Enter the string to be searched:");
String search = br.readLine();
System.out.println("Enter the string to replace:");
String replace = br.readLine();
String result = "";
int i = str.indexOf(search);
if (i != -1) {
// Splitting and replacing the substring
result = str.substring(0, i) + replace + str.substring(i + search.length());
System.out.println("Resultant string after replacement:");
System.out.println(result);
} else {
System.out.println("\"" + 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 java.util.Scanner;
public class Calculator1 {
public static void main(String[] args) {
double num1, num2, ans = 0;
char op;
Scanner reader = new Scanner(System.in);
System.out.println("Enter two numbers:");
num1 = reader.nextDouble();
num2 = reader.nextDouble();
System.out.print("Enter an operator (+, -, *, /): ");
op = reader.next().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 {
System.out.println("Error: Division by zero is not allowed.");
return;
}
break;
default:
System.out.println("Error: Enter a correct operator.");
return;
}
System.out.println("The result is:");
System.out.println(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 java.io.*;
class Rectangle {
private double length;
private double breadth;
public Rectangle(double length, double breadth) {
this.length = length;
this.breadth = breadth;
}
public double calculateArea() {
return length * breadth;
}
public void displayArea() {
System.out.println("The area of the rectangle is: " + calculateArea());
}
public static void main(String[] args) {
Rectangle rect = new Rectangle(10.5, 5.5);
rect.displayArea();
}
}
Output
The area of the rectangle is: 57.75
Ex No: 5 Student’s Percentage and Grade
import java.io.*;
class StudentGrade {
public static void main(String[] args) {
if (args.length < 5) {
System.out.println("Please provide marks for 5 subjects.");
return;
}
double totalMarks = 0;
for (int i = 0; i < 5; i++) {
totalMarks += Double.parseDouble(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';
}
System.out.println("Total Marks: " + totalMarks);
System.out.println("Percentage: " + percentage + "%");
System.out.println("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 java.util.Scanner;
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(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
scanner.close();
if (num < 0) {
System.out.println("Factorial is not defined for negative numbers.");
} else {
System.out.println("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 javax.swing.*;
import java.awt.*;
import java.util.Scanner;
class ShapeDrawer extends JPanel {
private String shapeType;
public ShapeDrawer(String shapeType) {
this.shapeType = shapeType;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
switch (shapeType.toLowerCase()) {
case "circle":
g.fillOval(50, 50, 150, 150); // Draw Circle
break;
case "triangle":
int[] xPoints = {125, 50, 200};
int[] yPoints = {50, 200, 200};
g.fillPolygon(xPoints, yPoints, 3); // Draw Triangle
break;
case "square":
g.fillRect(50, 50, 150, 150); // Draw Square
break;
default:
g.drawString("Invalid Shape", 100, 100);
}
}
}
public class ChooseShapeConsole {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Choose a shape to draw:");
System.out.println("1. Circle");
System.out.println("2. Triangle");
System.out.println("3. Square");
System.out.print("Enter your choice (1-3): ");
int choice = scanner.nextInt();
String shape = "";
switch (choice) {
case 1:
shape = "circle";
break;
case 2:
shape = "triangle";
break;
case 3:
shape = "square";
break;
default:
System.out.println("Invalid choice! Exiting...");
System.exit(0);
}
JFrame frame = new JFrame("Drawing: " + shape);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.add(new ShapeDrawer(shape));
frame.setVisible(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() {
System.out.println("Working as a part-time employee.");
}
public void study() {
System.out.println("Studying for exams.");
}
}
public class MultipleInheritanceExample {
public static void main(String[] args) {
WorkingStudent ws = new WorkingStudent();
ws.work();
ws.study();
}
}
Output
Working as a part-time employee.
Studying for exams.
Ex No: 9 Packages
package mypackage;
class MyClass {
void displayMessage() {
System.out.println("Hello from MyClass inside mypackage!");
}
}
public class PackageExample {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.displayMessage();
}
}
Output
javac -d . PackageExample.java
java mypackage.PackageExample
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() {


System.out.println(getName() + " started with priority " + getPriority());
for (int i = 1; i <= 5; i++) {
System.out.println(getName() + " is executing step " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(getName() + " was interrupted.");
}
}
System.out.println(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);
t1.start();
t2.start();
t3.start();
}
}
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 java.applet.*;
import java.awt.*;
import java.awt.event.*;
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(), "audio1.wav");
clip2 = getAudioClip(getCodeBase(), "audio2.wav");
playButton = new Button("Play Audio");
stopButton = new Button("Stop Audio");
playButton.addActionListener(this);
stopButton.addActionListener(this);
add(playButton);
add(stopButton);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == playButton) {
thread1 = new Thread(() -> clip1.play());
thread2 = new Thread(() -> clip2.play());
thread1.start();
thread2.start();
}
else if (e.getSource() == stopButton) {
clip1.stop();
clip2.stop();
}
}
}

HTML Code
<html>
<body>
<applet code="AudioPlayerApplet.class" width="300" height="100"></applet>
</body>
</html>
Output
javac AudioPlayerApplet.java
appletviewer AudioPlayerApplet.html
Ex No: 12 The Applet Change the Colors According to the Selection
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
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");
redCheckBox.addItemListener(this);
greenCheckBox.addItemListener(this);
blueCheckBox.addItemListener(this);
panel = new JPanel();
panel.setPreferredSize(new Dimension(300, 200));
JPanel checkboxPanel = new JPanel();
checkboxPanel.add(redCheckBox);
checkboxPanel.add(greenCheckBox);
checkboxPanel.add(blueCheckBox);
add(checkboxPanel, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
setTitle("Color Selector");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
int red = redCheckBox.isSelected() ? 255 : 0;
int green = greenCheckBox.isSelected() ? 255 : 0;
int blue = blueCheckBox.isSelected() ? 255 : 0;
panel.setBackground(new Color(red, green, blue));
}
public static void main(String[] args) {
new ColorCheckboxApp();
}
}
Output
Ex No: 13 Retrieve Employee Data from A File
import java.io.*;
class EmployeeDataReader {
public static void main(String[] args) {
String fileName = "employees.txt";
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
System.out.println("Employee Details:");
System.out.println("---------------------------------------------------");
System.out.printf("%-5s %-15s %-20s %s\n", "ID", "Name", "Designation", "Salary");
System.out.println("---------------------------------------------------");
while ((line = br.readLine()) != null) {
String[] details = line.split(",");
if (details.length == 4) {
System.out.printf("%-5s %-15s %-20s $%s\n",
details[0], details[1], details[2], details[3]);
}
}
System.out.println("---------------------------------------------------");
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
}
}
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 java.sql.*;
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 {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
System.out.println("Student Details:");
System.out.println("------------------------------------------");
System.out.printf("%-5s %-10s %-10s %-5s\n", "ID", "Name", "Course", "Marks");
System.out.println("------------------------------------------");
while (rs.next()) {
int id = rs.getInt("ID");
String name = rs.getString("Name");
String course = rs.getString("Course");
int marks = rs.getInt("Marks");
System.out.printf("%-5d %-10s %-10s %-5d\n", id, name, course, marks);
}
System.out.println("------------------------------------------");
rs.close();
stmt.close();
con.close();
} catch (ClassNotFoundException e) {
System.out.println("JDBC Driver not found: " + e.getMessage());
} catch (SQLException e) {
System.out.println("Database error: " + e.getMessage());
}
}
}
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 java.io.*;
import java.util.Scanner;
public class FileHandlingExample {
public static void main(String[] args) {
String fileName = "example.txt";
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 (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred while creating the file.");
e.printStackTrace();
}
}
public static void writeFile(String fileName, String content) {
try (FileWriter writer = new FileWriter(fileName)) {
writer.write(content);
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();
}
}
public static void readFile(String fileName) {
try (Scanner reader = new Scanner(new File(fileName))) {
System.out.println("File content:");
while (reader.hasNextLine()) {
System.out.println(reader.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("An error occurred while reading the file.");
e.printStackTrace();
}
}
public static void appendToFile(String fileName, String content) {
try (FileWriter writer = new FileWriter(fileName, true)) {
writer.write(content);
System.out.println("Successfully appended to the file.");
} catch (IOException e) {
System.out.println("An error occurred while appending to the file.");
e.printStackTrace();
}
}
public static void deleteFile(String fileName) {
File file = new File(fileName);
if (file.delete()) {
System.out.println("Deleted the file: " + file.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}
Output
File created: example.txt
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: example.txt

You might also like