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

Selvaraghav Java

The document discusses several Java programs related to file input/output (I/O) streams and threads. It provides the code and output for programs that copy a file, remove strings from a file, count elements in a file, display file details, read scores from a file, and count letter occurrences in a file.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Selvaraghav Java

The document discusses several Java programs related to file input/output (I/O) streams and threads. It provides the code and output for programs that copy a file, remove strings from a file, count elements in a file, display file details, read scores from a file, and count letter occurrences in a file.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

21SE04-ADVANCED JAVA PROGRAMMING

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.*;

public class FileCopy {


public static void main(String[] args) {
String inputFile = "input.txt";
String outputFile = "output.txt";
try {
FileInputStream fis = new FileInputStream(inputFile);
FileOutputStream fos = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
fis.close();
fos.close();
System.out.println("File copied successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

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;

public class RemoveStringFromFile {


public static void main(String[] args) {
System.out.println("717822S154 SRIMOULIDHARAN M");
String filename = "input1.txt";
String searchString = "John";
StringBuilder content = new StringBuilder();
try (Scanner scanner = new Scanner(new File(filename))) {
while (scanner.hasNextLine()) {
content.append(scanner.nextLine()).append(System.lineSeparator());
}
} catch (FileNotFoundException e) {
System.err.println("File not found: " + filename);

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

try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {


String line;
while ((line = reader.readLine()) != null) {
lineCount++;
charCount += line.length();
String[] words = line.split("\\s+"); // Split by whitespace
wordCount += words.length;
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
return;
}
System.out.println("The file '" + filename + "' has");
System.out.println(charCount + " characters");
System.out.println(wordCount + " words");
System.out.println(lineCount + " lines");
}
}

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;

public class FileStatistics {


public static void main(String[] args) {
System.out.println("717822S154 SRIMOULIDHARAN");
String filename = "input.txt";
File file = new File(filename);

if (!file.exists()) {
System.out.println("File not found: " + filename);
return;
}

System.out.println("File Name: " + file.getName());


System.out.println("Containing Folder: " + file.getParent());
System.out.println("Size: " + file.length() + " bytes");

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


System.out.println("Last Modified: " + sdf.format(file.lastModified()));
}
}

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;

public class ScoreStatistics {


public static void main(String[] args) {
System.out.println("717822S154 SRIMOULIDHARAN");
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the name of the file (e.g., scores.txt): ");
String filename = scanner.nextLine();
File file = new File(filename);
try {
Scanner fileScanner = new Scanner(file);
int total = 0;
int count = 0;
while (fileScanner.hasNext()) {
if (fileScanner.hasNextInt()) {
int score = fileScanner.nextInt();
total += score;
count++;
} else {
fileScanner.next(); // Read and discard non-integer tokens
}
}
if (count > 0) {
double average = (double) total / count;
System.out.println("Total: " + total);
System.out.println("Average: " + average);
} else {
System.out.println("No scores found in the file.");
}
fileScanner.close();
} catch (FileNotFoundException e) {
System.out.println("File not found: " + filename);
} finally {
scanner.close();
}
}
}

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);

Path filename = Paths.get("AccountRecords.txt");


Path file = filename.toAbsolutePath();

717822S147 - SELVARAGAVAN C 1
0
21SE04-ADVANCED JAVA PROGRAMMING

final int NUMBER_OF_RECORDS = 10000;


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();
FileChannel fc = null;
String acctString;
int acct;
String name;
double balance;
byte[] data;
ByteBuffer buffer;
final String QUIT = "QUIT";

createEmptyFile(file, defaultRecord, NUMBER_OF_RECORDS);

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);

System.out.print("\nEnter account number or " + QUIT + " >> ");


acctString = input.nextLine();
}
fc.close();
} catch (Exception e) {
System.out.println("Error message: " + e);
}

input.close();
}

717822S147 - SELVARAGAVAN C 1
1
21SE04-ADVANCED JAVA PROGRAMMING

public static void createEmptyFile(Path file, String s, int lines) {


try {
OutputStream outputStr = new BufferedOutputStream(Files.newOutputStream(file, CREATE));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStr));

for (int count = 0; count < lines; ++count)


writer.write(s, 0, s.length());

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

BufferedReader reader = new BufferedReader(new InputStreamReader(inputFile));


String s = reader.readLine();
while(s != null)
{
String[] array = s.split(delimiter);
if(!((array[1].trim()).isEmpty()))
System.out.println("Acct #" + array[0] + "\tAcct Holder: " + array[1]+ "\
tBalance: $" + array[2]);
s = reader.readLine();
}reader.close();
}
catch(Exception e){
System.out.println("Error message: " + e);
}
}
}

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;
}

public Circle(int radius) {


this.radius = radius;
}

public int getRadius() {


return radius;
}

public void setRadius(int radius) {


this.radius = radius;
}

public int getDiameter() {


this.diameter = this.radius * 2;
return this.diameter;
}

public double getArea() {


this.area = this.radius * this.radius * 3.14;
return this.area;
}

@Override
public String toString() {
return "Circle [radius=" + this.radius + ", diameter=" + this.diameter + ", area=" + this.area +
"]";
}

}
package Module1;

import java.io.*;
import java.util.Date;

public class SerializeCircle {


public static void main(String[] args) throws IOException {
try {
Circle c1 = new Circle();
Circle c2 = new Circle(7);
Circle c3 = new Circle(10);
c3.setRadius(23);
c1.getDiameter();
c1.getArea();
c2.getDiameter();
c2.getArea();
c3.getDiameter();
c3.getArea();

// serialization
FileOutputStream fos = new FileOutputStream("circle.dat");

717822S147 - SELVARAGAVAN C 1
5
21SE04-ADVANCED JAVA PROGRAMMING

ObjectOutputStream oos = new ObjectOutputStream(fos);


oos.writeObject(c1);
oos.writeObject(c2);
oos.writeObject(c3);
// De-serialization
FileInputStream fis = new FileInputStream("circle.dat");
ObjectInputStream ois = new ObjectInputStream(fis);

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) {

// Create 100 threads


for (int i = 0; i < 100; i++) {
Thread thread = new Thread(new IncrementThread());
thread.start();
}
}
}

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);
}

private int countWords(String filename) {


int count = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = reader.readLine()) != null) {
String[] words = line.split("\\s+");
count += words.length;
}
} catch (IOException e) {
e.printStackTrace();
}
return count;
}

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 class LinkedListManager {


private final LinkedList<Integer> linkedList;

public LinkedListManager() {
linkedList = new LinkedList<>();
}

public synchronized void addElement(int element) {


linkedList.add(element);
System.out.println("Added: " + element);
printList();
}

public synchronized void removeElement() {


if (!linkedList.isEmpty()) {
int removed = linkedList.removeFirst();
System.out.println("Removed: " + removed);
printList();
} else {
System.out.println("List is empty. Cannot remove.");
}
}

717822S147 - SELVARAGAVAN C 2
3
21SE04-ADVANCED JAVA PROGRAMMING

private synchronized void printList() {


System.out.print("List: ");
for (int element : linkedList) {
System.out.print(element + " ");
}
System.out.println();
}
}

package Module1;

public class AddThread extends Thread {


private final LinkedListManager manager;
private final int elementToAdd;

public AddThread(LinkedListManager manager, int elementToAdd) {


this.manager = manager;
this.elementToAdd = elementToAdd;
}

@Override
public void run() {
manager.addElement(elementToAdd);
}
}

package Module1;

public class RemoveThread extends Thread {


private final LinkedListManager manager;

public RemoveThread(LinkedListManager manager) {


this.manager = manager;
}

@Override
public void run() {
manager.removeElement();
}
}

package Module1;

public class Main2 {


public static void main(String[] args) {
System.out.println("717822s154 Srimoulidharan M");
LinkedListManager manager = new LinkedListManager();

// Create threads to add elements


for (int i = 0; i < 5; i++) {
AddThread addThread = new AddThread(manager, i);
addThread.start();
}

// Create threads to remove elements


for (int i = 0; i < 3; i++) {
RemoveThread removeThread = new RemoveThread(manager);
removeThread.start();
}
}

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

System.out.println("Withdrawal completed. New balance: Rs." + balance);


} else {
System.out.println("Insufficient funds for withdrawal.");
}
}
}
package Module1;
public class Customer extends Thread {
private BankAccount account;
private boolean isDeposit;
private double amount;
public Customer(BankAccount account, boolean isDeposit, double amount) {
this.account = account;
this.isDeposit = isDeposit;
this.amount = amount;
}
public void run() {
if (isDeposit) {
account.deposit(amount);
} else {
account.withdraw(amount);
}
}
}
package Module1;

import java.util.Scanner;

public class Main2 {


public static void main(String[] args) {
Scanner scanner = new Scanner(Sytem.in);
System.out.print("\nEnter initial balance: Rs.");
double initialBalance = scanner.nextDouble();
BankAccount account = new BankAccount(initialBalance);
System.out.print("Enter deposit amount: Rs.");
double depositAmount = scanner.nextDouble();
Customer customer1 = new Customer(account, true, depositAmount);
System.out.print("Enter withdrawal amount: Rs.");
double withdrawalAmount = scanner.nextDouble();
Customer customer2 = new Customer(account, false, withdrawalAmount);
scanner.close();
customer1.start();
customer2.start();
}
}

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

class Producer extends Thread {


private Stock stock;

public Producer(Stock stock) {


this.stock = stock;
}

@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();
}
}
}
}

class Consumer extends Thread {


private Stock stock;

public Consumer(Stock stock) {


this.stock = stock;
}

@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();
}
}
}
}

public class Main1 {


public static void main(String[] args) {
Stock stock = new Stock();
Producer producer = new Producer(stock);
Consumer consumer = new Consumer(stock);
producer.start();
consumer.start();
}
}

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

PROGRAMS USING JDBC CRUD OPERATIONS


DATE - SELVARAGAVAN C
717822S147 2
9
21SE04-ADVANCED JAVA PROGRAMMING

QUESTION
Consider the following “Nobel Prize” database table:
Name Year Subject

Rabindranath Tagore 1913 Literature

C. V. Raman 1930 Physics

Mother Teresa 1979 Peace

Amartya Sen 1998 Economic studies

Kailash Satyarthi 2014 Peace

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);

Statement statement = connection.createStatement();


String createTableQuery = "CREATE TABLE IF NOT EXISTS NobelPrize (" +
"Name VARCHAR(255), " +
"Year INT, " +
"Subject VARCHAR(255))";
statement.executeUpdate(createTableQuery);
String selectAllQuery = "SELECT * FROM NobelPrize";
ResultSet resultSet = statement.executeQuery(selectAllQuery);
System.out.println("\nAll Nobel Prize winners:");
while (resultSet.next()) {
System.out.println(resultSet.getString("Name") + " (" +
resultSet.getInt("Year") + ") - " +
resultSet.getString("Subject"));
}
String selectPeaceQuery = "SELECT * FROM NobelPrize WHERE Subject = 'Peace'";
ResultSet peaceResultSet = statement.executeQuery(selectPeaceQuery);
System.out.println("\nNobel Prize winners in Peace category:");

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);

ResultSet resultSetAfterDeletion = statement.executeQuery(selectAllQuery);


System.out.println("\nNobel Prize winners after deletion:");
while (resultSetAfterDeletion.next()) {
System.out.println(resultSetAfterDeletion.getString("Name") + " (" +
resultSetAfterDeletion.getInt("Year") + ") - " +
resultSetAfterDeletion.getString("Subject"));
}
resultSetBeforeDeletion.close();
resultSetAfterDeletion.close();
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

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

PROGRAMS USING PREPARED STATEMENT IN JDBC


DATE

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

4. Display one Record


5. Display All
6. Exit
Use Scanner class to accept input from the user.
Employee_table

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

To develop a Java program using Prepare Statement in JDBC

CODE

import java.sql.*;
import java.util.Scanner;

717822S147 - SELVARAGAVAN C 3
3
21SE04-ADVANCED JAVA PROGRAMMING

public class EmployeeManagementSystem {


private static final String DB_URL = "jdbc:mysql://localhost/EmployeeDB";
private static final String DB_USERNAME = "your_username";
private static final String DB_PASSWORD = "your_password";
public static void main(String[] args) {
try (Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME,
DB_PASSWORD)) {
Scanner scanner = new Scanner(System.in);
boolean exit = false;
while (!exit) {
System.out.println("Employee Management System Menu:");
System.out.println("1. Add Record");
System.out.println("2. Modify Record");
System.out.println("3. Delete Record");
System.out.println("4. Display One Record");
System.out.println("5. Display All Records");
System.out.println("6. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
scanner.nextLine(); // consume newline

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();
}
}

private static void addRecord(Connection connection, Scanner scanner) throws SQLException {


System.out.println("Enter Employee details:");
System.out.print("Employee ID: ");
String empId = scanner.nextLine();
System.out.print("Employee's First Name: ");

717822S147 - SELVARAGAVAN C 3
4
21SE04-ADVANCED JAVA PROGRAMMING

String firstName = scanner.nextLine();


System.out.print("Employee's Last Name: ");
String lastName = scanner.nextLine();
System.out.print("Join Date: ");
String joinDate = scanner.nextLine();
System.out.print("Department: ");
String department = scanner.nextLine();
System.out.print("Designation: ");
String designation = scanner.nextLine();
System.out.print("Basic Salary: ");
double basicSalary = scanner.nextDouble();

String sql = "INSERT INTO Employee_table VALUES (?, ?, ?, ?, ?, ?, ?)";


try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setString(1, empId);
preparedStatement.setString(2, firstName);
preparedStatement.setString(3, lastName);
preparedStatement.setString(4, joinDate);
preparedStatement.setString(5, department);
preparedStatement.setString(6, designation);
preparedStatement.setDouble(7, basicSalary);

int rowsAffected = preparedStatement.executeUpdate();


if (rowsAffected > 0) {
System.out.println("Record added successfully.");
} else {
System.out.println("Failed to add record.");
}
}
}

private static void modifyRecord(Connection connection, Scanner scanner) throws SQLException {


System.out.print("Enter Employee ID to modify: ");
String empId = scanner.nextLine();

String selectSql = "SELECT * FROM Employee_table WHERE Employee_ID=?";


try (PreparedStatement preparedStatement = connection.prepareStatement(selectSql)) {
preparedStatement.setString(1, empId);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
System.out.println("Employee Found. Current Details:");
System.out.println("Employee ID: " + resultSet.getString("Employee_ID"));
System.out.println("Designation: " + resultSet.getString("Designation"));
System.out.println("Department: " + resultSet.getString("Department"));
System.out.println("Basic Salary: " + resultSet.getDouble("Basic_Salary"));

System.out.print("Enter new Designation: ");


String newDesignation = scanner.nextLine();
System.out.print("Enter new Basic Salary: ");
double newBasicSalary = scanner.nextDouble();

String updateSql = "UPDATE Employee_table SET Designation=?, Basic_Salary=? WHERE


Employee_ID=?";
try (PreparedStatement updateStatement = connection.prepareStatement(updateSql)) {
updateStatement.setString(1, newDesignation);

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.");
}
}
}

private static void deleteRecord(Connection connection, Scanner scanner) throws SQLException {


System.out.print("Enter Employee ID to delete: ");
String empId = scanner.nextLine();

String deleteSql = "DELETE FROM Employee_table WHERE Employee_ID=?";


try (PreparedStatement preparedStatement = connection.prepareStatement(deleteSql)) {
preparedStatement.setString(1, empId);
int rowsAffected = preparedStatement.executeUpdate();
if (rowsAffected > 0) {
System.out.println("Record deleted successfully.");
} else {
System.out.println("Employee not found.");
}
}
}

private static void displayOneRecord(Connection connection, Scanner scanner) throws SQLException


{
System.out.print("Enter Employee ID: ");
String empId = scanner.nextLine();

String sql = "SELECT * FROM Employee_table WHERE Employee_ID=?";


try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setString(1, empId);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
System.out.println("Employee Details:");
System.out.println("Employee ID: " + resultSet.getString("Employee_ID"));
System.out.println("First Name: " + resultSet.getString("First_Name"));
System.out.println("Last Name: " + resultSet.getString("Last_Name"));
System.out.println("Join Date: " + resultSet.getString("Join_Date"));
System.out.println("Department: " + resultSet.getString("Department"));
System.out.println("Designation: " + resultSet.getString("Designation"));
System.out.println("Basic Salary: " + resultSet.getDouble("Basic_Salary"));
} else {
System.out.println("Employee not found.");
}
}
}

717822S147 - SELVARAGAVAN C 3
6
21SE04-ADVANCED JAVA PROGRAMMING

private static void displayAllRecords(Connection connection) throws SQLException {


String sql = "SELECT * FROM Employee_table";
try (Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql)) {
System.out.println("All Employee Records:");
while (resultSet.next()) {
System.out.println("Employee ID: " + resultSet.getString("Employee_ID"));
System.out.println("First Name: " + resultSet.getString("First_Name"));
System.out.println("Last Name: " + resultSet.getString("Last_Name"));
System.out.println("Join Date: " + resultSet.getString("Join_Date"));
System.out.println("Department: " + resultSet.getString("Department"));
System.out.println("Designation: " + resultSet.getString("Designation"));
System.out.println("Basic Salary: " + resultSet.getDouble("Basic_Salary"));
System.out.println();
}
}
}
}

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

PROGRAMS USING CALLABLE STATEMENT IN JDBC


DATE

717822S147 - SELVARAGAVAN C 3
8
21SE04-ADVANCED JAVA PROGRAMMING

QUESTION

Consider the following “Book” table:


Title Author Publication Price in Rs.

Java: The complete reference Herbert Schildt Prentice Hall 659.00

C Programming in Linux David Haskins John Wiley & Sons 788.00

HeadFirst java script Nickel Morison O’ Reilly 500.00

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.*;

public class BookDatabase {


private static final String URL = "jdbc:mysql://localhost:3306/bookstore";
private static final String USER = "root";
private static final String PASSWORD = "root";

public static void main(String[] args) {


try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
addNewBook(conn, "HTML, CSS & JavaScript", "Laura Lemay", "Prentice Hall", 250.00);
displayAllBooks(conn);
createPriceIncreaseProcedure(conn);
createAddNewRecordProcedure(conn);
executeProcedures(conn);
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}

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();
}

private static void displayAllBooks(Connection conn) throws SQLException {


Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM books");
System.out.println("Title\tAuthor\tPublication\tPrice");
while (rs.next()) {
System.out.println(rs.getString("title") + "\t" + rs.getString("author") + "\t" +
rs.getString("publication") + "\t" + rs.getDouble("price"));
}
}
private static void createPriceIncreaseProcedure(Connection conn) throws SQLException {
String sql = "CREATE PROCEDURE increasePrice() " +
"BEGIN " +
"UPDATE books SET price = price + 200; " +
"END";
Statement stmt = conn.createStatement();
stmt.executeUpdate(sql);
}
private static void createAddNewRecordProcedure(Connection conn) throws SQLException {
String sql = "CREATE PROCEDURE addNewRecord(IN title VARCHAR(255), IN author
VARCHAR(255), " +
"IN publication VARCHAR(255), IN price DOUBLE) " +
"BEGIN " +
"INSERT INTO books (title, author, publication, price) VALUES (title, author, publication,
price); " +
"END";
Statement stmt = conn.createStatement();
stmt.executeUpdate(sql);
}

private static void executeProcedures(Connection conn) throws SQLException {


CallableStatement cstmt1 = conn.prepareCall("{call increasePrice()}");
cstmt1.execute();
CallableStatement cstmt2 = conn.prepareCall("{call addNewRecord(?, ?, ?, ?)}");
cstmt2.setString(1, "New Book Title");
cstmt2.setString(2, "New Book Author");
cstmt2.setString(3, "New Book Publication");
cstmt2.setDouble(4, 300.00);
cstmt2.execute();
}
OUTPUT

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 {

public boolean palindromeCheck(String input) {


StringBuilder reversed = new StringBuilder();
for (int i = input.length() - 1; i >= 0; i--) {
reversed.append(input.charAt(i));
}
return input.equals(reversed.toString());
}
}
package Junit2;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
public class TestMyUnit {
@Test
public void testPalindromeCheck() {
Myunit myUnit = new Myunit();
assertTrue(myUnit.palindromeCheck("madam"));
assertTrue(myUnit.palindromeCheck("mom"));
assertTrue(myUnit.palindromeCheck("dad"));
assertTrue(myUnit.palindromeCheck("malayalam"));
assertFalse(myUnit.palindromeCheck("hello"));
assertFalse(myUnit.palindromeCheck("world"));
}
}

OUTPUT

RESULT:

717822S147 - SELVARAGAVAN C 4
3
21SE04-ADVANCED JAVA PROGRAMMING

Thus the Junit tested successfully and the output is verified

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

You might also like