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

Java Programming Lab Manual

The document is a lab manual for a Java programming course at Aditya University, detailing various programming experiments for students. It includes a list of 31 programming tasks, ranging from finding prime numbers to implementing CRUD operations using JDBC. Each task is accompanied by a brief description and example code, aimed at enhancing students' practical understanding of Java programming concepts.

Uploaded by

Legend
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 views80 pages

Java Programming Lab Manual

The document is a lab manual for a Java programming course at Aditya University, detailing various programming experiments for students. It includes a list of 31 programming tasks, ranging from finding prime numbers to implementing CRUD operations using JDBC. Each task is accompanied by a brief description and example code, aimed at enhancing students' practical understanding of Java programming concepts.

Uploaded by

Legend
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

ADITYA UNIVERSITY

JAVA PROGRAMMING
LAB MANUAL
Course Code: 241IT006

Semester: IV Semester

Regulations : AR24
INDEX

[Link] Name Of The Experiment Page


No
1 Write a Java program which selects and prints all the prime numbers within 1
the range of 1 to 100.
2 Write a Java Program which finds the sum of all even terms in the Fibonacci 2
sequence up to the given range N.
3 Write a Java program to check whether a given number is Armstrong or 4
[Link] Armstrong number (also called a Narcissistic number) is a number
that is equal to the sum of its own digits raised to the power of the number of
digits.
4 Write a Java program to sort an array of integers in ascending order 6

5 write a java program to find the maximum and minimum element in an array 8

6 write a java program to remove the duplicate elements in the array 10

7 Write a Java Program to display the details of a person. Personal details 12


should be given in one method and the qualification details in another
method.
8 Write a Java Program to implement constructor and constructor overloading. 15

9 Write a Java Program to implement method overloading. 18

10 Write a java program to check whether the given string is pangram or not 20
(contains every letter of the alphabet atleast once)
11 Write a java program to find the most frequently occurring character in a 22
string.
12 Write a Java Program to find all permutations of a given string. 23

13 Write a Java Program to Check if a given string is a anagram (Ex: CAT and 24
ACT).
14 Write a java program implementing multi level Inheritance. 25

15 Write a Java Program to implement multiple Inheritance. 28

16 Write a Java program to find the areas of different shapes using abstract 30
classes.
[Link] Name Of The Experiment Page
No
17 Write a Java program to import and use user defined package. 32

18 Write a Java program to illustrate the use of protected members in a 33


package.
19 Write a java program to copy Even numbers into [Link] file and Odd 34
Numbers into [Link] file.

20 Write a java program to make use of ArrayList and LinkedList 36

21 Write a java program to make use of Iterator and Iterable 38

22 Write a java program to make use of Comparator and Comparable 39

23 Write a java program to make use of HashMap and TreeMap 41

24 Write a java program to make use of HashSet and TreeSet 43

25 Write a java program to make use of HashTable 45

26 Write a Java program to illustrate exception handling mechanism using 47


multiple catch clauses.
27 Write a Java program to Make use of Built-in and user-defined Exceptions 49
in handling a run time exception.
28 Write a Java program that creates threads by extending Thread class. First 52
thread display “Good Morning “every 1 sec, the second thread displays
“Hello “every 2 seconds and the third display “Welcome” every 3 seconds.
29 Write a Java program that creates threads by implementing Runnable 54
Interface. First thread display “Good Morning “every 1 sec, the second
thread displays “Hello “every 2 seconds and the third display “Welcome”
every 3 seconds.
30 Write a java program to solve Producer – Concumer problem using 56
synchronization
31 Write a Java program to implement CRUD operations on a Database using 59
JDBC API
Exp. No: Roll. No:
Date:

Program 1:
Write a Java program which selects and prints all the prime numbers within the range of
1 to 100.
Program:
[Link]:
public class PrimeNumbersAppl {
public static void main(String[] args)
{ [Link]("Prime numbers between 1 and 100
are:"); for (int num = 2; num <= 100; num++) {
boolean isPrime = true;
// Check if num is divisible by any number from 2 to num/2
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0)
{ isPrime = false;
break;
}
}
// Print num if it is
prime if (isPrime) {
[Link](num + " ");
}
}
}
}
Output:
Compilation: javac [Link]

Execution : java PrimeNumbersAppl

Prime numbers between 1 and 100 are:

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

ADITYA UNIVERSITY Page No:1


Exp. No: Roll. No:
Date:

Program 2:
Write a Java Program which finds the sum of all even terms in the Fibonacci sequence
up to the given range N.
Program:
[Link]:
import [Link];
public class EvenFibonacciSum {
public static void main(String[] args) {
int n,first = 0, second = 1,sum = 0,next;
Scanner sc = new Scanner([Link]);
[Link]("Enter the range : ");
n = [Link]();
[Link]("Fibonacci sequence up to " + n + ":");
// Print first term if within range
if(first <= n) {
[Link](first + " ");
}
if(second <= n)
{ [Link](second + " ");
}
while (true) {
next = first + second;
if (next > n) {
break;
}
// Print the term
[Link](next + " ");
// Add even term to sum
if (next % 2 == 0) {
sum += next;
}

ADITYA UNIVERSITY Page No:2


Exp. No: Roll. No:
Date:

first = second;
second = next;
}
[Link]("\nSum of even Fibonacci numbers up to " + n + " = " + sum);
}
}
Output:
Compilation: javac [Link]

Execution : java EvenFibonacciSum

Enter the range : 13

Fibonacci sequence up to 13:

0 1 1 2 3 5 8 13

Sum of even Fibonacci numbers up to 13 = 10

ADITYA UNIVERSITY Page No:3


Exp. No: Roll. No:
Date:

Program 3:
Write a Java program to check whether a given number is Armstrong or [Link]
Armstrong number (also called a Narcissistic number) is a number that is equal to the
sum of its own digits raised to the power of the number of digits.
Program:
[Link]:
import [Link];
public class ArmstrongNumber {
public static void main(String[] args)
{ int num,sum = 0,digits = 0,temp;
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
num = [Link]();
// Count digits
temp = num;
while (temp > 0)
{
digits++;
temp /= 10;
}
// Calculate Armstrong sum
temp = num;
while (temp > 0) {
int remainder = temp % 10;
sum += [Link](remainder, digits);
temp /= 10;
}
// Check condition
if (sum == num) {
[Link](num + " is an Armstrong number.");
} else {
[Link](num + " is NOT an Armstrong number.");
}
ADITYA UNIVERSITY Page No:4
Exp. No: Roll. No:
Date:

}
}

Output:
Compilation: javac [Link]

Execution : java ArmstrongNumber

Enter a number: 153

153 is an Armstrong number.

Execution : java ArmstrongNumber

Enter a number: 1634

1634 is an Armstrong number.

ADITYA UNIVERSITY Page No:5


Exp. No: Roll. No:
Date:

Program 4:
Write a Java program to sort an array of integers in ascending order
Program:
[Link]:
import [Link];
public class SortingAppl {
public static void main(String[] args)
{ Scanner sc = new
Scanner([Link]);
// Read array size
[Link]("Enter number of elements: ");
int n = [Link]();
int[] arr = new int[n];
// Read array elements
[Link]("Enter array elements:");
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}
[Link]("\nGiven order of elements:");
for (int i = 0; i < n; i++) {
[Link](arr[i] + " ");
}
// Bubble Sort logic
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++)
{ if (arr[j] > arr[j + 1]) {
// swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
ADITYA UNIVERSITY Page No:6
Exp. No: Roll. No:
Date:

// Display sorted array


[Link]("\nSorted array in ascending order:");
for (int i = 0; i < n; i++) {
[Link](arr[i] + " ");
}
}
}
Output:
Compilation: javac [Link]

Execution : java SortingAppl

Enter number of elements: 8

Enter array elements:

10

92

32

86

34

45

23

Given order of elements:

10 2 92 32 86 34 45 23

Sorted array in ascending order:

2 10 23 32 34 45 86 92

ADITYA UNIVERSITY Page No:7


Exp. No: Roll. No:
Date:

Program 5:
write a java program to find the maximum and minimum element in an array
Program:
[Link]:
import [Link];
public class MaxMinArray {
public static void main(String[] args)
{ Scanner sc = new
Scanner([Link]);
// Read array size
[Link]("Enter number of elements: ");
int n = [Link]();
int[] arr = new int[n];
// Read array elements
[Link]("Enter array elements:");
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}
// Display given order of elements
[Link]("\nGiven array elements:");
for (int i = 0; i < n; i++) {
[Link](arr[i] + " ");
}
// Initialize max and min with first element
int max = arr[0];
int min = arr[0];
// Find maximum and minimum
for (int i = 1; i < n; i++) {
if (arr[i] > max)
{ max = arr[i];
}
if (arr[i] < min)
{ min = arr[i];
ADITYA UNIVERSITY Page No:8
Exp. No: Roll. No:
Date:

}
}
// Display results
[Link]("\n\nMaximum element = " + max);
[Link]("Minimum element = " + min);
}
}
Output:
Compilation: javac [Link]

Execution : java MaxMinArray

Enter number of elements: 5

Enter array elements:

12

78

34

45

Given array elements:

12 3 78 34 45

Maximum element = 78

Minimum element = 3

ADITYA UNIVERSITY Page No:9


Exp. No: Roll. No:
Date:

Program 6:
write a java program to remove the duplicate elements in the array
Program:
[Link]:
import [Link];
public class RemDupArray {
public static void main(String[] args)
{ Scanner sc = new
Scanner([Link]);
// Read array size
[Link]("Enter number of elements: ");
int n = [Link]();
int[] arr = new int[n];
int[] brr = new int[n];
// Read array elements
[Link]("Enter array elements:");
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}
// Display given order of elements
[Link]("\nGiven array elements:");
for (int i = 0; i < n; i++) {
[Link](arr[i] + " ");
}
int newSize = 0;
for (int i = 0; i < n; i++)
{ boolean isDup = false;
for (int j = 0; j < newSize; j++)
{ if (arr[i] == brr[j]) {
isDup = true;
break;
}
}
ADITYA UNIVERSITY Page No:10
Exp. No: Roll. No:
Date:

if (!isDup)
{ brr[newSize] =
arr[i]; newSize++;
}
}
[Link]("\nGiven array elements after removing duplicates:");
for (int i = 0; i < newSize; i++) {
[Link](brr[i] + " ");
}
}
}
Output:
Compilation: javac [Link]
Execution : java RemDupArray

Enter number of elements: 8

Enter array elements:

10

20

30

20

40

10

80

60

Given array elements:


10 20 30 20 40 10 80 60
Given array elements after removing duplicates:
10 20 30 40 80 60

ADITYA UNIVERSITY Page No:11


Exp. No: Roll. No:
Date:

Program 7:
Write a Java Program to display the details of a person. Personal details should be given
in one method and the qualification details in another method.
Program:
[Link]:
import [Link];
class Person{
String name, gender, city;
int age;
String degree, branch, university;
int year;
Scanner sc = new Scanner([Link]);
void readPersonalDetails() {
[Link]("Enter Personal Details:");
[Link]("Name: ");
name = [Link]();
[Link]("Age: ");
age = [Link]();
[Link]();
[Link]("Gender: ");
gender = [Link]();
[Link]("City: ");
city = [Link]();
}
void readQualificationDetails() { [Link]("\
nEnter Qualification Details:");
[Link]("Degree: ");
degree = [Link]();
[Link]("Branch: ");
branch = [Link]();
[Link]("University: ");
university = [Link]();

ADITYA UNIVERSITY Page No:12


Exp. No: Roll. No:
Date:

[Link]("Year of Passing: ");


year = [Link]();
}
void displayPersonalDetails()
{ [Link]("\nPersonal
Details:"); [Link]("Name : "
+ name); [Link]("Age :"+
age); [Link]("Gender : " +
gender); [Link]("City : " +
city);
}
void displayQualificationDetails()
{ [Link]("\nQualification
Details:"); [Link]("Degree
: " + degree);
[Link]("Branch : " + branch);
[Link]("University : " + university);
[Link]("Year : " + year);
}
public static void main(String[] args)
{ Person p = new Person();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Output:
Compilation: javac [Link]

Execution : java Person


Enter Personal Details:
Name: Chakri
Age: 41

ADITYA UNIVERSITY Page No:13


Exp. No: Roll. No:
Date:
Gender: Male
City: Kakinada

ADITYA UNIVERSITY Page No:14


Exp. No: Roll. No:
Date:

Enter Qualification Details:


Degree: [Link]
Branch: CSE
University: JNTUK
Year of Passing: 2006
Personal Details:
Name : Chakri
Age : 41
Gender : Male
City : Kakinada
Qualification
Details: Degree:
[Link] Branch: CSE
University : JNTUK
Year 2006

ADITYA UNIVERSITY Page No:15


Exp. No: Roll. No:
Date:

Program 8:
Write a Java Program to implement constructor and constructor overloading.
Program:
[Link]:
class Student
{ String
name; int
age; String
course;
// Default constructor
Student() {
name = "Not Assigned";
age = 0;
course = "Not Selected";
}
// Constructor with one parameter
Student(String n) {
name = n;
age = 0;
course = "Not Selected";
}
// Constructor with two parameters
Student(String n, int a) {
name = n;
age = a;
course = "Not Selected";
}
// Constructor with three parameters
Student(String n, int a, String c) {
name = n;
age = a;
course = c;

ADITYA UNIVERSITY Page No:16


Exp. No: Roll. No:
Date:
}

ADITYA UNIVERSITY Page No:17


Exp. No: Roll. No:
Date:

void display() {
[Link]("Name : " + name);
[Link]("Age : " + age);
[Link]("Course : " + course);
[Link]();
}
public static void main(String[] args) {
Student s1 = new Student(); // default constructor
Student s2 = new Student("Ravi"); // one parameter
Student s3 = new Student("Anita", 20); // two parameters
Student s4 = new Student("Kiran", 22, "Java"); // three parameters
[Link]("Student details created with default
constructor"); [Link]();
[Link]("Student details created with parameterised constructor(String)");
[Link]();
[Link]("Student details created with parameterised constructor(String,int)");
[Link]();
[Link]("Student details created with parameterised
constructor(String,int,String)");
[Link]();
}
}
Output:
Compilation: javac [Link]

Execution : java Student

Student details created with default constructor

Name : Not Assigned

Age :0

Course : Not Selected

Student details created with parameterised constructor(String)

Name : Ravi

ADITYA UNIVERSITY Page No:18


Exp. No: Roll. No:
Date:

Age :0

Course : Not Selected

Student details created with parameterised constructor(String,int)

Name : Anita

Age : 20

Course : Not Selected

Student details created with parameterised constructor(String,int,String)

Name : Kiran

Age : 22

Course : Java

ADITYA UNIVERSITY Page No:19


Exp. No: Roll. No:
Date:

Program 9:
Write a Java Program to implement method overloading.
Program:
[Link]:
class MethodOverloadingAppl {
// Method with two integer parameters
int add(int a, int b) {
[Link]("add(int, int) method is used");
return a + b;
}
// Method with three integer parameters
int add(int a, int b, int c) {
[Link]("add(int, int, int) method is used");
return a + b + c;
}
// Method with two double parameters
double add(double a, double b) {
[Link]("add(double, double) method is used");
return a + b;
}
// Method with int and double parameters
double add(int a, double b) {
[Link]("add(int, double) method is used");
return a + b;
}
// Method with double and int parameters
double add(double a, int b) {
[Link]("add(double, int) method is used");
return a + b;
}

ADITYA UNIVERSITY Page No:20


Exp. No: Roll. No:
Date:

public static void main(String[] args) {


MethodOverloadingAppl obj = new MethodOverloadingAppl();
int sum1 = [Link](10, 20);
[Link]("Returned Sum: " + sum1 + "\n");
int sum2 = [Link](5, 10, 15);
[Link]("Returned Sum: " + sum2 + "\n");
double sum3 = [Link](10.5, 20.3);
[Link]("Returned Sum: " + sum3 + "\n");
double sum4 = [Link](10, 20.5);
[Link]("Returned Sum: " + sum4 + "\n");
double sum5 = [Link](15.5, 10);
[Link]("Returned Sum: " + sum5);
}
}

Output:
Compilation: javac [Link]

Execution : java MethodOverloadingAppl


add(int, int) method is used

Returned Sum: 30

add(int, int, int) method is used

Returned Sum: 30

add(double, double) method is used

Returned Sum: 30.8

add(int, double) method is used

Returned Sum: 30.5

add(double, int) method is used

Returned Sum: 25.5

ADITYA UNIVERSITY Page No:21


Exp. No: Roll. No:
Date:

Program 10:
Write a java program to check whether the given string is pangram or not (contains every
letter of the alphabet atleast once)
Program:
[Link]:
import [Link];
public class PangramCheck {
public static void main(String[] args)
{ Scanner sc = new Scanner([Link]);
[Link]("Enter a sentence: ");
String str = [Link]().toLowerCase();
boolean[] alphabet = new boolean[26];
int index;
for (int i = 0; i < [Link](); i++)
{ char ch = [Link](i);
if (ch >= 'a' && ch <= 'z')
{ index = ch - 'a';
alphabet[index] = true;
}
}
boolean isPangram = true;
for (int i = 0; i < 26; i++) {
if (!alphabet[i])
{ isPangram = false;
break;
}
}
if (isPangram)
[Link]("The given string is a Pangram.");
else
[Link]("The given string is NOT a Pangram.");

ADITYA UNIVERSITY Page No:22


Exp. No: Roll. No:
Date:

[Link]();
}
}
O
u
t
p
u
t
:
Compilation: javac [Link]

Execution : java PangramCheck

Enter a sentence: The quick brown fox jumps over the lazy dog

The given string is a Pangram.

Execution : java PangramCheck

Enter a sentence: hello students how are you

The given string is NOT a Pangram.

ADITYA UNIVERSITY Page No:23


Exp. No: Roll. No:
Date:

Program 11:
Write a java program to find the most frequently occurring character in a string.
Program:
[Link]:
import [Link];
public class MostFrequentCharacter
{ public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();
int maxCount = 0;
char maxChar = ' ';
for (int i = 0; i < [Link](); i++)
{ int count = 0;
for (int j = 0; j < [Link](); j++)
{ if ([Link](i) == [Link](j))
{
count++;
}
}
if (count > maxCount)
{ maxCount = count;
maxChar = [Link](i);
}
}
[Link]("Most frequent character: " +
maxChar); [Link]("Frequency: " + maxCount);
[Link]();
}
}
Output:
Compilation: javac [Link]
Execution : java MostFrequentCharacter
Enter a string: Java Programming
Most frequent character: a

ADITYA UNIVERSITY Page No:24


Exp. No: Roll. No:
Date:
Frequency: 3

ADITYA UNIVERSITY Page No:25


Exp. No: Roll. No:
Date:

Program 12:
Write a Java Program to find all permutations of a given string.
Program:
[Link]:
import [Link];
public class StringPermutations {
// Method to generate permutations
public static void permute(String str, String result)
{ if ([Link]() == 0) {
[Link](result);
return;
}
for (int i = 0; i < [Link](); i++)
{ char ch = [Link](i);
// Remaining string after removing the selected character
String remaining = [Link](0, i) + [Link](i + 1);
permute(remaining, result + ch);
}
}
public static void main(String[] args)
{ Scanner sc = new
Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();
[Link]("Permutations of the string are:");
permute(str, "");
[Link]();
}
}
O
u
t
p
u
t
:
Compilation: javac [Link]
Execution : java StringPermutations
Enter a string: abc
Permutations of the string are:
abc
acb

ADITYA UNIVERSITY Page No:26


Exp. No: Roll. No:
Date:
bac
bca
cab
cba

ADITYA UNIVERSITY Page No:27


Exp. No: Roll. No:
Date:

Program 13:
Write a Java Program to Check if a given string is a anagram (Ex: CAT and ACT).
Program:
[Link]:
import [Link];
import [Link];
public class AnagramCheck {
public static void main(String[] args)
{ Scanner sc = new Scanner([Link]);
[Link]("Enter first string: ");
String str1 = [Link]();
[Link]("Enter second string: ");
String str2 = [Link]();
// Convert strings to
lowercase str1 =
[Link](); str2 =
[Link]();
// Convert strings to character arrays
char[] arr1 = [Link]();
char[] arr2 = [Link]();
// Sort both arrays
[Link](arr1);
[Link](arr2);
// Compare arrays
if ([Link](arr1, arr2))
[Link]("The given strings are Anagrams.");
else
[Link]("The given strings are NOT Anagrams.");
[Link]();
}
}
O
u
t
p
u
t
:
Compilation: javac [Link]
Execution : java AnagramCheck
Enter first string: LISTEN
Enter second string: SILENT
ADITYA UNIVERSITY Page No:28
Exp. No: Roll. No:
Date:
The given strings are Anagrams.
Execution : java AnagramCheck
Enter first string: CAT
Enter second string: MAT
The given strings are NOT Anagrams.

ADITYA UNIVERSITY Page No:29


Exp. No: Roll. No:
Date:

Program 14:
Write a java program implementing multi level Inheritance.
Program:
[Link]:
class Person {
protected String name;
protected int age;
// Constructor
Person(String name, int age)
{ [Link] = name;
[Link] = age;
[Link]("Person constructor called");
}
// Method
public void displayDetails()
{ [Link]("Name: " +
name); [Link]("Age: " +
age);
}
// final method (cannot be overridden)
public final void showCategory() {
[Link]("Category: Human");
}
}
class Employee extends Person
{ protected int empId;
protected double salary;
Employee(String name, int age, int empId, double salary) {
super(name, age); // calling parent constructor
[Link] = empId;
[Link] = salary;
[Link]("Employee constructor called");
}
ADITYA UNIVERSITY Page No:30
Exp. No: Roll. No:
Date:

// Method overriding
public void displayDetails()
{ [Link](); // calling parent
method [Link]("Employee ID: " +
empId); [Link]("Salary: " + salary);
}
public void work() {
[Link](name + " is working as an employee");
}
}
class Manager extends Employee
{ private String department;
Manager(String name, int age, int empId, double salary, String department)
{ super(name, age, empId, salary); // calling Employee constructor
[Link] = department;
[Link]("Manager constructor called");
}
// Method overriding
public void displayDetails() {
[Link](); // calling Employee version
[Link]("Department: " + department);
}
public void manageTeam() {
[Link](name + " is managing " + department + " department");
}
}
public class MultilevelInheritanceDemo
{ public static void main(String[] args) {
// Creating Manager object
Manager m = new Manager("Kiran", 35, 101, 75000,
"IT"); [Link]("\n--- Display Details ---");
[Link]();

ADITYA UNIVERSITY Page No:31


Exp. No: Roll. No:
Date:

[Link]("\n--- Calling methods ---");


[Link]();
[Link]();
[Link]();
[Link]("\n--- Dynamic Method Dispatch ---");
Person p = new Manager("Ravi", 40, 102, 90000, "HR");
[Link](); // runtime polymorphism
}
}

Output:
Compilation: javac [Link]

Execution : java MultilevelInheritanceDemo

Person constructor called


Employee constructor called
Manager constructor called
--- Display Details ---
Name: Kiran
Age: 35
Employee ID: 101
Salary: 75000.0
Department: IT
--- Calling methods ---
Kiran is working as an employee
Kiran is managing IT department
Category: Human

--- Dynamic Method Dispatch ---


Person constructor called
Employee constructor called
Manager constructor called
Name: Ravi
Age: 40
Employee ID: 102
Salary: 90000.0
Department: HR

ADITYA UNIVERSITY Page No:32


Exp. No: Roll. No:
Date:

Program 15:
Write a Java Program to implement multiple Inheritance.
Program:
[Link]:
// First interface
interface Teacher {
int hours = 5; // public static final by default
void teach(); // public abstract by default
}
// Second interface
interface Researcher {
int papers = 10;
void doResearch();
}
// Class implementing multiple interfaces
class Professor implements Teacher, Researcher
{ String name;
// Constructor
Professor(String name) {
[Link] = name;
}
// Implement Teacher method
public void teach() {
[Link](name + " teaches for " + hours + " hours per day");
}
// Implement Researcher method
public void doResearch() {
[Link](name + " publishes " + papers + " research papers");
}
// Own method
public void display()
{ [Link]("Professor Name: " +

ADITYA UNIVERSITY Page No:33


Exp. No: Roll. No:
Date:
name);

ADITYA UNIVERSITY Page No:34


Exp. No: Roll. No:
Date:

}
}
// Main class
public class MultipleInheritanceDemo
{ public static void main(String[] args)
{ Professor p = new
Professor("Kiran"); [Link]();
[Link]();
[Link]();
}
}
O
u
t
p
u
t
:
Compilation: javac [Link]

Execution : java MultipleInheritanceDemo

Professor Name: Kiran

Kiran teaches for 5 hours per day

Kiran publishes 10 research papers

ADITYA UNIVERSITY Page No:35


Exp. No: Roll. No:
Date:

Program 16:
Write a Java program to find the areas of different shapes using abstract classes.
Program:
[Link]:
// Abstract class
abstract class Shape {
// Abstract method (no body)
abstract void calculateArea();
}
// Circle class
class Circle extends Shape
{ double radius;
// Constructor
Circle(double radius) {
[Link] = radius;
}
// Implement abstract method
void calculateArea() {
double area = [Link] * radius * radius;
[Link]("Area of Circle = " + area);
}
}
// Rectangle class
class Rectangle extends Shape {
double length, width;
// Constructor
Rectangle(double length, double width) {
[Link] = length;
[Link] = width;
}
// Implement abstract method
void calculateArea() {

ADITYA UNIVERSITY Page No:36


Exp. No: Roll. No:
Date:

double area = length * width;


[Link]("Area of Rectangle = " + area);
}
}
// Triangle class
class Triangle extends Shape
{ double base, height;
// Constructor
Triangle(double base, double height)
{ [Link] = base;
[Link] = height;
}
// Implement abstract method
void calculateArea() {
double area = 0.5 * base * height;
[Link]("Area of Triangle = " + area);
}
}
// Main class
public class AbstractShapeDemo {
public static void main(String[] args)
{
// Using runtime polymorphism
Shape s;
s = new Circle(5);
[Link]();
s = new Rectangle(4, 6);
[Link]();
s = new Triangle(3, 8);
[Link]();
}
}
O
u
t
p
u
t
:
Compilation: javac [Link]
ADITYA UNIVERSITY Page No:37
Exp. No: Roll. No:
Date:

Execution : java AbstractShapeDemo


Area of Circle = 78.53981633974483
Area of Rectangle = 24.0
Area of Triangle = 12.0

ADITYA UNIVERSITY Page No:38


Exp. No: Roll. No:
Date:

Program 17:
Write a Java program to import and use user defined package.
Program:
[Link]:
package pack1; // package declaration
public class Calculator {
public int add(int a, int b)
{ return a + b;
}
public int sub(int a, int b)
{ return a - b;
}
}
[Link]:
package pack2;
import [Link];
class Test
{
public static void main(String args[])
{
Calculator c=new Calculator();
[Link]("addition is:" + [Link](10,20));
[Link]("Substraction is:" + [Link](20,10));
}
}
Output:
Compilation: javac -d . [Link]
Compilation: javac -d . [Link]
Execution : java [Link]

addition is:30

Substraction is:10

ADITYA UNIVERSITY Page No:39


Exp. No: Roll. No:
Date:

Program 18:

Write a Java program to illustrate the use of protected members in a package.


Program:
[Link]:
package pack1;
public class Base {
protected int num = 50;
protected void display() {
[Link]("Protected number: " + num);
}
}
[Link]:
package pack2;
import [Link];
public class Derived extends Base
{ public static void main(String[] args)
{
Derived obj = new Derived();
// Accessing protected member through inheritance
[Link]("Value of num: " + [Link]);
[Link]();
}
}
O
u
t
p
u
t
:
Compilation: javac -d . *.java

Execution : java [Link]

Value of num: 50

Protected number: 50

ADITYA UNIVERSITY Page No:40


Exp. No: Roll. No:
Date:

Program 19:
Write a java program to copy Even numbers into [Link] file and Odd Numbers into
[Link] file.
Program:
[Link]:
import [Link].*;
import [Link].*;
public class EvenOddFileCopy {
public static void main(String[] args) {
try {
// Input file containing numbers
File inputFile = new File("[Link]");
Scanner sc = new Scanner(inputFile);
// Writers for even and odd files
FileWriter evenWriter = new FileWriter("[Link]");
FileWriter oddWriter = new FileWriter("[Link]");
while ([Link]()) {
int num = [Link]();
if (num % 2 == 0) {
[Link](num + " ");
} else {
[Link](num + " ");
}
}
[Link]();
[Link]();
[Link]();
[Link]("Numbers copied successfully!");
} catch (Exception e) {
[Link](e);
}
}

ADITYA UNIVERSITY Page No:41


Exp. No: Roll. No:
Date:

}
Output:
Compilation: javac [Link]

Execution : java EvenOddFileCopy

Numbers copied successfully!

[Link]:

1
2
3
4
5
6
7
8
9
10

[Link]:

2 4 6 8 10

[Link]:

1 3 5 7 9

ADITYA UNIVERSITY Page No:42


Exp. No: Roll. No:
Date:

Program 20:
Write a java program to make use of ArrayList and LinkedList
Program:
[Link]:
import [Link];
import [Link];
public class ListExample {
public static void main(String[] args) {
// Creating an ArrayList
ArrayList<String> arrayList = new ArrayList<>();
// Adding elements to ArrayList
[Link]("Apple");
[Link]("Banana");
[Link]("Mango");
[Link]("Orange");
[Link]("Elements in ArrayList:");
for (String fruit : arrayList) {
[Link](fruit);
}
// Removing an element
[Link]("Banana");
[Link]("ArrayList after removing Banana: " + arrayList);
// Creating a LinkedList
LinkedList<String> linkedList = new LinkedList<>();
// Adding elements to LinkedList
[Link]("Red");
[Link]("Green");
[Link]("Blue");
[Link]("Yellow");
[Link]("\nElements in LinkedList:");
for (String color : linkedList) {
[Link](color);

ADITYA UNIVERSITY Page No:43


Exp. No: Roll. No:
Date:

}
// Adding element at first position
[Link]("Black");

// Removing last element


[Link]();

[Link]("LinkedList after modifications: " + linkedList);


}
}
O
u
t
p
u
t
:
Compilation: javac [Link]

Execution : java ListExample

Elements in ArrayList:

Apple

Banana

Mango

Orange

ArrayList after removing Banana: [Apple, Mango, Orange]

Elements in LinkedList:

Red

Green

Blue

Yellow

LinkedList after modifications: [Black, Red, Green, Blue]

ADITYA UNIVERSITY Page No:44


Exp. No: Roll. No:
Date:

Program 21:
Write a java program to make use of Iterator and Iterable
Program:
[Link]:
import [Link];
import [Link];
public class IteratorExample {
public static void main(String[] args) {
// Creating an ArrayList (Collection implementing Iterable)
ArrayList<String> names = new ArrayList<>();
// Adding elements
[Link]("Ravi");
[Link]("Anil");
[Link]("Kiran");
[Link]("Sita");
// Getting the iterator
Iterator<String> it =
[Link]();
[Link]("Elements in the list:");
// Traversing the list using Iterator
while([Link]()) {
String name = [Link]();
[Link](name);
}
}
}
Output:
Compilation: javac [Link]

Execution : java IteratorExample

Elements in the list:


Ravi
Anil
Kiran
ADITYA UNIVERSITY Page No:45
Exp. No: Roll. No:
Date:
Sita

ADITYA UNIVERSITY Page No:46


Exp. No: Roll. No:
Date:

Program 22:
Write a java program to make use of Comparator and Comparable
Program:
[Link]:
import [Link].*;
// Student class implementing Comparable
class Student implements Comparable<Student>
{ int id;
String name;
Student(int id, String name) {
[Link] = id;
[Link] = name;
}
// Comparable method - sort by ID
public int compareTo(Student s) {
return [Link] - [Link];
}
}
// Comparator class to sort by Name
class NameComparator implements Comparator<Student>
{ public int compare(Student s1, Student s2) {
return [Link]([Link]);
}
}
public class ComparatorComparableExample
{ public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<>();
[Link](new Student(101, "Ravi"));
[Link](new Student(102, "Kiran"));
[Link](new Student(103, "Anil"));
// Sorting using Comparable (by ID)
[Link](list);

ADITYA UNIVERSITY Page No:47


Exp. No: Roll. No:
Date:

[Link]("Sorting by ID (Comparable):");
for (Student s : list) {
[Link]([Link] + " " + [Link]);
}
// Sorting using Comparator (by Name)
[Link](list, new NameComparator());
[Link]("\nSorting by Name (Comparator):");
for (Student s : list) {
[Link]([Link] + " " + [Link]);
}
}
}
Output:
Compilation: javac [Link]

Execution : java ComparatorComparableExample

Sorting by ID (Comparable):

101 Ravi

102 Kiran

103 Anil

Sorting by Name (Comparator):

103 Anil

102 Kiran

101 Ravi

ADITYA UNIVERSITY Page No:48


Exp. No: Roll. No:
Date:

Program 23:
Write a java program to make use of HashMap and TreeMap
Program:
[Link]:
import [Link].*;
public class MapExample {
public static void main(String[] args) {
// HashMap example
HashMap<Integer, String> hmap = new HashMap<>();
[Link](45, "Ravi");
[Link](12, "Anil");
[Link](78, "Kiran");
[Link](3, "Sita");
[Link](90, "Ram");
[Link](17, "Latha");
[Link]("HashMap Output (No ordering):");
for ([Link]<Integer, String> entry : [Link]())
{ [Link]([Link]() + " : " + [Link]());
}
// TreeMap example
TreeMap<Integer, String> tmap = new TreeMap<>();
[Link](45, "Ravi");
[Link](12, "Anil");
[Link](78, "Kiran");
[Link](3, "Sita");
[Link](90, "Ram");
[Link](17, "Latha");
[Link]("\nTreeMap Output (Sorted by keys):");
for ([Link]<Integer, String> entry : [Link]()) {
[Link]([Link]() + " : " + [Link]());
}
}

ADITYA UNIVERSITY Page No:49


Exp. No: Roll. No:
Date:

}
Output:
Compilation: javac [Link]

Execution : java MapExample

HashMap Output (No ordering):

17 : Latha

3 : Sita

90 : Ram

12 : Anil

45 : Ravi

78 : Kiran

TreeMap Output (Sorted by keys):

3 : Sita

12 : Anil

17 : Latha

45 : Ravi

78 : Kiran

90 : Ram

ADITYA UNIVERSITY Page No:50


Exp. No: Roll. No:
Date:

Program 24:
Write a java program to make use of HashSet and TreeSet
Program:
[Link]:
import [Link];
import [Link];
public class SetExample {
public static void main(String[] args) {
// Creating HashSet
HashSet<Integer> hset = new HashSet<>();
[Link](45);
[Link](12);
[Link](78);
[Link](3);
[Link](90);
[Link](17);
[Link]("HashSet Output (No ordering):");
for(Integer num : hset)
{
[Link](num + " ");
}
[Link]("\n");
// Creating TreeSet
TreeSet<Integer> tset = new TreeSet<>();
[Link](45);
[Link](12);
[Link](78);
[Link](3);
[Link](90);
[Link](17);
[Link]("TreeSet Output (Sorted order):");
for(Integer num : tset)

ADITYA UNIVERSITY Page No:51


Exp. No: Roll. No:
Date:

{
[Link](num + " ");
}
}
}
O
u
t
p
u
t
:
Compilation: javac [Link]

Execution : java SetExample

HashSet Output (No ordering):

17 3 90 12 45 78

TreeSet Output (Sorted order):

3 12 17 45 78 90

ADITYA UNIVERSITY Page No:52


Exp. No: Roll. No:
Date:

Program 25:
Write a java program to make use of HashTable
Program:
[Link]:
import [Link];
import [Link];
public class HashTableExample {
public static void main(String[] args) {
// Creating a Hashtable
Hashtable<Integer, String> ht = new Hashtable<>();
// Adding key-value pairs
[Link](101, "Ravi");
[Link](102, "Anil");
[Link](103, "Kiran");
[Link](104, "Sita");
[Link]("Elements in Hashtable:");
// Traversing Hashtable using [Link]
for ([Link]<Integer, String> entry : [Link]())
{ [Link]([Link]() + " : " + [Link]());
}
// Checking a key
if ([Link](102)) {
[Link]("\nKey 102 exists in Hashtable");
}
// Removing an element
[Link](103);
[Link]("\nHashtable after removing key 103:");
for ([Link]<Integer, String> entry : [Link]()) {
[Link]([Link]() + " : " + [Link]());
}
}
}

ADITYA UNIVERSITY Page No:53


Exp. No: Roll. No:
Date:

Output:
Compilation: javac [Link]

Execution : java HashTableExample

Elements in Hashtable:

104 : Sita

103 : Kiran

102 : Anil

101 : Ravi

Key 102 exists in Hashtable

Hashtable after removing key 103:

104 : Sita

102 : Anil

101 : Ravi

ADITYA UNIVERSITY Page No:54


Exp. No: Roll. No:
Date:

Program 26:
Write a Java program to illustrate exception handling mechanism using multiple catch
clauses.
Program:
[Link]:
import [Link];
public class MultipleCatchDemo {
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
double arr[] = new double[5];
try {
// Division part
[Link]("Enter first number:");
int a = [Link]();
[Link]("Enter second
number:"); int b = [Link]();
int result = a / b; // ArithmeticException possible
[Link]("Result = " + result);
// Array access part
[Link]("Enter array index where you want to store the above result:");
int index = [Link]();
arr[index]=result;
[Link]("Result: "+ result +" stored at index: " + index);
// ArrayIndexOutOfBoundsException possible
}
catch (ArithmeticException e)
{ [Link]("Error: Cannot divide by zero.");
}
catch (ArrayIndexOutOfBoundsException e)
{ [Link]("Error: Invalid array index entered.");
}
catch (Exception e) {

ADITYA UNIVERSITY Page No:55


Exp. No: Roll. No:
Date:
[Link]("General Exception Occurred.");

ADITYA UNIVERSITY Page No:56


Exp. No: Roll. No:
Date:

}
finally {
[Link]("in finally block");
}
[Link]();
[Link]("program execution completed");
}
}
O
u
t
p
u
t
:
Compilation: javac [Link]

Execution : java MultipleCatchDemo

Enter first number:


10
Enter second number:
0
Error: Cannot divide by zero.
in finally block
program execution completed

Execution : java MultipleCatchDemo

Enter first number:


10
Enter second number:
2
Result = 5
Enter array index where you want to store the above
result: 7
Error: Invalid array index entered.
in finally block
program execution completed

Execution : java MultipleCatchDemo

Enter first number:


10
Enter second number:
2
Result = 5
ADITYA UNIVERSITY Page No:57
Exp. No: Roll. No:
Date:
Enter array index where you want to store the above
result: 2
Result: 5 stored at index: 2
in finally block
program execution completed

ADITYA UNIVERSITY Page No:58


Exp. No: Roll. No:
Date:

Program 27:
Write a Java program to Make use of Built-in and user-defined Exceptions in handling a
run time exception.
Program:
[Link]:
import [Link];
// User-defined Exception
class InsufficientFundsException extends Exception
{ public InsufficientFundsException(String message) {
super(message);
}
}
// Bank Account Class
class BankAccount {
double balance;
BankAccount(double balance) {
[Link] = balance;
}
void withdraw(double amount)throws InsufficientFundsException
{ if (amount > balance) {
throw new InsufficientFundsException("Insufficient balance in account.");
} else {
balance = balance - amount;
[Link]("Withdrawal successful.");
[Link]("Remaining Balance = " + balance);

}
}
}
// Main Class
public class BankApplication {
public static void main(String[] args) {

ADITYA UNIVERSITY Page No:59


Exp. No: Roll. No:
Date:

Scanner sc = new Scanner([Link]);


boolean txStatus=false;
try {
// Taking input as String (for NumberFormatException)
[Link]("Enter initial balance:");
String balInput = [Link]();
double balance = [Link](balInput);
BankAccount account = new BankAccount(balance);
[Link]("Enter amount to withdraw:");
String amtInput = [Link]();
double amount = [Link](amtInput);
[Link](amount);
txStatus=true;
}
// User-defined Exception
catch (InsufficientFundsException e) {
[Link]("User Defined Exception: " + [Link]());
}
// Built-in Exception
catch (NumberFormatException e) {
[Link]("Built-in Exception: Invalid numeric input.");
}
// General Exception
catch (Exception e) {
[Link]("Some other exception occurred.");
}
finally {
if(txStatus)

[Link]("Bank transaction completed Successfully");


else
[Link]("Bank transaction was Unsuccessfull");
}
[Link]();

ADITYA UNIVERSITY Page No:60


Exp. No: Roll. No:
Date:

}
}
Output:
Compilation: javac [Link]

Execution : java BankApplication

Enter initial balance:


5000
Enter amount to withdraw:
7000
User Defined Exception: Insufficient balance in account.
Bank transaction was Unsuccessfull

Execution : java BankApplication

Enter initial balance:


5000
Enter amount to withdraw:
2000aa
Built-in Exception: Invalid numeric input.
Bank transaction was Unsuccessfull

Execution : java BankApplication

Enter initial balance:


5000
Enter amount to withdraw:
3000
Withdrawal successful.
Remaining Balance = 2000.0
Bank transaction completed Successfully

ADITYA UNIVERSITY Page No:61


Exp. No: Roll. No:
Date:

Program 28:
Write a Java program that creates threads by extending Thread class. First thread display
“Good Morning “every 1 sec, the second thread displays “Hello “every 2 seconds and
the third display “Welcome” every 3 seconds.
Program:
[Link]:
class GoodMorningThread extends Thread
{ public void run() {
try {
while (true) {
[Link]("Good Morning");
[Link](1000); // 1 second
}
} catch (InterruptedException e) {
[Link](e);
}
}
}
class HelloThread extends Thread
{ public void run() {
try {
while (true) {
[Link]("Hello");
[Link](2000); // 2 seconds
}
} catch (InterruptedException e) {
[Link](e);
}
}
}
class WelcomeThread extends Thread
{ public void run() {

ADITYA UNIVERSITY Page No:62


Exp. No: Roll. No:
Date:

try {
while (true) {
[Link]("Welcome");
[Link](3000); // 3 seconds
}
} catch (InterruptedException e) {
[Link](e);
}
}
}
public class ThreadExample {
public static void main(String[] args)
{ GoodMorningThread t1 = new
GoodMorningThread(); HelloThread t2 = new
HelloThread();
WelcomeThread t3 = new WelcomeThread();
[Link]();
[Link]();
[Link]();
}
}
Output:
Compilation: javac [Link]

Execution : java ThreadExample

Good Morning
Welcome
Hello
Good Morning
Hello
Good Morning
Welcome
Good Morning
Hello
Good Morning
Good Morning
Hello
^C

ADITYA UNIVERSITY Page No:63


Exp. No: Roll. No:
Date:

Program 29:
Write a Java program that creates threads by implementing Runnable Interface. First
thread display “Good Morning “every 1 sec, the second thread displays “Hello “every 2
seconds and the third display “Welcome” every 3 seconds.
Program:
[Link]:
class GoodMorningRunnable implements Runnable {
public void run() {
try {
while (true) {
[Link]("Good Morning");
[Link](1000); // 1 second
}
} catch (InterruptedException e) {
[Link](e);
}
}
}
class HelloRunnable implements Runnable
{ public void run() {
try {
while (true) {
[Link]("Hello");
[Link](2000); // 2 seconds
}
} catch (InterruptedException e) {
[Link](e);
}
}
}
class WelcomeRunnable implements Runnable
{ public void run() {

ADITYA UNIVERSITY Page No:64


Exp. No: Roll. No:
Date:

try {
while (true) {
[Link]("Welcome");
[Link](3000); // 3 seconds
}
} catch (InterruptedException e) {
[Link](e);
}
}
}
public class RunnableExample {
public static void main(String[] args)
{ GoodMorningRunnable gmr=new
GoodMorningRunnable(); HelloRunnable hr=new
HelloRunnable(); WelcomeRunnable wr=new
WelcomeRunnable();
Thread t1 = new Thread(gmr);
Thread t2 = new Thread(hr);
Thread t3 = new Thread(wr);
[Link]();
[Link]();
[Link]();
}
}
O
u
t
p
u
t
:
Compilation: javac [Link]

Execution : java RunnableExample

Good Morning
Welcome
Hello
ADITYA UNIVERSITY Page No:65
Exp. No: Roll. No:
Date:
Good Morning
Hello
Good Morning
Welcome
Good Morning
Hello
^C

ADITYA UNIVERSITY Page No:66


Exp. No: Roll. No:
Date:

Program 30:
Write a java program to solve Producer – Concumer problem using synchronization
Program:
[Link]:
class Q {
int n;
boolean valueSet = false;
synchronized int get() {
while (!valueSet)
{ try {
wait();
} catch (InterruptedException e)
{ [Link]("InterruptedException
caught");
}
}
[Link]("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n)
{ while (valueSet) {
try {
wait();
} catch (InterruptedException e)
{ [Link]("InterruptedException
caught");
}
}
this.n = n;
valueSet = true;
[Link]("Put: " + n);
ADITYA UNIVERSITY Page No:67
Exp. No: Roll. No:
Date:
notify();

ADITYA UNIVERSITY Page No:68


Exp. No: Roll. No:
Date:

}
}
class Producer implements Runnable
{ Q q;

Producer(Q q)
{ this.q = q;
new Thread(this, "Producer").start();
}
public void run()
{ int i = 0;
while (true) {
[Link](i++);
}
}
}
class Consumer implements Runnable
{ Q q;
Consumer(Q q)
{ this.q = q;
new Thread(this, "Consumer").start();
}
public void run()
{ while (true) {
[Link]();
}
}
}
class ProducerConsumerExample
{ public static void main(String args[])
{
Q q = new Q();
new Producer(q);
new Consumer(q);
ADITYA UNIVERSITY Page No:69
Exp. No: Roll. No:
Date:

[Link]("Press Control-C to stop.");


}
}
O
u
t
p
u
t
:
Compilation: javac [Link]

Execution : java ProducerConsumerExample

Put: 0

Got: 0
Put: 1
Got: 1
Put: 2
Got: 2
Put: 3
Got: 3
Put: 4
Got: 4
Put: 5
Got: 5
Put: 6
Got: 6
^C

ADITYA UNIVERSITY Page No:70


Exp. No: Roll. No:
Date:

Program 31:
Write a Java program to implement CRUD operations on a Database using JDBC API
Program:
[Link]:
import [Link].*;
import [Link];
public class AusEmpCRUD {
static String url = "jdbc:oracle:thin:@localhost:1521/XE";
// value changes based upon the database
static String username = "SYSTEM";// value changes based upon the database
static String password = "Password123"; // value changes based upon the database
public static void createTable(Connection conn) {
try {
Statement stmt = [Link]();
String sql = "CREATE TABLE ausemp (empno NUMBER(5), empname
VARCHAR2(30), salary NUMBER(10,2))";
[Link](sql);
[Link]("Table 'ausemp' created successfully.");
} catch (SQLException e)
{ [Link]("Table already
exists.");
}
}
public static void insertRecord(Connection conn, Scanner sc)
{ try {
[Link]("Enter Emp No: ");
int eno = [Link]();
[Link]();
[Link]("Enter Emp Name: ");
String ename = [Link]();
[Link]("Enter Salary: ");
double sal = [Link]();
PreparedStatement ps = [Link](
ADITYA UNIVERSITY Page No:71
Exp. No: Roll. No:
Date:

"INSERT INTO ausemp VALUES(?,?,?)");


[Link](1, eno);
[Link](2, ename);
[Link](3, sal);
int result = [Link]();
if (result == 1)
[Link]("Employee inserted successfully.");
} catch (SQLException e) {
[Link]();
}
}
public static void displayRecords(Connection conn)
{ try {
PreparedStatement ps = [Link]("SELECT * FROM ausemp");
ResultSet rs = [Link]();
[Link](" ");
[Link]("EmpNo\tEmpName\t\tSalary");
[Link](" ");
while ([Link]()) {
[Link](
[Link](1) + "\t" +
[Link](2) + "\t\t" +
[Link](3));
}
} catch (SQLException e) {
[Link]();
}
}
public static void updateRecord(Connection conn, Scanner sc)
{ try {
[Link]("Enter Emp No to update salary: ");
int eno = [Link]();
[Link]("Enter New Salary: ");

ADITYA UNIVERSITY Page No:72


Exp. No: Roll. No:
Date:

double sal = [Link]();


PreparedStatement ps = [Link](
"UPDATE ausemp SET salary=? WHERE empno=?");
[Link](1, sal);
[Link](2, eno);
int result = [Link]();
if (result == 1)
[Link]("Salary updated successfully.");
else
[Link]("Employee not found.");
} catch (SQLException e) {
[Link]();
}
}
public static void deleteRecord(Connection conn, Scanner sc) {
try {
[Link]("Enter Emp No to delete: ");
int eno = [Link]();
PreparedStatement ps =
[Link]( "DELETE FROM
ausemp WHERE empno=?");
[Link](1, eno);
int result = [Link]();
if (result == 1)
[Link]("Employee deleted successfully.");
else
[Link]("Employee not found.");
} catch (SQLException e) {
[Link]();
}
}
public static void main(String[] args)
{ Scanner sc = new
Scanner([Link]); try {
ADITYA UNIVERSITY Page No:73
Exp. No: Roll. No:
Date:

[Link]("[Link]");
Connection conn = [Link](url, username, password);
[Link]("Connected to Oracle Database");
// Step 1: Create
table
createTable(conn);
int choice;
do {
[Link]("\n===== AUSEMP TABLE MENU =====");
[Link]("1. Insert Employee");
[Link]("2. Update Employee Salary");
[Link]("3. Display Employees");
[Link]("4. Delete Employee");
[Link]("5. Exit");
[Link]("Enter choice: ");
choice = [Link]();
switch (choice) {
case 1:
insertRecord(conn, sc);
break;
case 2:
updateRecord(conn, sc);
break;
case 3:
displayRecords(conn);
break;
case 4:
deleteRecord(conn, sc);
break;
case 5:
[Link]("Exiting program...");
break;
default:
[Link]("Invalid choice.");
ADITYA UNIVERSITY Page No:74
Exp. No: Roll. No:
Date:

} while (choice != 5);


[Link]();
} catch (Exception e) {
[Link]();
}
}
}
Output:
Compilation: javac [Link]

Execution : java AusEmpCRUD

Connected to Oracle Database


Table 'ausemp' created successfully.
===== AUSEMP TABLE MENU =====
1. Insert Employee
2. Update Employee Salary
3. Display Employees
4. Delete Employee
5. Exit
Enter choice: 1
Enter Emp No: 10
Enter Emp Name: chakri
Enter Salary: 70000
Employee inserted successfully.
===== AUSEMP TABLE MENU =====
1. Insert Employee
2. Update Employee Salary
3. Display Employees
4. Delete Employee
5. Exit
Enter choice: 1
Enter Emp No: 20
Enter Emp Name: kiran

ADITYA UNIVERSITY Page No:75


Exp. No: Roll. No:
Date:

Enter Salary: 90000


Employee inserted successfully.
===== AUSEMP TABLE MENU =====
1. Insert Employee
2. Update Employee Salary
3. Display Employees
4. Delete Employee
5. Exit
Enter choice: 3

EmpNo EmpName Salary

10 chakri 70000.0
20 kiran 90000.0
===== AUSEMP TABLE MENU =====
1. Insert Employee
2. Update Employee Salary
3. Display Employees
4. Delete Employee
5. Exit
Enter choice: 2
Enter Emp No to update salary: 10
Enter New Salary: 100000
Salary updated successfully.
===== AUSEMP TABLE MENU =====
1. Insert Employee
2. Update Employee Salary
3. Display Employees
4. Delete Employee
5. Exit
Enter choice: 3

EmpNo EmpName Salary

10 chakri 100000.0

ADITYA UNIVERSITY Page No:76


Exp. No: Roll. No:
Date:

20 kiran 90000.0
===== AUSEMP TABLE MENU =====
1. Insert Employee
2. Update Employee Salary
3. Display Employees
4. Delete Employee
5. Exit
Enter choice: 4
Enter Emp No to delete: 20
Employee deleted successfully.
===== AUSEMP TABLE MENU =====
1. Insert Employee
2. Update Employee Salary
3. Display Employees
4. Delete Employee
5. Exit
Enter choice: 3

EmpNo EmpName Salary

10 chakri 100000.0
===== AUSEMP TABLE MENU =====
1. Insert Employee
2. Update Employee Salary
3. Display Employees
4. Delete Employee
5. Exit
Enter choice: 5
Exiting program...

ADITYA UNIVERSITY Page No:77

You might also like