Selvaraghav Java
Selvaraghav Java
Ex no: 01
PROGRAM USING IO STREAMS AND THREADS
Date:
1.1 QUESTION
Write a Java program to copy the contents from one file (input.txt) to another file (output.txt).
AIM
To write a Java program to copy the contents from one file (input.txt) to another file (output.txt).
CODE:
package Module1;
import java.io.*;
OUTPUT:
Input.txt
717822S147 - SELVARAGAVAN C 1
21SE04-ADVANCED JAVA PROGRAMMING
Output.txt
RESULT:
Thus, Copying the contents from one file to another file was executed successfully and the Output was
verified.
1.2 QUESTION
Write a Java program that removes all the occurrences of a specified string from a text file (words.txt).
For example, if the given string is “John” then the program should remove all the occurrences of the
sword “John” from the file.
AIM
To write a Java program that removes all the occurrences of a specified string from a text file.
CODE:
package Module1;
import java.io.*;
import java.util.Scanner;
717822S147 - SELVARAGAVAN C 2
21SE04-ADVANCED JAVA PROGRAMMING
return;
}
String updatedContent = content.toString().replaceAll(searchString, "");
try (PrintWriter writer = new PrintWriter(new FileWriter(filename))) {
writer.print(updatedContent);
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
}
System.out.println("Occurrences of \"" + searchString + "\" removed from the file.");
}
}
OUTPUT:
RESULT:
Thus, removing all the occurrences of a string from a text file was executed successfully and the output
was verified.
1.3 QUESTION
Write a Java program that will count the number of characters, words, and lines in a file (input.txt).
Words are separated by whitespace characters. The program should display the output in the following
format:
The file ‘input.txt’ has
1920 characters
250 words
70 lines
Aim:
To write a Java program that will count the number of characters, words, and lines in a file
CODE:
package Module1;
import java.io.*;
public class FileStats {
public static void main(String[] args) {
System.out.println("717822S154 SRIMOULIDHARAN");
String filename = "input.txt";
int charCount = 0;
int wordCount = 0;
int lineCount = 0;
717822S147 - SELVARAGAVAN C 3
21SE04-ADVANCED JAVA PROGRAMMING
OUTPUT:
Input file.txt
RESULT:
Thus, counting the number of characters, words, and lines in a file was executed successfully and the
output was verified
1.4 QUESTION
717822S147 - SELVARAGAVAN C 4
21SE04-ADVANCED JAVA PROGRAMMING
Write a Java program that displays the file’s name, containing folder, size, and time of last
modification. Save the file as FileStatistics.java.
Aim:
To write a Java program that displays the file’s name, containing folder, size, and time of last modification.
CODE:
package Module1;
import java.io.File;
import java.text.SimpleDateFormat;
if (!file.exists()) {
System.out.println("File not found: " + filename);
return;
}
OUTPUT:
RESULT:
Thus , displaying the file’s name, containing folder, size, and time of last modification was executed
successfully and the output was verified
717822S147 - SELVARAGAVAN C 5
21SE04-ADVANCED JAVA PROGRAMMING
1.5 QUESTION
Suppose that a text file (scores.txt) contains an unspecified number of scores separated by blanks.
Write a Java program that prompts the user to enter the file, reads the scores from the file, and displays their
total and average.
AIM:
To write a java program that reads the scores from the file, and displays their total and average.
CODE:
package Module1;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
717822S147 - SELVARAGAVAN C 6
21SE04-ADVANCED JAVA PROGRAMMING
OUTPUT:
RESULT:
Thus, reading the scores from the file, and displays their total and average was executed successfully
and the output was verified.
1.6 QUESTION
Write a Java program that prompts the user to enter a file name and displays the occurrences of each
letter in the file. Letters are case- insensitive.
AIM:
To Write a Java program that prompts the user to enter a file name and displays the occurrences of each
letter in the file
CODE:
package Module1;
import java.io.*;
import java.util.*;
public class LetterOccurrences {
public static void main(String[] args) {
System.out.println("717822S154 SRIMOULIDHARAN");
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a filename: ");
String filename = scanner.nextLine();
File file = new File(filename);
try {
Scanner fileScanner = new Scanner(file);
Map<Character, Integer> letterCount = new HashMap<>();
for (char ch = 'A'; ch <= 'Z'; ch++) {
letterCount.put(ch, 0);
}
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
line = line.toUpperCase();
for (char ch : line.toCharArray()) {
if (Character.isLetter(ch)) {
letterCount.put(ch, letterCount.get(ch) + 1);
}
}
}
for (char ch = 'A'; ch <= 'Z'; ch++) {
int count = letterCount.get(ch);
System.out.println("Number of " + ch + "'s: " + count);
}
717822S147 - SELVARAGAVAN C 7
21SE04-ADVANCED JAVA PROGRAMMING
fileScanner.close();
} catch (FileNotFoundException e) {
System.out.println("File not found: " + filename);
} finally {
scanner.close();
}
}
}
OUTPUT:
Letter.txt
RESULT:
Thus, displaying the occurrences of each letter in the file was executed successfully and the output
was verified.
717822S147 - SELVARAGAVAN C 8
21SE04-ADVANCED JAVA PROGRAMMING
1.7 QUESTION
Using a text editor, create a file (account.txt) that contains a list of at least 10 six-digit account
numbers. Read in each account number and display whether it is valid. An account number is valid
only if the last digit is equal to the sum of the first five digits divided by 10.
For example,
the number 223355 is valid because the sum of the first five digits is 15, the remainder when 15 is
divided by 10 is 5, and the last digit is 5.
Write only valid account numbers to an output file (valid.txt).
AIM
To write a java program to read account number and display whether it is valid or not
CODE:
package Module1;
import java.io.*;
import java.util.Scanner;
public class AccountValidation {
public static void main(String[] args) throws NumberFormatException, IOException {
System.out.println("717822S154 SRIMOULIDHARAN M");
try {
FileInputStream ff = new FileInputStream("account.txt");
Scanner sc = new Scanner(ff);
int input = 0;
int number;
int last;
int sum = 0;
while (sc.hasNext()) {
input += sc.nextInt();}
System.out.println(input);
number = input;
last = number % 10;
number = number / 10;
while (number > 0) {
sum += number % 10;
number = number / 10;
}
//System.out.println(sum);
//System.out.println(last);
if ((sum % 10) == last) {
System.out.println("Valid");
}
else
System.out.println("InValid");
} catch (FileNotFoundException fe) {
fe.printStackTrace();
}
}
}
717822S147 - SELVARAGAVAN C 9
21SE04-ADVANCED JAVA PROGRAMMING
OUTPUT:
RESULT:
Thus, writing a java program to read account number and display whether it is valid or not was
executed successfully and the output was verified
1.8 QUESTION
a.) The Rochester Bank maintains customer records in a random- access file (records.txt). Write a
Java program that creates 10,000 blank records and then allows the user to enter customer account
information, including an account number that is 9999 or less, a last name, and a balance. Insert each
new record into a data file at a location that is equal to the account number. Save the file as
CreateBankFile.java.
Constraints:
• The account number should range from 1 to 9999.
• The customer’s name must be exactly 8 characters.
Assumptions:
• The user will not enter invalid account numbers.
• The user will not enter a bank balance greater than Rs. 99,000.00.
b) Write a Java program that uses the file ‘records.txt’ and displays all existing accounts in account-
number order. Save the file as ReadBankAccountsSequentially.java.
c) Write a Java program that uses the file ‘records.txt’ and allows the user to enter an account
number to view the account balance. Save the file as ReadBankAccountsRandomly.java.
AIM:
To write a java program to enter customer account information ,display the accounts in account number
order and allows user to enter an account number to view the account balance.
CODE:
package Module1;
import java.nio.file.*;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;
import java.text.*;
public class CreateBankFile {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
717822S147 - SELVARAGAVAN C 1
0
21SE04-ADVANCED JAVA PROGRAMMING
try {
fc = (FileChannel) Files.newByteChannel(file, CREATE, WRITE);
System.out.print("Enter account number or " + QUIT + " >> ");
acctString = input.nextLine();
while (!(acctString.equals(QUIT))) {
acct = Integer.parseInt(acctString);
System.out.print("Account holder name for account #" + acctString + " >> ");
name = input.nextLine();
StringBuilder sb = new StringBuilder(name);
sb.setLength(NAME_LENGTH);
name = sb.toString();
System.out.print("Balance of account #" + acctString + " >> ");
balance = input.nextDouble();
input.nextLine();
DecimalFormat df = new DecimalFormat(BALANCE_FORMAT);
String s = acctString + delimiter + name + delimiter + df.format(balance) +
System.getProperty("line.separator");
data = s.getBytes();
buffer = ByteBuffer.wrap(data);
fc.position(acct * RECORD_SIZE);
fc.write(buffer);
input.close();
}
717822S147 - SELVARAGAVAN C 1
1
21SE04-ADVANCED JAVA PROGRAMMING
writer.close();
} catch (Exception e) {
System.out.println("Error message: " + e);
}
}
}
OUTPUT:
(B)
package Module1;
import java.nio.file.*;
import java.io.*;
import static java.nio.file.StandardOpenOption.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Scanner;
public class ReadBankAccountsSequentially {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userInput;
Path filename = Paths.get("AccountRecords.txt");
Path file = filename.toAbsolutePath();
final String QUIT = "QUIT";
final String ACCOUNT_NUMBER_FORMAT = "0000";
final String NAME_FORMAT = " ";
final int NAME_LENGTH = NAME_FORMAT.length();
final String BALANCE_FORMAT = "00000.00";
final String delimiter = ",";
String defaultRecord = ACCOUNT_NUMBER_FORMAT + delimiter + NAME_FORMAT +
delimiter + BALANCE_FORMAT + System.getProperty("line.separator");
final int RECORD_SIZE = defaultRecord.length();
String acctString;
717822S147 - SELVARAGAVAN C 1
2
21SE04-ADVANCED JAVA PROGRAMMING
int acct;
byte[] data = defaultRecord.getBytes();
String s;
System.out.print("Enter the number of the account to view >> ");
userInput = input.nextLine();
try {
FileChannel fc = (FileChannel) Files.newByteChannel(file, READ);
while (!(userInput.equals(QUIT))) {
ByteBuffer buffer = ByteBuffer.wrap(data);
acct = Integer.parseInt(userInput);
fc.position(acct * RECORD_SIZE);
fc.read(buffer);
s = new String(data);
prettyPrint(s.split(delimiter));
System.out.print("Enter the number of the account to view or " + QUIT + " >> ");
userInput = input.nextLine();
}
fc.close();
} catch (Exception e) {
System.out.println("Error message: " + e);
}
input.close();}
public static void prettyPrint(String[] c) {
StringBuilder sb = new StringBuilder();
for (String s : c)
sb.append(s + " ");
System.out.println(sb.toString());
}
}
OUTPUT:
(C)Package Module1;
import java.nio.file.*;
import java.io.*;
import static java.nio.file.StandardOpenOption.*;
public class ReadBankAccountsSequentially{
public static void main(String[] args){
Path filename = Paths.get("AccountRecords.txt");
Path file = filename.toAbsolutePath();
final String delimiter = ",";
try{
InputStream inputFile = new BufferedInputStream(Files.newInputStream(file));
717822S147 - SELVARAGAVAN C 1
3
21SE04-ADVANCED JAVA PROGRAMMING
OUTPUT:
RESULT:
Thus, to enter customer account information ,display the accounts in account number order and allows user
to enter an account number to view the account balance was executed successfully and the output was
verified.
1.9 QUESTION
a.) Create a Java class named Circle that implements Serializable interface and has fields named radius,
diameter, and area. Include a constructor that sets the radius to 1 and calculates the other two values.
Also include methods named set Radius() and get Radius(). The set Radius() method not only sets the
radius, it also calculates the other two values. Include a to String() method also. Save the class as
Circle.java.
b)Write a Java program that creates three Circle objects and serializes them in a file (circle.dat).
c) Write a Java program to de-serialize the three Circle objects from circle.dat file and displays the data.
AIM:
To write a java program to create a java class Circle and implement Serialization and deserialization
CODE:
package Module1;
import java.io.Serializable;
@SuppressWarnings("serial")
public class Circle implements Serializable {
int radius;
int diameter;
double area;
717822S147 - SELVARAGAVAN C 1
4
21SE04-ADVANCED JAVA PROGRAMMING
public Circle() {
this.radius = 1;
}
@Override
public String toString() {
return "Circle [radius=" + this.radius + ", diameter=" + this.diameter + ", area=" + this.area +
"]";
}
}
package Module1;
import java.io.*;
import java.util.Date;
// serialization
FileOutputStream fos = new FileOutputStream("circle.dat");
717822S147 - SELVARAGAVAN C 1
5
21SE04-ADVANCED JAVA PROGRAMMING
System.out.println((Circle)ois.readObject());
System.out.println(ois.readObject());
System.out.println(ois.readObject());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
OUTPUT:
RESULT:
Thus , creating a java class Circle and implement Serialization and deserialization was executed
successfully and the output was verified
1.10 QUESTION
a.) Write a Java program for the following UML class diagram: [The employee class must implement
Serializable interface.]
b) Write a Java program that creates three Employee objects and serializes them in a file (employee.dat).
717822S147 - SELVARAGAVAN C 1
6
21SE04-ADVANCED JAVA PROGRAMMING
c) Write a Java program to de-serialize the three Employee objects from employee.dat file and displays the
data.
AIM:
To write a java program to create a java class Employee and implement Serialization and
deserialization by creating an object
CODE:
package Module1;
import java.io.*;
class Employee implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String firstName;
private String lastName;
private int salary;
public Employee(int id, String firstName, String lastName, int salary) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.salary = salary;
}
public int getID() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getName() {
return firstName + " " + lastName;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public int getAnnualSalary() {
return salary * 12;
}
public int raiseSalary(int percent) {
salary += (salary * percent) / 100;
return salary;
}
@Override
public String toString() {
return "Employee[id=" + id + ", name=" + getName() + ", salary=" + salary + "]";
}
}
717822S147 - SELVARAGAVAN C 1
7
21SE04-ADVANCED JAVA PROGRAMMING
package Module1;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Main {
public static void main(String[] args) {
// Create three Employee objects
Employee employee1 = new Employee(1, "John", "Doe", 50000);
Employee employee2 = new Employee(2, "Jane", "Smith", 60000);
Employee employee3 = new Employee(3, "Alice", "Johnson", 70000);
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("employee.dat")))
{
oos.writeObject(employee1);
oos.writeObject(employee2);
oos.writeObject(employee3);
System.out.println("Objects serialized successfully.");
} catch (IOException e) {
e.printStackTrace();
} try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("employee.dat"))) {
Employee emp1 = (Employee) ois.readObject();
Employee emp2 = (Employee) ois.readObject();
Employee emp3 = (Employee) ois.readObject();
// Display data
System.out.println("Employee 1: " + emp1.toString());
System.out.println("Employee 2: " + emp2.toString());
System.out.println("Employee 3: " + emp3.toString());
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
OUTPUT:
RESULT:
Thus creating a java class Employee and implement Serialization and deserialization was executed
successfully and the Output was verified
717822S147 - SELVARAGAVAN C 1
8
21SE04-ADVANCED JAVA PROGRAMMING
1.11 QUESTION
Write a Java program that creates two threads T1 and T2 by extending Thread class. T1 asks the user to
enter an integer and displays a statement that indicates whether the integer is even or odd. T2 asks the user
to enter three integers and displays them in ascending and descending order.
AIM:
To write a java code to create two thread and ask to enter an integer from user to perform Odd or Even
and ascending and descending order
CODE:
package Module1;
import java.util.Scanner;
public class Thread1 extends Thread {
public void run() {
Scanner scn = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scn.nextInt();
if (num % 2 == 0) {
System.out.println(num + " is an Even number");
} else {
System.out.println(num + " is an Odd number") }
}
}
package Module1;
import java.util.Arrays;
import java.util.Scanner;
public class Thread2 extends Thread {
public void run() {
Scanner scn = new Scanner(System.in);
int[] arr = new int[3];
System.out.println("Enter three numbers:");
for (int i = 0; i < 3; i++) {
arr[i] = scn.nextInt();
}
Arrays.sort(arr);
System.out.println("Ascending order:");
for (int i = 0; i < 3; i++) {
System.out.println(arr[i]);
}
System.out.println("Descending order:");
for (int i = 2; i >= 0; i--) {
System.out.println(arr[i]);
}
}
}
package Module1;
public class ThreadDemo {
public static void main(String[] args) {
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
t1.start();
t2.start();
}}
717822S147 - SELVARAGAVAN C 1
9
21SE04-ADVANCED JAVA PROGRAMMING
OUTPUT:
RESULT:
Thus, creating two thread and perform Odd or Even and ascending and descending order
was executed successfully and the output was verified.
717822S147 - SELVARAGAVAN C 2
0
21SE04-ADVANCED JAVA PROGRAMMING
Ex no: 2
PROGRAM USING MULTITHREADING
Date:
2.1 QUESTION
Write a Java program that creates 100 threads by implementing Runnable interface. Each thread adds 1 to a
variable ‘sum’ that is initially 0. Display the value of sum after each increment.
AIM
To write a java code to create thread and perform increment the Sum of each thread
PROGRAM/SOURCE CODE:
package Module1;
public class IncrementThread implements Runnable {
private static int sum = 0;
@Override
public void run() {
synchronized (IncrementThread.class) {
sum++;
System.out.println("Sum after increment: " + sum);
}
}
public static void main(String[] args) {
OUTPUT:
RESULT:
Thus , creating thread and perform increment the Sum of each thread was executed successfully and the
output was verified
717822S147 - SELVARAGAVAN C 2
1
21SE04-ADVANCED JAVA PROGRAMMING
2.2 QUESTION
Write a Java program that creates three threads to count the words in three files address.txt,
Homework.java and report.txt. and displays them in the following format:
address.txt: 1052
Homework.java: 445
report.txt: 2099
AIM
To write a java code to create thread and count the words in a file
CODE:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class CountThread {
public static void main(String[] args) {
WordCountThread thread1 = new WordCountThread("address.txt");
WordCountThread thread2 = new WordCountThread("Homework.java");
WordCountThread thread3 = new WordCountThread("report.txt");
thread1.start();
thread2.start();
thread3.start();
try {
thread1.join();
thread2.join();
thread3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class WordCountThread extends Thread {
private String filename;
public WordCountThread(String filename) {
this.filename = filename;
}
@Override
public void run() {
int wordCount = countWords(filename);
System.out.println(filename + ": " + wordCount);
}
717822S147 - SELVARAGAVAN C 2
2
21SE04-ADVANCED JAVA PROGRAMMING
}
}
OUTPUT:
RESULT:
Thus creating thread and count the words in a file was executed Successfully and the output was
verified
2.3 QUESTION
Write a Java program in which multiple threads add and remove elements from a LinkedList.
AIM:
To write a Java program in which multiple threads add and remove elements from a LinkedList.
CODE:
package Module1;
import java.util.LinkedList;
public LinkedListManager() {
linkedList = new LinkedList<>();
}
717822S147 - SELVARAGAVAN C 2
3
21SE04-ADVANCED JAVA PROGRAMMING
package Module1;
@Override
public void run() {
manager.addElement(elementToAdd);
}
}
package Module1;
@Override
public void run() {
manager.removeElement();
}
}
package Module1;
717822S147 - SELVARAGAVAN C 2
4
21SE04-ADVANCED JAVA PROGRAMMING
OUTPUT:
RESULT:
Thus , multiple threads adding and removing elements from a LinkedList was executed successfully and
the output was verified.
2.4 QUESTION
Consider a banking scenario in which a customer wishes to withdraw or deposit an amount from his/her
account. Write a Java program which ensures that only one person is able to perform withdraw or deposit on
a bank account at a time. Illustrate the above scenario using the synchronization concept in Java.
AIM:
To write a code to perform withdraw or deposit on a bank account at a time using Synchronization.
CODE:
package Module1;
import java.util.Scanner;
public class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
public synchronized void deposit(double amount) {
System.out.println("Depositing Rs." + amount);
balance += amount;
System.out.println("Deposit completed. New balance: Rs." + balance);
}
public synchronized void withdraw(double amount) {
if (balance >= amount) {
System.out.println("Withdrawing Rs." + amount);
balance -= amount;
717822S147 - SELVARAGAVAN C 2
5
21SE04-ADVANCED JAVA PROGRAMMING
import java.util.Scanner;
OUTPUT:
717822S147 - SELVARAGAVAN C 2
6
21SE04-ADVANCED JAVA PROGRAMMING
RESULT:
Thus to perform withdraw or deposit on a bank account at a time using synchronization was executed
successfully and the output was verified
2.5 QUESTION
Write a program for Inter Thread Communication process. Create three classes’ Consumer, Producer and
Stock.
• Stock class which contains synchronized getStock() and putStock() methods.
• Producer class invokes addStock() method.
• Consumer class invokes getStock() method
• Create a Main class that starts Producer and Consumer Threads.
AIM
To write a program to perform Inter Thread Communication processes by creating Classes
PROGRAM/SOURCE CODE:
package Module1;
class Stock {
private int stock = 0;
private final int capacity = 5;
public synchronized void putStock(int amount) {
while (stock + amount > capacity) {
try {
System.out.println("Producer waiting as stock is full...");
wait(); // Wait for space to become available
} catch (InterruptedException e) {
e.printStackTrace();
}
}
stock += amount;
System.out.println("Produced " + amount + " items. Current stock: " + stock);
notifyAll(); // Notify waiting consumers that new items are available
}
public synchronized void getStock(int amount) {
while (stock < amount) {
try {
System.out.println("Consumer waiting as stock is empty...");
wait(); // Wait for items to become available
} catch (InterruptedException e) {
e.printStackTrace();
}
}
stock -= amount;
System.out.println("Consumed " + amount + " items. Current stock: " + stock);
notifyAll(); // Notify waiting producers that space is available
}
717822S147 - SELVARAGAVAN C 2
7
21SE04-ADVANCED JAVA PROGRAMMING
@Override
public void run() {
for (int i = 0; i < 5; i++) {
stock.putStock(1); // Produce 1 item
try {
sleep(1000); // Simulate some processing time
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
stock.getStock(1); // Consume 1 item
try {
sleep(1000); // Simulate some processing time
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
717822S147 - SELVARAGAVAN C 2
8
21SE04-ADVANCED JAVA PROGRAMMING
OUTPUT:
RESULT:
Thus to perform Inter Thread Communication processes by creating class was executed
successfully and the output was verified.
EX NO 3
QUESTION
Consider the following “Nobel Prize” database table:
Name Year Subject
Develop a Java program to connect with database and retrieve following details:
• Write a Java code to insert records by reading input from the user.
• Display all the details which are stored in the Nobel Prize table.
• Display the details of the Nobel Prize winners who got for the subject Peace.
• Delete the NobelPrize winners who got NobelPrize before 1930.
AIM
To develop a Java program to connect with database and retrieve following details
CODE
package Module2;
import java.sql.*;
import java.util.Scanner;
public class NobelPrizeDatabase {
public static void main(String[] args) {
try {
System.out.println("717822s154 Srimoulidharan M");
String url = "jdbc:mysql://localhost:3306/jdbcexercise";
String username = "root";
String password = "977327341426";
Connection connection = DriverManager.getConnection(url, username, password);
717822S147 - SELVARAGAVAN C 3
0
21SE04-ADVANCED JAVA PROGRAMMING
while (peaceResultSet.next()) {
System.out.println(peaceResultSet.getString("Name") + " (" +
peaceResultSet.getInt("Year") + ")");
}
ResultSet resultSetBeforeDeletion = statement.executeQuery(selectAllQuery);
System.out.println("\nNobel Prize winners before deletion:");
while (resultSetBeforeDeletion.next()) {
System.out.println(resultSetBeforeDeletion.getString("Name") + " (" +
resultSetBeforeDeletion.getInt("Year") + ") - " +
resultSetBeforeDeletion.getString("Subject"));
}
String deleteQuery = "DELETE FROM NobelPrize WHERE Year < 1930";
int deletedRows = statement.executeUpdate(deleteQuery);
System.out.println("Number of rows deleted: " + deletedRows);
OUTPUT
717822S147 - SELVARAGAVAN C 3
1
21SE04-ADVANCED JAVA PROGRAMMING
RESULT:
Thus, developing a Java program to connect with database and retrieve following details was
executed Successfully and the output was verified.
EX NO 4
QUESTION
Given the following table containing information about employees of an organization, develop a small
java application, using JDBC, which displays a menu for the user consisting of following options:
(Use Prepared Statement for Executing Queries)
1. Add Record
2. Modify Record
3. Delete Record
717822S147 - SELVARAGAVAN C 3
2
21SE04-ADVANCED JAVA PROGRAMMING
Add Record :
When the user input is 1, the user should be asked to enter the following details one by one (again
using Scanner).
Employee ID
Employee’s First Name
Employee’s last Name
Join Date
Department
Designation
Basic Salary
The data entered by the user should be stored in database table
Modify Record:
If the user selects option 2, Modify Record, the user should be asked to enter the employee no.
whose data he needs to modify. When the user enters the employee no., the application should
display the employee’s details like employee no., designation, department and basic salary. If the
employee no. is not present, it should display appropriate error message. The user should be able to
change only the Designation and Basic Salary.
Delete Record:
When the user selects option 3, Delete Record, the application should ask him to enter the employee
no. and if the employee no. does not exist, it should display appropriate error message. If the
employee no. exists, the record should be deleted. Display One Record
When the user selects option 4, Display One Record, the application should ask him to enter the
employee no. and if the employee no. does not exist, it should display appropriate error message. If
the employee no. exists, it should display all the details of this employee.
Display all Records
When the user selects option 5, Display all Records, the application should display all the records.
Exit
When the user wants to stop using this application, he will select option 6 and he should be allowed
to exit from this system. It should display a message on the system “Thank you for using this
application”
AIM
CODE
import java.sql.*;
import java.util.Scanner;
717822S147 - SELVARAGAVAN C 3
3
21SE04-ADVANCED JAVA PROGRAMMING
switch (choice) {
case 1:
addRecord(connection, scanner);
break;
case 2:
modifyRecord(connection, scanner);
break;
case 3:
deleteRecord(connection, scanner);
break;
case 4:
displayOneRecord(connection, scanner);
break;
case 5:
displayAllRecords(connection);
break;
case 6:
exit = true;
System.out.println("Thank you for using this application.");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
717822S147 - SELVARAGAVAN C 3
4
21SE04-ADVANCED JAVA PROGRAMMING
717822S147 - SELVARAGAVAN C 3
5
21SE04-ADVANCED JAVA PROGRAMMING
updateStatement.setDouble(2, newBasicSalary);
updateStatement.setString(3, empId);
int rowsAffected = updateStatement.executeUpdate();
if (rowsAffected > 0) {
System.out.println("Record updated successfully.");
} else {
System.out.println("Failed to update record.");
}
}
} else {
System.out.println("Employee not found.");
}
}
}
717822S147 - SELVARAGAVAN C 3
6
21SE04-ADVANCED JAVA PROGRAMMING
OUTPUT
717822S147 - SELVARAGAVAN C 3
7
21SE04-ADVANCED JAVA PROGRAMMING
RESULT:
Thus, developing a Java program to connect with database and retrieve following details was
executed Successfully and the output was verified.
EX NO 5
717822S147 - SELVARAGAVAN C 3
8
21SE04-ADVANCED JAVA PROGRAMMING
QUESTION
Develop a Java program to connect with database and retrieve following details:
1) Add a new book ‘HTML, CSS & JavaScript’ by Laura Lemay, Prentice Hall, Rs. 250.00 using
Prepared Statement.
2) Display all the details which are stored in Books table.
3) Create a Procedure to increase the price of books by Rs.200.
4) Create a Procedure to add new record into table.
5) Execute procedures using Callable Statement
AIM
To develop a Java program to connect with database and retrieve following details
CODE
import java.sql.*;
private static void addNewBook(Connection conn, String title, String author, String publication, double
price) throws SQLException {
String sql = "INSERT INTO books (title, author, publication, price) VALUES (?, ?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, title);
pstmt.setString(2, author);
717822S147 - SELVARAGAVAN C 3
9
21SE04-ADVANCED JAVA PROGRAMMING
pstmt.setString(3, publication);
pstmt.setDouble(4, price);
pstmt.executeUpdate();
}
717822S147 - SELVARAGAVAN C 4
0
21SE04-ADVANCED JAVA PROGRAMMING
RESULT:
Thus, developing a Java program to connect with database and retrieve following details was
executed Successfully and the output was verified.
EX NO 6 6.1
PROGRAMS USING JUNIT
DATE
QUESTION
The following method is written to find Nth Fibonacci number.
Note: Fibbonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, ….
public int nthFibonacci(int num) {
if (num == 1) {
return 0;
717822S147 - SELVARAGAVAN C 4
1
21SE04-ADVANCED JAVA PROGRAMMING
}
if (num == 2) {
return 1;
}
return nthFibonacci(num - 1) + nthFibonacci(num + 1);
}
Test the function using JUnit & check whether it is finding the Nth Fibonacci number. Try to fix
the logical errors if any.
AIM:
To write a java program to test the Junit for the given method
CODE
package Junit2;
public class Fibo {
public int nthFibonacci(int n) {
if (n <= 0)
throw new IllegalArgumentException("Input must be a positive integer.");
if (n == 1 || n == 2)
return n - 1;
int a = 0, b = 1, c = 0;
for (int i = 2; i < n; i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
}
package Junit2;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestFibo {
@Test
public void testNthFibonacci() {
Fibo fibonacci = new Fibo();
assertEquals(0, fibonacci.nthFibonacci(1));
assertEquals(1, fibonacci.nthFibonacci(2));
assertEquals(1, fibonacci.nthFibonacci(3));
assertEquals(2, fibonacci.nthFibonacci(4));
assertEquals(3, fibonacci.nthFibonacci(5)); }}
OUTPUT
717822S147 - SELVARAGAVAN C 4
2
21SE04-ADVANCED JAVA PROGRAMMING
RESULT:
Thus the Junit tested successfully and the output is verified
6.2 QUESTION
Create the following class and implement the method to check given string is a palindrome and return the
result
Class Name: MyUnit
Method: public boolean palindromeCheck(String input){
}
(Hint: If the reversed string is equal to the actual string is palindrome string. Ex: madam, mom, dad,
malayalam )
Create a Junit test class to test the above class.
AIM
To write a java program to test the Junit for the given method
CODE
package Junit2;
public class Myunit {
OUTPUT
RESULT:
717822S147 - SELVARAGAVAN C 4
3
21SE04-ADVANCED JAVA PROGRAMMING
6.3 QUESTION
Create the following class and implement the method to find number of digits in a given string
Class Name: MyUnit
Method: public int digitCount(String input){
}
Sample Input: Java2022
Sample output: 4
Create a Junit test class to test the above class.
AIM
To write a java program to test the Junit for the given method
CODE
package Junit2;
public class digit {
public int digitCount(String input) {
int count = 0;
for (char c : input.toCharArray()) {
if (Character.isDigit(c)) {
count++;
}
}
return count;
}
}
package Junit2;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class Testdigit {
@Test
public void testDigitCount() {
digit myUnit = new digit();
assertEquals(4, myUnit.digitCount("Java2022"));
assertEquals(0, myUnit.digitCount("Hello"));
assertEquals(6, myUnit.digitCount("123abc456def"));
}
}
OUTPUT
RESULT:
Thus the Junit tested successfully and the output is verified
717822S147 - SELVARAGAVAN C 4
4
21SE04-ADVANCED JAVA PROGRAMMING
6.4 QUESTION
Test the functions of Calculate class using JUnit. Print binary function is used to print the binary equivalent
of the given number. Note: Try to fix the logical errors in these functions.
Test all three functions using Parameterized Test mechanism.
public class Calculate {
public byte add(byte b1, byte b2) {
return (byte) (b1 + b2);
}
public short add(short b1, short b2) {
return (short) (b1 + b2);
}
public int[] printBinary(byte number) {
int[] result;
int size = 10;
if (number < 16)
result = new int[4];
else if (number < 32)
result = new int[5];
else if (number < 64)
result = new int[6];
else
result = new int[7];
int i = 0;
for (i = 0; number >= 1; i++) {
result[i] = number % 2;
i++;
number = (byte) (number / (byte) 2);
}
result[i] = number;
return result;
}
}
AIM
To write a java program to test the Junit for the given method
CODE
package Junit2;
public class Calculate {
public byte add(byte b1, byte b2) {
return (byte) (b1 + b2);
}
public short add(short b1, short b2) {
return (short) (b1 + b2);
}
public int[] printBinary(byte number) {
int size = 8;
if (number < 0)
number += 256;
int[] result = new int[size];
for (int i = size - 1; i >= 0; i--) {
717822S147 - SELVARAGAVAN C 4
5
21SE04-ADVANCED JAVA PROGRAMMING
result[i] = number % 2;
number /= 2;
} return result;
}
}
package Junit2;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.*;
@RunWith(Parameterized.class)
public class CalculateTest {
private Calculate calculate;
private Object input1;
private Object input2;
private Object expectedResult;
public CalculateTest(Object input1, Object input2, Object expectedResult) {
this.input1 = input1;
this.input2 = input2;
this.expectedResult = expectedResult;
calculate = new Calculate();
}
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ (byte) 5, (byte) 7, (byte) 12 },
{ (short) 10, (short) 20, (short) 30 }
});
}
@Test
public void testAdd() {
if (input1 instanceof Byte && input2 instanceof Byte) {
assertEquals(expectedResult, calculate.add((Byte) input1, (Byte) input2));
} else if (input1 instanceof Short && input2 instanceof Short) {
assertEquals(expectedResult, calculate.add((Short) input1, (Short) input2));
}
}
@Test
public void testPrintBinary() {
byte number = (byte) 10;
int[] expectedBinary = {0, 0, 0, 0, 1, 0, 1, 0};
assertArrayEquals(expectedBinary, calculate.printBinary(number));
}
}
OUTPUT
717822S147 - SELVARAGAVAN C 4
6
21SE04-ADVANCED JAVA PROGRAMMING
RESULT:
Thus the Junit tested successfully and the output is verified
6.5 QUESTION
Create a test suite class for the above exercises 2 & 3 and test the methods
AIM
To write a java program to test the Junit for the given method
CODE
package Junit2;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
TestMyUnit.class,
Testdigit.class
})
public class TestSuite {
}
OUTPUT
717822S147 - SELVARAGAVAN C 4
7
21SE04-ADVANCED JAVA PROGRAMMING
RESULT:
Thus the Junit tested successfully and the output is verified
717822S147 - SELVARAGAVAN C 4
8