Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views92 pages

Java Record.81

The document is a JAVA Lab Record for II/IV B.Tech students, detailing a series of 27 experiments conducted during the academic year 2024-25. Each experiment focuses on different Java programming concepts, including salary calculations, inheritance, access modifiers, and eligibility criteria using interfaces. The record includes a certificate of completion, an index of experiments, and sample codes for selected experiments.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views92 pages

Java Record.81

The document is a JAVA Lab Record for II/IV B.Tech students, detailing a series of 27 experiments conducted during the academic year 2024-25. Each experiment focuses on different Java programming concepts, including salary calculations, inheritance, access modifiers, and eligibility criteria using interfaces. The record includes a certificate of completion, an index of experiments, and sample codes for selected experiments.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 92

JAVA LAB

RECORD

Name: Year : II/IV


Semester: I Branch: Information Technology
Subject: JAVA LAB RECORD Roll No:

1
CERTIFICATE

This is to certify that is


a student, studying II/IV B.Tech register no. , branch
INFORMATION TECHNOLOGY has done 27 number of
experiments during the year 2024-25 in the subject OOPS
THROUGH JAVA LAB.

Lecture-in-charge Head of the Department

2
INDEX

PNO. DATE COURS GRADE SIGN


E
S.No NAME OF THE EXPERIMENT OUTCO
ME
1. Write a java program to
calculate gross salary & net
salary

2. Write a java program that


implements educational
hierarchy using
inheritance.

3. Write a program to identify the


accessibility of a variable by means
of different access specifies within
and outside package.

4. Write a java program to find the


details of the students eligible to
enroll for the examination
(Students, Department
combined give the eligibility
criteria for the enrolment class)
using interfaces
5. Write a Java program that
displays area of different Figures
(Rectangle, Square, Triangle)
using the method overloading.

6. Write a Java program that


displays that displays the time in
different formats in the form of
HH,MM,SS using constructor
Overloading.

3
7. Write a Java program that counts
the number of objects created by
using static variable.

8. Write a Java program to count the


frequency of words,
characters in the given line of
text.

9. Write a Java program for sorting


a given list of names in
ascending order.

10. Write a Java program that reads a


line of integers separated by
commas and then displays each
integer and fund the sum of the
integers (using String Tokenizer).

11. Write a java program that stores


city/place against the country for
which it is a capital. country can
have more than
one capital.

12. Given a large list size (greater


than 1000) of integers with
positive and negative numbers,
write a sort program to sort all
negative and positive numbers
using streams.
13. Given a digital account, write
a multithreaded program with
account
credits and debits happening on
multiple cards in the digital
account in a concurrent fashion
with consistent transaction. for
example, account is a set of cards
modified concurrently.
14. Write a Java program that
reads a file name from the
user then displays
information about whether that
file exists, file is writable, the type
of file and length of the file in
bytes.

15. Write a Java program that reads a


file and displays the file on the
screen with a line number before
word count of a file.

16. Write a java program that


implements
Array Index out of bound
Exception using built in-
Exception.

17. Write a program that takes path as


input and displays al files and
folders including sub folders with
file and folder properties.

18. Write a java program that


implements bank transactions
using user defined exception.
example: Insufficient funds,
account not active, invalid
amount.

13
19. Write a java program to generate
multiple threads of creating clock
pulses. (using
runnable interface).

20. Write a java program to use


synchronized blocks for
instantiating a singleton class.

21. Write a java program to


demonstrate key events by using
Delegation event model on a frame.

22. Write a java program to implement


mouse events like mouse pressed,
mouse released and mouse moved
by means of adapter classes.

23. Write a java program to design a


registration form for creating a
new eMail account with first
name, last name,
username, user date of birth, user
address line1, address line2, area,
city/district, pin code using grid
layout.

24. Write a JDBC program which


creates customer table, insert
data into it and retrieves data
from customer.

14
25. Write a java program to
handle jdbc resources via try
with resources and finally
block to handle all kind of
exceptions.

26. Write a set of 500 customers


into the customer table of (24
experiment) in batches of 50
records each.

27. Print your date of birth using date


format of India, Germany, USA
and find no of days you have lived.

15
EXPERIMENT-1
AIM: Write a java program to calculate gross salary & net salary
taking the following data.
Input: emp no, emp name, basic
Process: DA=50%of basic
HRA=25%of basic
PF=10%of
basic
PT=Rs100/-
DESCRIPTION:
This Java program takes input for an employee's number, name, and
basic salary, then calculates the gross and net salary based on
specified percentages for DA, HRA, and PF, as well as a fixed PT
deduction. The program outputs each component of the salary
calculation along with the final gross and net salaries.
Input:
 Employee Number (employeeNo): A unique identifier for
the employee.
 Employee Name (employeeName): The name of the employee.
 Basic Salary (basicSalary): The base salary of the
employee before any additions or deductions.
Process:
 DA (Dearness Allowance): Calculated as 50% of the basic salary.
 HRA (House Rent Allowance): Calculated as 25% of the
basic salary.
 PF (Provident Fund): Calculated as 10% of the basic salary.
 PT (Professional Tax): A fixed amount of 100.
Using these, the program calculates:
 Gross Salary: The sum of the basic salary, DA, and HRA.
 Net Salary: Gross salary minus the PF and PT deductions.
Output:
 The program displays the employee’s basic salary, DA, HRA,
PF, PT, gross salary, and net salary in a structured format.
SOURCE CODE:
import java.util.Scanner;
public class Salary{
public static void main(String args[]) {
String employeeNo, employeeName;
int basicsalary, DA, HRA, PF, PT = 100, grosssalary,
netsalary; Scanner scanner = new Scanner(System.in);
System.out.println("Enter basic salary:");
basicsalary = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter employee number:");
employeeNo = scanner.nextLine();
System.out.println("Enter employee name:");
employeeName = scanner.nextLine();
DA = 50 * basicsalary / 100;
HRA = 25 * basicsalary / 100;
PF = 10 * basicsalary / 100;
grosssalary = basicsalary + DA + HRA;
netsalary = grosssalary - PF - PT;
System.out.println("Gross salary of " + employeeName + ": " +
grosssalary);
System.out.println("Net salary of " + employeeName + ": " +
netsalary);
}
}
OUTPUT:

RESULT: JAVA program is successfully executed.


EXPERIMENT-2
AIM: Write a java program that implements educational hierarchy
using inheritance.
DESCRIPTION:
To create an educational hierarchy in Java, we can use inheritance to
represent the different levels within a school or university system.
For example, let's consider a structure where we have a general
Person class at the top, and specific types of people in an educational
context—such as Student, Teacher, and Principal—inheriting from
Person. This demonstrates a simple hierarchy using inheritance.
Base Class: Person
 Represents a general person with common attributes such
as name, age, and address.
 Provides a constructor to initialize these attributes and
a method to display basic information.
Derived Class: Student
 Inherits from Person.
 Adds specific attributes for students, such as gradeLevel
and studentID.
 Contains methods to display student-specific information.
Derived Class: Teacher
 Inherits from Person.
 Adds specific attributes for teachers, such as subject
and teacherID.
 Contains methods to display teacher-specific information.
Derived Class: Principal
 Inherits from Person.
 Adds specific attributes for principals, such as officeNumber.
 Contains methods to display principal-specific information.
Each class provides relevant methods for displaying its own
information, demonstrating how inheritance allows each derived
class to extend the base Person class with additional attributes and
behaviors.
SOURCE CODE:
import java.util.Scanner;
public class Inheritance
{
public static void main(String args[]) {
Teaching t = new Teaching();
System.out.println("Enter details for Teaching Staff:");
t.getvalue();
t.setvalue();
NonTeaching t1 = new NonTeaching();
System.out.println("\nEnter details for Non-Teaching Staff:");
t1.getvalue();
t1.setvalue();
}
}
class Office {
int
empno;
String empname;
double salary;
void getvalue() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter employee number:
"); empno = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter employee name: ");
empname = scanner.nextLine();
System.out.print("Enter salary: ");
salary = scanner.nextDouble();
}
}
class Teaching extends Office
{ String designation;
void setvalue() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter designation: ");
designation = scanner.next();
System.out.println("\nTeaching Staff Details:");
System.out.println("Employee Number: " + empno);
System.out.println("Employee Name: " + empname);
System.out.println("Salary: " + salary);
System.out.println("Designation: " + designation);
}
}
class NonTeaching extends Office
{ String designation;
void setvalue() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter designation: ");
designation = scanner.next();
System.out.println("\nNon-Teaching Staff Details:");
System.out.println("Employee Number: " + empno);
System.out.println("Employee Name: " + empname);
System.out.println("Salary: " + salary);
System.out.println("Designation: " + designation);
}
}
OUTPUT:

RESULT: JAVA program is successfully executed.


EXPERIMENT-3
AIM: Write a program to identify the accessibility of a variable by
means of different access specifies within and outside package.

DESCRIPTION:
In Java, access modifiers define the scope and accessibility of
variables, methods, constructors, and classes. There are four main
access modifiers:
1. public: Accessible from any class in any package.
2. protected: Accessible within the same package and
in subclasses in other packages.
3. default (no modifier): Accessible only within the same package.
4. private: Accessible only within the class it is declared in.
To illustrate this, let’s create a Java program with two
packages:
 Package 1 (package1): Contains a class with variables
using different access modifiers.
 Package 2 (package2): Contains another class that attempts
to access these variables.
Package 1 (package1) with Class AccessModifiersDemo:
 This class has variables with different access modifiers.
 A method display() shows the accessible variables within
the same class.
Package 2 (package2) with Class AccessTester:
 Attempts to access the variables from AccessModifiersDemo
to demonstrate which modifiers are accessible outside the
package.
SOURCE CODE:
//save by
A.java package
same; public
class A { int a =
20;
int b =
30; int c =
40; int d
= 50;
public void display() {
System.out.println("Inside display() method of A:");
System.out.println("Default (a): " + a);
System.out.println("Public (b): " + b);
System.out.println("Private (c): " + c);
System.out.println("Protected (d): " + d); } }
COMPILE ABOVE PROGRAM BY SYNTAX: java -d . classname.java
//save by B.java
package same;
public class B extends A {
public static void main(String[] args) {
B b = new B();
System.out.println("Within the same package:");
System.out.println("Default (a): " + b.a);
System.out.println("Public (b): " + b.b);
System.out.println("Protected (d): " + b.d);
b.display(); } }
//save by C.java
package other;
import same.A;
public class C extends A {
public static void main(String[] args) {
C c = new C();
System.out.println("Within a different package:");
System.out.println("Default (a): " + c.a);
System.out.println("Public (b): " + c.b);
System.out.println("Private (c): " + c.c);
System.out.println("Protected (d): " +
c.d); c.display(); } }
Output:

RESULT: JAVA program is successfully executed.


EXPERIMENT-4
AIM: Write a java program to find the details of the students eligible
to enroll for the examination (Students, Department combined give
the eligibility criteria for the enrolment class) using interfaces.
Description:
The goal of the Java program is to find the details of students who
are eligible to enroll for an examination, based on certain eligibility
criteria that combine both student and department information.
This is done using interfaces.
The eligibility criteria for the enrollment can include conditions like:
 Minimum CGPA: A student needs to have a certain CGPA to
be eligible.
 Minimum attendance percentage: A student needs to have
a minimum attendance percentage to be eligible.
 Department: Some departments might have additional
specific conditions for eligibility.
The program will use an interface to define the eligibility criteria,
then implement that interface in a class. This approach will help to
encapsulate the eligibility logic separately and make it easier to
apply to different student/department objects.
Steps:
1. Define an Interface (EligibilityCriteria): The interface will
contain methods that will define the eligibility criteria for
enrolling in the examination. For example, checking if a
student's CGPA and attendance meet the criteria.
2. Create the Student Class: The student class will implement the
EligibilityCriteria interface and will have attributes like name,
student ID, CGPA, attendance, and the department they belong
to.
3. Create the Department Class: The department class will
contain details about the department, such as its name
and code.
4. Create a Main Class: The main class will initialize the students
and departments, then check if each student is eligible to
enroll in the examination based on the provided criteria.

SOURCE CODE:
interface EligibilityCriteria {
boolean isEligible(double cgpa, int attendance);
}
class Department {
String deptName;
String deptCode;
Department(String deptName, String deptCode) {
this.deptName = deptName;
this.deptCode = deptCode;
}
}
class Student implements EligibilityCriteria {
String studentName;
int studentId;
double cgpa;
int attendance;
Department department;
Student(String studentName, int studentId, double cgpa, int
attendance, Department department) {
this.studentName = studentName;
this.studentId = studentId;
this.cgpa = cgpa;
this.attendance = attendance;
this.department = department;
}
@Override
public boolean isEligible(double cgpa, int attendance) {
return cgpa >= 7.0 && attendance >= 75;
}
public void displayDetails() {
System.out.println("Student Name: " + studentName);
System.out.println("Student ID: " + studentId);
System.out.println("Department: " + department.deptName + "
(" + department.deptCode + ")");
System.out.println("CGPA: " + cgpa);
System.out.println("Attendance: " + attendance + "%");
}
public void checkEligibility() {
if (isEligible(cgpa, attendance)) {
System.out.println(studentName + " is eligible for the
examination.");
} else {
System.out.println(studentName + " is not eligible for the
examination.");
}
}
}
public class Main {
public static void main(String[] args) {
Department csDept = new Department("Computer Science",
"CS101");
Department eeDept = new Department("Electrical Engineering",
"EE102");
Student student1 = new Student("Sri", 1001, 8.0, 80, csDept);
Student student2 = new Student("Ram", 1002, 6.5, 70, eeDept);
student1.displayDetails();
student1.checkEligibility();
System.out.println("-------------------------");
student2.displayDetails();
student2.checkEligibility();
}
}

Output:
RESULT: JAVA program is successfully executed.
EXPERIMENT-5

Aim: Write a Java program that displays area of different


Figures (Rectangle, Square, Triangle) using the method
overloading.
Description:
The task is to write a Java program that calculates the area of
different geometric figures (Rectangle, Square, and Triangle) using
method overloading. Method overloading allows multiple methods in
the same class to have the same name but different parameters.
Approach:
1. Method Overloading:
o We will create methods with the same name
calculateArea() in the class, but with different parameter
lists (for different figures).
o For each shape, we will pass different arguments:
 For a Rectangle, we need two parameters:
length and width.
 For a Square, we need one parameter: side (since
all sides are equal).
 For a Triangle, we need two parameters: base
and height.
2. Create Classes for Shapes:
o We will create a class Shape that contains
overloaded methods to calculate the area for each
shape.
3. Display Area:
o The main class will call the respective
calculateArea() method for each shape and display
the result.
Source code:
import
java.util.*; class
Area
{
static double area(double b, double h)
{
return 0.5*b*h;
}
static int area(int l, int w)
{
return l*w;
}
static double area(double s)
{
return s*s;
}
public static void main(String args[])
{
System.out.println("area of triangle="+area(2.3,4.5));
System.out.println("area of square="+area(10));
System.out.println("area of rectangle="+area(12,14));
}}
Output:

RESULT: JAVA program is successfully executed.


EXPERIMENT-6
Aim: Write a Java program that displays that displays the time in
different formats in the form of HH,MM,SS using constructor
Overloading.
Description:
The task is to write a Java program that displays time in different
formats using constructor overloading. Constructor overloading
allows a class to have multiple constructors with different
parameters. In this program, we will create a class that provides
different ways to represent time using overloaded constructors, and
display the time in the format HH:MM
1. Constructor Overloading:
o We will create multiple constructors to initialize the
time in different formats:
 A constructor that accepts hours, minutes,
and seconds.
 A constructor that accepts only hours and
minutes, assuming seconds as 00.
 A constructor that accepts only hours,
assuming both minutes and seconds as 00.
2. Display Time:
o We will create methods to display the time in the
format HH:MM:SS after initializing the time using any of
the constructors.
Source code:
import java.util.*;
class ConstructorDemo
{
int hours;
int minutes;
int seconds;
ConstructorDemo(int hours, int minutes, int seconds)
{
this.hours=hours;
this.minutes=minutes;
this.seconds=seconds;
System.out.println("hours="+hours);
System.out.println("minutes="+minutes);
System.out.println("seconds="+seconds);
}
ConstructorDemo(int minutes, int seconds)
{
this.minutes=minutes;
this.seconds=seconds;
System.out.println("minutes="+minutes);
System.out.println("seconds="+seconds);
}
ConstructorDemo(int seconds)
{
this.seconds=seconds;
System.out.println("seconds="+seconds);
}
public static void main(String args[])
{
ConstructorDemo cd1=new ConstructorDemo(8,7,20);
ConstructorDemo cd2=new ConstructorDemo(4,36);
ConstructorDemo cd3=new ConstructorDemo(12);
}}
Output:

RESULT: JAVA program is successfully executed.


EXPERIMENT-7
Aim: Write a Java program that counts the number of objects
created by using static variable.
Description:
1. The objectCount variable is declared as static, meaning it's
shared among all instances of the ObjectCounter class.
2. The constructor ObjectCounter() increments the
objectCount variable each time a new object is created.
3. The getObjectCount() method returns the current value
of objectCount.
4. In the main() method, three objects are created, and the
object count is printed.
Advantages:
- Simple implementation
- Efficient use of memory (single static
variable) Limitations:
- Does not account for object destruction (garbage collection)
- Not thread-safe (multiple threads may access
objectCount simultaneously)
Variations:
- To account for object destruction, use a finalize()
method (deprecated) or PhantomReference.
- To ensure thread-safety, use AtomicInteger or synchronized blocks.
Source code:
import java.util.*;
public class ObjectCounter{
private static int ObjectCount=0;
public ObjectCounter()
{
ObjectCount++;
}
public static int getObjectCount(){
return ObjectCount;
}
public void finalize()
{
ObjectCount--;
}
public static void main(String args[]){
ObjectCounter Obj1=new ObjectCounter();
ObjectCounter Obj2=new ObjectCounter();
ObjectCounter Obj3=new ObjectCounter();
System.out.println("no of objects
created:"+ObjectCounter.getObjectCount());
}
}
Output:

RESULT: JAVA program is successfully executed.


EXPERIMENT-8
Aim: Write a Java program to count the frequency of words,
characters in the given line of text.

Description:
This Java program analyzes a line of text and provides two types of
frequency counts:
1. Word Frequency: Counts the occurrences of each word in the text.
2. Character Frequency: Counts the occurrences of each character
in the text.
1. The program prompts the user to enter a line of text.
2. The countWordFrequency method splits the text into
words, converts them to lowercase, and stores their
frequencies in a HashMap.
3. The countCharFrequency method iterates through each
character in the text and stores their frequencies in another
HashMap.
4. The printMap method displays the contents of each
frequency map.
Variations:
- To ignore punctuation, add a regex pattern to remove
punctuation from the text before counting.
- To count frequency in a file, replace Scanner with
BufferedReader and read the file line by line.
Source code:

class Frequency {
public static void main(String[] args) {
String str = "picture perfect";
int[] freq = new int[str.length()];
char[] string = str.toCharArray(); for
(int i = 0; i < str.length(); i++) {
freq[i] = 1;
for (int j = i + 1; j < str.length(); j++) { if
(string[i] == string[j]) {
freq[i]++;
string[j] = '0';
}
}
}
System.out.println("Characters and their corresponding
frequencies:");
for (int i = 0; i < freq.length; i++) {
if (string[i] != ' ' && string[i] != '0')
System.out.println(string[i] + "-" + freq[i]);
}
}}
Output:

RESULT: JAVA program is successfully executed.


EXPERIMENT-9
Aim: Write a Java program for sorting a given list of names in
ascending order.
Description:
This Java program sorts a list of names in ascending order using the
Collections.sort() method.
1. Asks the user for the number of names.
2. Prompts the user to enter each name.
3. Stores the names in an ArrayList.
4. Prints the unsorted list.
5. Sorts the list using Collections.sort().
6. Prints the sorted list.
- To sort in descending order, use
Collections.sort(names, Collections.reverseOrder()).
- To sort names ignoring case, use
Collections.sort(names,
String.CASE_INSENSITIVE_ORDER).
Uses Java 8 Streams for
sorting. Reads names into an
array.
Sorts the array using `Arrays.stream().sorted()`.
Joins sorted names into a single string using `Collectors.joining()`.
Prints the sorted names.
Source Code:
import java.util.ArrayList;
import java.util.Collections;
public class Cars{
public static void main(String args[])
{
ArrayList<String>cars=new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add(“RangeRover”);
cars.add("Ford");
cars.add("Audi");
Collections.sort(cars);
for(String i:cars)
{
System.out.println(i);}
}
}
Output:

RESULT: JAVA program is successfully executed.


EXPERIMENT-10
Aim: Write a Java program that reads a line of integers separated by
commas and then displays each integer and fund the sum of the
integers (using String Tokenizer).
Description:
This Java program demonstrates the usage of the StringTokenizer
class to split a string into substrings based on a specified delimiter.
Functionality:
1. Reads a string input from the user.
2. Splits the input string into tokens using a comma (",") as
the delimiter.
3. Displays each token.
4. Calculates the sum of integers in the tokens.
Error handling: Handles non-integer inputs and invalid delimiter
usage.
Input validation: Validates user input for integers separated by
commas.
Tokenization: Demonstrates tokenization using StringTokenizer.
This program:
1. Prompts the user to enter a line of integers separated by commas.
2. Uses `StringTokenizer` to split the input string into integer tokens.
3. Iterates through each token, converts it to an integer, and
displays it.
4. Calculates the sum of all integers.
Use `String.split()` instead of `StringTokenizer` for simpler cases.
Use `Scanner` with `useDelimiter()` for parsing strings with multiple
delimiters.
Source code:
import java.util.*;
class StringTokenDemo {
public static void main(String[] args) {
StringTokenizer str1 = new StringTokenizer("518275,9876,4325,917", ",");
StringTokenizer s2 = new StringTokenizer("Hi Sri");
System.out.println("Number of tokens in str1 = "+str1.countTokens());
System.out.println("Number of tokens in s2 = "+s2.countTokens());
int sum = 0;
while (str1.hasMoreTokens()) {
int n=Integer.parseInt(str1.nextToken());
sum+= n;
}
System.out.println("Sum of integers = "+sum); while
(s2.hasMoreTokens()) {
System.out.println("Next Token = "+s2.nextToken());
}
}
}
Output:

RESULT: JAVA program is successfully executed.


EXPERIMENT-11
Aim: Write a java program that stores city/place against the country
for which it is a capital. country can have more than one capital.
Description:
Here's a Java program that allows storing cities (capitals) for a
country. This program uses a HashMap<String, List<String>> where
the key is the country name, and the value is a list of cities (capitals)
associated with that country. This design allows multiple capitals to
be stored for each country.
The program provides methods to:
1. Add a capital city for a country.
2. Display all capitals for a specified country.
3. Display all countries with their capitals.
4. Data Structure: A HashMap<String, List<String>> is used to
store the country as the key and a list of capitals as the
value. This allows multiple capitals for each country.
5. Adding Capitals: The addCapital() method uses
computeIfAbsent() to add a new capital to the list for
the country.
6. Displaying Capitals: The displayCapitals() method retrieves
and displays all capitals of a specified country.
7. Displaying All Data: The displayAllCountriesAndCapitals()
method loops through the HashMap to display each
country and its list of capitals.

Source code:
import java.util.*;
class Capital {
private String country;
private Set<String> capitals;
public Capital(String country) {
this.country = country;
this.capitals = new HashSet<>();
}
public void addCapital(String capital) {
capitals.add(capital);
}
public String getCountry() {
return country;
}
public Set<String> getCapitals() {
return capitals;
}
}
public class CountryCapitalMap {
private Map<String, Capital> countryCapitalMap;
public CountryCapitalMap() {
countryCapitalMap = new HashMap<>();
}
public void addCountryCapital(String country, String capital) {
countryCapitalMap.computeIfAbsent(country, c -> new
Capital(c)).addCapital(capital);
}
public void printCountryCapitals() {
for (Map.Entry<String, Capital> entry
: countryCapitalMap.entrySet()) {
Capital capital = entry.getValue();
System.out.println("Country: " + capital.getCountry());
System.out.println("Capitals: " + capital.getCapitals());
System.out.println();
}}
public static void main(String[] args) {
CountryCapitalMap map = new CountryCapitalMap();
map.addCountryCapital("USA", "Washington D.C.");
map.addCountryCapital("Japan", "Tokyo");
map.addCountryCapital("France", "Paris");
map.printCountryCapitals();
}}
Output:

RESULT: JAVA program is successfully executed.


EXPERIMENT-12
Aim: Given a large list size (greater than 1000) of integers
with positive and negative numbers, write a sort program to
sort all negative and positive numbers using streams.
Description:
To sort a large list of integers (with both positive and negative
numbers) in Java using streams, you can separate the negative and
positive numbers, sort each group, and then combine them.
Filter and Sort Negatives: The stream first filters out the negative
numbers, sorts them in ascending order, and collects them in a list.
Filter and Sort Positives: The stream then filters the non-negative
numbers (positive and zero), sorts them, and appends them to the
list containing the sorted negative numbers.
Combining the Lists: The sorted positive numbers are appended to
the list of sorted negative numbers, resulting in all negative numbers
appearing before all non-negative numbers.
This approach maintains all negative numbers in ascending order
first, followed by non-negative numbers in ascending order.
Source code:
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main1 {
public static void main(String[] args) {
int[] numbers = IntStream.range(-10, 10).toArray();
List<Integer> negativeNumbers =
IntStream.of(numbers)
.filter(n -> n < 0)
.boxed()
.sorted()
.collect(Collectors.toList());
List<Integer> positiveNumbers = IntStream.of(numbers)
.filter(n -> n >= 0)
.boxed()
.sorted()
.collect(Collectors.toList());
System.out.println("Negative Numbers: " + negativeNumbers);
System.out.println("Positive Numbers: " + positiveNumbers);
}
}
Output:

RESULT: JAVA program is successfully executed.


EXPERIMENT-13
Aim: Given a digital account, write a multi-threaded program with
account credits and debits happening on multiple cards in the digital
account in a concurrent fashion with consistent transaction. for
example, account is a set of cards modified concurrently.

Description:
In this example, we’ll implement a multi-threaded Java program to
simulate concurrent credit and debit transactions happening on
multiple "cards" in a digital account. Each "card" represents a thread
performing random credits and debits. We’ll use a shared Account
object to keep track of the balance, and we’ll synchronize
transactions to ensure thread-safe operations on the account
balance.
Account Class:
 Manages the account balance with synchronized credit
and debit methods to ensure thread safety.
 The debit method checks if there’s enough balance
before deducting, simulating real-world balance
validation.
CardTransaction Class:
 Implements Runnable and simulates random credit and
debit transactions on the shared account.
 Each card performs 10 transactions, with random delays
to emulate real-world concurrent activity.
DigitalAccountSimulation Class (Main):
 Initializes the account with an initial balance.
 Creates multiple threads (each representing a card) that
perform transactions on the shared account
concurrently.
 Joins all threads to ensure the main program waits until
all transactions are complete.
Thread-Safety: The use of synchronized blocks on credit and debit
ensures that only one thread can modify the balance at any time,
preserving consistency.

Source code:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
class Account {
private int balance;
public Account(int initialBalance) {
this.balance = initialBalance;
}
public synchronized void credit(int amount) {
balance += amount;
System.out.println(Thread.currentThread().getName() + "
credited " + amount + ". Balance: " + balance);
}
public synchronized void debit(int amount) {
if (balance >= amount) {
balance -= amount;
System.out.println(Thread.currentThread().getName() + " debited " +
amount + ". Balance: " + balance);
} else {
System.out.println(Thread.currentThread().getName() + " tried to
debit " + amount + " but insufficient funds. Balance: " + balance);
}}
public int getBalance() {
return balance;
}}
class CardTransaction implements Runnable {
private Account account;
private Random random = new Random();
public CardTransaction(Account account)
{
this.account = account;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
int amount = random.nextInt(100) +
1; if (random.nextBoolean()) {
account.credit(amount);
} else {
account.debit(amount);
}
try {
Thread.sleep(random.nextInt(100));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Transaction interrupted: " +
e.getMessage());
}}}
}
public class DigitalAccountSimulation {
public static void main(String[] args) {
Account sharedAccount = new Account(500);
List<Thread> cards = new ArrayList<>();
for (int i = 0; i < 5; i++) {
Thread card = new Thread(new
CardTransaction(sharedAccount), "Card-" + (i + 1));
cards.add(card);
card.start();
}
for (Thread card : cards)
{ try {
card.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Main thread interrupted: " +
e.getMessage());
}}
System.out.println("Final Balance: "
+ sharedAccount.getBalance());
}
}
Output:

RESULT: JAVA program is successfully executed.


EXPERIMENT-14
Aim: Write a Java program that reads a file name from the user then
displays information about whether that file exists, file is writable,
the type of file and length of the file in bytes.
Description:
Here's a Java program that reads a file name from the user, then
displays information about the file, including whether it exists,
whether it is writable, the type of file, and its length in bytes.
This program uses the java.io.File class to retrieve information about
the file.
User Input: The program prompts the user to enter a file name,
which is read using Scanner.
File Existence Check: The program checks if the file exists with
file.exists().
File Writable Check: The program checks if the file is writable using
file.canWrite().
File Type Check: The program determines whether the specified path
is a file or a directory using file.isDirectory().
File Length: The program retrieves the length of the file in bytes
using file.length().
Source code:
import java.util.*;
import java.io.*;
public class FileInformation {
public static void main(String[] args) throws IOException {
System.out.println("Enter your file name:");
Scanner sc = new Scanner(System.in);
String fileName = sc.nextLine();
sc.close();
File file = new
File(fileName); if
(file.exists()) {
System.out.println("File exists: " + file.exists());
System.out.println("File is writable: " + file.canWrite());
if (file.isDirectory()) {
System.out.println("File Type: Directory");
} else {
System.out.println("File Type: Regular file");
}
long fileSize = file.length();
System.out.println("File Size: " + fileSize + " bytes");
} else {
System.out.println("File does not exist");
}}}
Output:

RESULT: JAVA program is successfully executed.


EXPERIMENT-15
Aim: Write a Java program that reads a file and displays the file on
the screen with a line number before word count of a file.
Description:
Here's a Java program that reads a file and displays its contents line
by line on the screen. Each line is preceded by its line number and
followed by the word count for that line. This program uses the
java.io.BufferedReader class to read the file and
java.util.StringTokenizer to count words.
User Input for File Name:
 The program prompts the user to enter the file
name. Reading the File:
 The BufferedReader reads each line of the
file. Line-by-Line Processing:
 For each line, a StringTokenizer counts the words by
splitting the line into tokens (words).
Displaying Information:
 For each line, the program displays the line number,
word count, and line content.
Exception Handling:
 Handles IOException in case of file reading
errors. File Closure:
 The finally block ensures the file is closed after reading
Source code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
class FileReaderWithWordCount {
public static void main(String[] args) {
String fileName = "sample.txt";
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line;
int lineNumber = 1;
while ((line = br.readLine()) != null)
{ int wordCount =
countWords(line);
System.out.println("Line " + lineNumber + " (" + wordCount + "
words): " + line);
lineNumber++;
}
br.close();
} catch (IOException e) {
System.out.println("An error occurred while reading the file: " +
e.getMessage());
}}
private static int countWords(String line) {
if (line == null || line.trim().isEmpty()) {
return 0;
}
String[] words = line.trim().split("\\s+");
return words.length;}}
Output:

RESULT: JAVA program is successfully executed.


EXPERIMENT-16
Aim: Write a java program that implements Array Index out of
bound Exception using built in- Exception.
Description:
Here’s a Java program that demonstrates the
ArrayIndexOutOfBoundsException, which is a built-in exception in
Java. This program intentionally tries to access an array element at an
invalid index to trigger the exception, then handles it using a try-
catch block.
Array Declaration: The numbers array has 5 elements, with valid
indices from 0 to 4.
Out-of-Bounds Access: In the try block, the program attempts to
access numbers[5], which is outside the array’s bounds.
Exception Handling:
 When the out-of-bounds access occurs, an
ArrayIndexOutOfBoundsException is thrown.
 The catch block catches this exception, allowing the program
to handle the error and print a meaningful message.
Program Continuation: After handling the exception, the program
continues executing normally.
This program demonstrates how to handle
ArrayIndexOutOfBoundsException in Java, providing clear feedback
to the user and ensuring the program continues running smoothly
after the exception is caught.
Source code:
import java.util.*;
class ExceptionDemo {
public static void main(String[] args) {
int[] a = {1, 2, 6, 8, 9};
System.out.println("Accessing valid indexes:");
System.out.println("a[4]: " + a[4]);
System.out.println("a[2]: " +
a[2]); try {
System.out.println("Trying to access a[6]: " + a[6]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception raised: " + e);
System.out.println("Exception is handled.");
}}}
Output:

RESULT: JAVA program is successfully executed.


EXPERIMENT-17
Aim: Write a program that takes path as input and displays al files
and folders including sub folders with file and folder properties.
Description:
Here is a Java program that takes a directory path as input and
recursively lists all files and folders, including their properties like
whether they are files or directories, and their size. It uses the File
class to check the properties of files and folders.
User Input:
 The program prompts the user to enter the directory path.
 The directory path is read using
Scanner. Directory Validation:
 The program checks if the provided path exists and if it's a
directory using directory.exists() and
directory.isDirectory().
Listing Files and Folders:
 The listFilesAndFolders method recursively lists all files
and folders in the given directory.
 It checks whether an entry is a file or a directory using
file.isDirectory() and displays the name and size (in bytes)
for files. For directories, it displays "N/A" for size and
recursively lists its contents.
Recursive Directory Traversal:
 The method listFilesAndFolders is called recursively
for subdirectories to explore the contents of each
folder.
Source code:
import java.io.*;
import java.util.*;
public class FileFolderLister {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the directory path: ");
String path = scanner.nextLine();
scanner.close();
File directory = new File(path);
if (directory.exists() && directory.isDirectory()) {
System.out.println("Listing files and folders in: " + path);
listFilesAndFolders(directory);
} else {
System.out.println("The path is not a valid directory or does not
exist.");
}}
public static void listFilesAndFolders(File directory) {
File[] files = directory.listFiles();
if (files != null && files.length > 0) {
for (File file : files) {
System.out.print("Name: " +
file.getName()); if (file.isDirectory()) {
System.out.print("[Directory]");
System.out.println(" - Size:
N/A"); listFilesAndFolders(file);
} else {
System.out.print(" [File]");
System.out.println(" - Size: " + file.length() + " bytes");
}}} else {
System.out.println("No files or folders found in this directory.");
}}
}

Output:

RESULT: JAVA program is successfully executed.


EXPERIMENT-18
Aim: Write a java program that implements bank transactions using
user defined exception. example: Insufficient funds, account not
active, invalid amount.
Description:
Here is a Java program that simulates a simple banking system with
custom user-defined exceptions for various situations, such as
insufficient funds, account not active, and invalid amount.
User-defined Exceptions:
 InsufficientFundsException: This exception is thrown when the
user tries to withdraw more money than what is available in
the account.
 AccountNotActiveException: This exception is thrown if
the user tries to perform transactions on a deactivated
account.
 InvalidAmountException: This exception is thrown if the
user tries to deposit or withdraw an invalid (negative or
zero) amount.
BankAccount Class:
 The BankAccount class has methods for depositing,
withdrawing, checking balance, and deactivating the
account.
 It throws exceptions as needed based on the conditions
(e.g., insufficient funds, account not active, or invalid
amount).
BankTransactionApp Class:
 This is the main class that allows the user to perform
transactions like deposit, withdraw, check balance,
and deactivate the account.
 The menu is displayed repeatedly until the user chooses to exit.
 Try-catch blocks are used to catch and handle
exceptions thrown by the methods in the BankAccount
class.
Source code:
import java.util.*;
class UserDefinedException extends Exception {
public UserDefinedException(String message) {
super(message);
}}
class BankTransaction {
public static void main(String[] args) {
Scanner sc = new
Scanner(System.in); int balance =
1000;
while (true) {
System.out.println("\n1.Deposit 2.Withdraw 3.Check Balance 4.Exit");
int option = sc.nextInt();
try {
switch (option) {
case 1:
System.out.println("Enter amount to deposit:");
int deposit = sc.nextInt();
balance += deposit;
System.out.println("Deposited: " + deposit);
break;
case 2:
System.out.println("Enter withdrawal amount:");
int withdraw = sc.nextInt();
if (withdraw > balance) {
throw new UserDefinedException("Insufficient funds");
}
balance -= withdraw;
System.out.println("Withdrew: " + withdraw);
break;
case 3:
System.out.println("Current balance: " + balance);
break;
case 4:
System.out.println("Exiting...");
sc.close();
return;
default:
System.out.println("Invalid option. Please try again.");
}}
catch (UserDefinedException e) {
System.out.println(e.getMessage());}
}
}
}
Output:

RESULT: JAVA program is successfully executed.


EXPERIMENT-19
Aim: Write a java program to generate multiple threads of creating
clock pulses. (using runnable interface).
Description:
To create a Java program that generates multiple threads simulating
clock pulses using the Runnable interface, we need to implement a
thread that will continuously print the clock pulse at regular intervals.
Multiple threads can simulate different clock pulses.
ClockPulse Class:
 Implements the Runnable interface, meaning the run()
method must be defined.
 The run() method simulates the generation of clock pulses by
printing the pulse count every second (1 second interval
using Thread.sleep(1000)).
 The clockName is passed to identify different clock pulses
(e.g., Clock 1, Clock 2).
ClockPulseSimulator Class:
 This is the main class where we create and start
multiple threads to simulate different clock pulses.
 We create two ClockPulse objects (representing two
different clock pulses) and pass them to Thread objects.
 The threads are started using start() method, which in turn
calls the run() method of the ClockPulse class.
Thread Execution:
 Each thread independently simulates a clock pulse by
printing messages like "Clock 1 Pulse: 1", "Clock 2 Pulse: 1",
and so on.
 The pulses are printed every second because of
Thread.sleep(1000), which pauses the thread for 1000
milliseconds (1 second).
Source code:
import java.util.*;
class ClockPulse implements Runnable {
String name;
public ClockPulse(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.print(name);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}}}
}
public class ClockPulses {
public static void main(String[] args) {
ClockPulse cp = new ClockPulse("_|");
ClockPulse cp1 = new ClockPulse("-|");
Thread t1 = new Thread(cp);
Thread t2 = new
Thread(cp1); t1.start();
t2.start();
}}

Output:

RESULT: JAVA program is successfully executed.


EXPERIMENT-20
Aim: Write a java program to use synchronized blocks for
instantiating a singleton class.
Description:
In Java, a singleton class ensures that only one instance of the class is
created and provides a global point of access to that instance. In
multi-threaded environments, it is essential to ensure that only one
instance is created, even when multiple threads are trying to create
the instance simultaneously. To achieve this, we can use synchronized
blocks to prevent race conditions.
Singleton Class:
 Private Static Variable (instance): This variable holds the
single instance of the class. It is declared private to prevent
direct access from outside the class.
 Private Constructor: The constructor is private, so the
class cannot be instantiated directly from outside.
 getInstance() Method: This method returns the single
instance of the Singleton class. It uses the synchronized block
to ensure that only one thread can create the instance at a
time.
o The first if (instance == null) check ensures that
the synchronization only occurs the first time.
o The second if (instance == null) inside the synchronized
block ensures that another thread hasn't already
created the instance while the first thread was blocked.
o This double-checking mechanism is a common pattern
for implementing a thread-safe singleton.
Source code:

class Table{
void printTable(int n) {
synchronized(this) {
for(int i = 1; i <= 5; i++) {
System.out.println(n *
i); try{
Thread.sleep(400);
} catch (Exception e) {
System.out.println(e);
}}}}
}
class MyThread extends Thread
{ Table t;
MyThread(Table t)
{ this.t = t;
}
public void run()
{ t.printTable(5);

}
}
class MyThread2 extends Thread
{ Table t;
MyThread2(Table t)
{ this.t = t;}
public void run()
{ t.printTable(100
);
}
}
class SynchronizedBlock {
public static void main(String args[]) {
Table obj = new Table();
MyThread t1 = new MyThread(obj);
MyThread2 t2 = new
MyThread2(obj); t1.start();
t2.start();
}
}
Output:

RESULT: JAVA program is successfully executed.


EXPERIMENT-21
Aim: Write a java program to demonstrate key events by using
Delegation event model on a frame.
Description:
Here is a Java program that demonstrates handling key events on a
frame using the Delegation Event Model. In this example, we'll create
a simple frame that listens for key events, and it will display the key
pressed, released, or typed on the frame.
Frame Setup: A frame (KeyEventDemo) is created, which extends
Frame and implements KeyListener to handle key events.
Label for Displaying Events: A label (label) is added to display
messages when keys are pressed, typed, or released.
KeyListener Interface Methods: The program overrides three
methods:
 keyTyped(KeyEvent e): Called when a key is typed
(character input).
 keyPressed(KeyEvent e): Called when a key is pressed down.
 keyReleased(KeyEvent e): Called when a key is released.
Window Closing Listener: An anonymous WindowAdapter is added to
handle closing the frame by exiting the application.
Source code:
import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class KeyEventDemo extends JFrame implements KeyListener
{ private JTextArea textArea;
public KeyEventDemo() {
setTitle("KeyEvent Demo");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
textArea = new JTextArea();
textArea.setBounds(20, 20, 350,
200); textArea.addKeyListener(this);
add(textArea);
textArea.setFocusable(true);
textArea.requestFocusInWindow();
}
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
char keyChar = e.getKeyChar();
textArea.append("Key Pressed: " + keyChar + " (Code: " + keyCode +
")\n");
}
public void keyReleased(KeyEvent e)
{ int keyCode = e.getKeyCode();
char keyChar = e.getKeyChar();
textArea.append("Key Released: " + keyChar + " (Code: " + keyCode
+ ")\n");
}
public void keyTyped(KeyEvent e)
{ char keyChar = e.getKeyChar();
textArea.append("Key Typed: " + keyChar + "\n");
}
public static void main(String[] args) {
KeyEventDemo frame = new
KeyEventDemo(); frame.setVisible(true);
}
}

Output:

RESULT: JAVA program is successfully executed.


EXPERIMENT-22
Aim: Write a java program to implement mouse events like mouse
pressed, mouse released and mouse moved by means of adapter
classes.

Description:
Here's a Java program that demonstrates handling mouse
events such as mousePressed, mouseReleased, and
mouseMoved using adapter classes. We’ll use a JFrame and
implement these mouse events by extending MouseAdapter
and MouseMotionAdapter.
Frame Setup: The frame (MouseEventDemo) is created with
basic properties like title, size, and close operation.
Label for Displaying Events: A label (label) is added to show
which mouse event occurred along with the coordinates.
MouseAdapter for Pressed and Released Events:
 mousePressed(MouseEvent e): Triggered when the
mouse button is pressed; displays the coordinates of the
press.
 mouseReleased(MouseEvent e): Triggered when the
mouse button is released; displays the coordinates of the
release.
MouseMotionAdapter for Moved Event:
 mouseMoved(MouseEvent e): Triggered when the mouse
is moved without pressing buttons; displays the current
coordinates.

Source code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseEventDemo extends MouseAdapter {
Label label;
public MouseEventDemo() {
Frame frame = new Frame("Mouse Event Demo");
frame.setSize(300, 300);
frame.setLayout(null);
frame.addMouseListener(this);
label = new Label();
label.setBounds(20, 50, 200, 20);
frame.add(label);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}});
}
@Override
public void mouseClicked(MouseEvent e)
{ if (SwingUtilities.isLeftMouseButton(e)) {
label.setText("Left Click");
} else if (SwingUtilities.isRightMouseButton(e)) {
label.setText("Right Click");
}
}
@Override
public void mouseEntered(MouseEvent e) {
label.setText("Mouse Entered");
}
@Override
public void mouseExited(MouseEvent e) {
label.setText("Mouse Exited");
}
@Override
public void mousePressed(MouseEvent e) {
label.setText("Mouse Pressed");
}
@Override
public void mouseReleased(MouseEvent e) {
label.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseEventDemo();
}}
Output:
RESULT: JAVA program is successfully executed.
EXPERIMENT-23
Aim: Write a java program to design a registration form for creating
a new eMail account with first name, last name, username, user date
of birth, user address line1, address line2, area, city/district, pin code
using grid layout.
Description:
Here's a Java program to create a registration form for an email
account using GridLayout. The form includes fields for first name,
last name, username, date of birth, address line 1, address line 2,
area,
city/district, and pin code.
Frame Setup:
 We create a JFrame with the title "Email Registration Form."
 Set a GridLayout with 10 rows and 2 columns. Each
component is placed in a grid cell.
Form Fields:
 Labels and JTextFields are used for each required field: first
name, last name, username, date of birth, address lines,
area, city/district, and pin code.
Submit Button:
 A JButton labeled "Submit" is added for form submission
(without any action listener here; you could add functionality
as needed).
Alignment:
 An empty JLabel is added after the JButton to keep
the alignment consistent within the grid.

Source code:
import
javax.swing.*;
import java.awt.*;
class GridLayoutDemo
{ GridLayoutDemo() {
JFrame frame = new JFrame("Email Account Registration");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(9, 2, 5, 5)); // 9 rows, 2 columns,
with 5px padding
frame.add(new JLabel("First
Name:")); frame.add(new
JTextField()); frame.add(new
JLabel("Last Name:")); frame.add(new
JTextField()); frame.add(new
JLabel("Username:")); frame.add(new
JTextField());
frame.add(new JLabel("Date of Birth (DD/MM/YYYY):"));
frame.add(new JTextField());
frame.add(new JLabel("Address Line 1:"));
frame.add(new JTextField());
frame.add(new JLabel("Address Line 2:"));
frame.add(new JTextField());
frame.add(new JLabel("Area:"));
frame.add(new JTextField());
frame.add(new JLabel("City/District:"));
frame.add(new JTextField());
frame.add(new JLabel("Pin Code:"));
frame.add(new JTextField());
JButton submitButton = new
JButton("Submit"); frame.add(submitButton);
frame.add(new JLabel(""));
frame.setVisible(true);
}
public static void main(String args[]) {
new GridLayoutDemo();}
}
Output:

RESULT: JAVA program is successfully executed.


EXPERIMENT-24
Aim: Write a JDBC program which creates customer table, insert
data into it and retrieves data from customer.
Description:
JDBC program that creates a customer table, inserts some data into
it, and then retrieves the data from the customer table. This
example assumes you're using MySQL, but it can be adapted for
other databases with minor changes (like changing the connection
string and driver).
Creating the table:
 The SQL CREATE TABLE statement is used to create a table
named customer with columns id, name, email, and phone.
 The id is set as the primary key and is auto-incremented.
Inserting data:
 The INSERT INTO SQL statement adds two rows of customer data into
the customer table.
Retrieving data:
 The SELECT * FROM customer SQL query retrieves all the rows from
the customer table.
 The ResultSet object processes the retrieved data row by row.
JDBC Setup:
 The Connection object is used to manage the connection to
the database.
 A Statement object is used to execute SQL queries (like CREATE,
INSERT, SELECT).
Source code:
import
java.util.*;
import java.sql.*;
class Data
{
public static void main(String args[]) throws Exception
{
System.out.println("==========================");
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","admin");
Statement stmt=con.createStatement();
String sql1 = "CREATE TABLE secondyearitb67 " + "(stu_id INTEGER
not NULL, " +" stu_name VARCHAR(20), " + " stu_phno NUMBER(10),
" + " stu_addr VARCHAR(20)," + " PRIMARY KEY (stu_id ))";
stmt.executeUpdate(sql1);
System.out.println("Created table in given
database...");System.out.println("Goodbye!");
Scanner sc=new
Scanner(System.in); for(int
i=1;i<=2;i++)
{
System.out.println("enter student record-"+i);
int a=sc.nextInt();
String s=sc.next();
int mno=sc.nextInt();
String address=sc.next();
System.out.println("hi");
String sql2 = "INSERT INTO secondyearitb67 " + "VALUES
("+a+",'"+s+"',"+mno+",'"+address+"')";
stmt.executeUpdate(sql2);
}
System.out.println("inserted values in given database...");
System.out.println("Goodbye!");
ResultSet rs=stmt.executeQuery("select * from secondyearitb67");
while(rs.next())
{
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
System.out.println(rs.getString(4));
System.out.println("==========================");
}
con.close();
}
}
Output:
EXPERIMENT-25
Aim: Write a java program to handle jdbc resources via try with
resources and finally block to handle all kind of exceptions.
Description:
Using Java's try-with-resources statement simplifies resource
management for JDBC connections, as it automatically closes the
resources at the end of the try block. Here’s an example Java
program that uses try-with-resources along with a finally block
to manage JDBC resources and handle exceptions effectively.
This program will connect to a MySQL database, create a customer
table, insert some sample data, and retrieve the data from the table.
The program is designed to handle exceptions by catching
SQLException and other potential errors.
Try-with-Resources:
 The Connection, Statement, and ResultSet resources are
declared in the try-with-resources statements. This ensures
they are automatically closed at the end of the block,
whether an exception occurs or not.
Handling SQL Exceptions:
 If a SQLException occurs, the program catches it in the
catch (SQLException e) block and displays the error
message and stack trace for debugging.
Generic Exception Handling:
 A general catch (Exception e) block captures any
other unexpected exceptions and provides error
feedback.
Source code:
import java.sql.*;
class OracleData2
{
public static void main(String args[]) throws Exception
{
System.out.println("==========================");
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:152
1:xe","system","admin");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from customer15");
while(rs.next())
{
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
System.out.println(rs.getString(4));
System.out.println("==========================");
}
con.close();
}
}
Output:
EXPERIMENT-26
Aim: Write a set of 500 customers into the customer table of (24
experiment) in batches of 50 records each.
Description:
Define the Dataset: Prepare a list of 500 customer records, ensuring
that each record includes all the necessary fields required by the
customer table (e.g., CustomerID, Name, Email, Address, etc.).
Batch Creation: Split these 500 records into 10 smaller batches,
each containing exactly 50 records. This can be done manually or by
using a tool to divide the dataset.
Batch Insertion:
 Begin Transaction: For each batch, initiate a transaction to
ensure that either the entire batch is successfully added
or none are added in case of any error.
 Insert Records: Insert the 50 records of each batch into
the customer table. This process can be done with a single
SQL
INSERT statement per batch by listing each record's data as
part of the query.
 Commit Transaction: After the records for a batch are
inserted, commit the transaction to save these changes to the
database.
Error Handling: Monitor for any errors during the insertion. If an
error occurs within a batch, roll back the transaction for that batch,
ensuring data integrity.
Validation: Once all 10 batches have been successfully inserted, verify
that the customer table now contains all 500 new records.
Completion: Confirm the total insertion and validate the data quality
to ensure all records are properly formatted and aligned with the
table schema.
Source code:
import java.sql.*;
class OracleData3
{
public static void main(String args[]) throws Exception
{
System.out.println("==========================");
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:152
1:xe","system","admin");
Statement stmt=con.createStatement();
String sql = "CREATE TABLE CUSTOMER15 " + "(cust_id INTEGER not
NULL, " + " cust_name VARCHAR(20), " + " cust_phno NUMBER(10), "
+ " cust_addr VARCHAR(20)," + " PRIMARY KEY (cust_id ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
System.out.println("Goodbye!");
con.close();
}
}
Output:
EXPERIMENT-27
Aim: Print your date of birth using date format of India, Germany,
USA and find no of days you have lived.
Description:
Displaying Date in Various Formats
Assume the date of birth is 15th August 1990. Different countries
have different formats for representing dates. Here’s how we would
display it:
1. India (DD-MM-YYYY): 15-08-1990
2. Germany (DD.MM.YYYY): 15.08.1990
3. USA (MM/DD/YYYY): 08/15/1990
Step 2: Calculating Days Lived
To find out the number of days from 15th August 1990 until today:
1. Find the Current Date: Note today’s date (for example, let’s
say it’s 14th November 2024).
2. Calculate the Difference:
o Determine the number of years, months, and
days between the two dates.
o Calculate the total number of days, accounting for
leap years and varying month lengths.
3. Result: Sum up all these days to get the total number of
days lived.
Source code:
import java.sql.*;
class OracleData4
{
public static void main(String args[]) throws Exception
{
System.out.println("==========================");
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:152
1:xe","system","admin");
Statement stmt=con.createStatement();
String sql = "INSERT INTO customer15 " +"VALUES (188, 'Sri',
8985823456, 'vskp')";
stmt.executeUpdate(sql);
sql = "INSERT INTO customer15 " +"VALUES (89, 'Sai',
9642667949, 'hyd')";
stmt.executeUpdate(sql);
System.out.println("inserted values in given database...");
System.out.println("Goodbye!");
con.close();
}
}
Output:

……. ***THE END *** …….

You might also like