Java Programming Lab Manual
Java Programming Lab Manual
JAVA PROGRAMMING
LAB MANUAL
Course Code: 241IT006
—
Semester: IV Semester
—
Regulations : AR24
INDEX
5 write a java program to find the maximum and minimum element in an array 8
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
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
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]
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
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;
}
first = second;
second = next;
}
[Link]("\nSum of even Fibonacci numbers up to " + n + " = " + sum);
}
}
Output:
Compilation: javac [Link]
0 1 1 2 3 5 8 13
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]
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:
10
92
32
86
34
45
23
10 2 92 32 86 34 45 23
2 10 23 32 34 45 86 92
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]
12
78
34
45
12 3 78 34 45
Maximum element = 78
Minimum element = 3
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
10
20
30
20
40
10
80
60
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]();
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;
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]
Age :0
Name : Ravi
Age :0
Name : Anita
Age : 20
Name : Kiran
Age : 22
Course : Java
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;
}
Output:
Compilation: javac [Link]
Returned Sum: 30
Returned Sum: 30
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.");
[Link]();
}
}
O
u
t
p
u
t
:
Compilation: javac [Link]
Enter a sentence: The quick brown fox jumps over the lazy dog
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
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
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.
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]();
Output:
Compilation: javac [Link]
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: " +
}
}
// 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]
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() {
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
Program 18:
Value of num: 50
Protected number: 50
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);
}
}
}
Output:
Compilation: javac [Link]
[Link]:
1
2
3
4
5
6
7
8
9
10
[Link]:
2 4 6 8 10
[Link]:
1 3 5 7 9
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);
}
// Adding element at first position
[Link]("Black");
Elements in ArrayList:
Apple
Banana
Mango
Orange
Elements in LinkedList:
Red
Green
Blue
Yellow
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]
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);
[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]
Sorting by ID (Comparable):
101 Ravi
102 Kiran
103 Anil
103 Anil
102 Kiran
101 Ravi
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]());
}
}
}
Output:
Compilation: javac [Link]
17 : Latha
3 : Sita
90 : Ram
12 : Anil
45 : Ravi
78 : Kiran
3 : Sita
12 : Anil
17 : Latha
45 : Ravi
78 : Kiran
90 : Ram
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)
{
[Link](num + " ");
}
}
}
O
u
t
p
u
t
:
Compilation: javac [Link]
17 3 90 12 45 78
3 12 17 45 78 90
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]());
}
}
}
Output:
Compilation: javac [Link]
Elements in Hashtable:
104 : Sita
103 : Kiran
102 : Anil
101 : Ravi
104 : Sita
102 : Anil
101 : Ravi
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) {
}
finally {
[Link]("in finally block");
}
[Link]();
[Link]("program execution completed");
}
}
O
u
t
p
u
t
:
Compilation: javac [Link]
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) {
}
}
Output:
Compilation: javac [Link]
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() {
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]
Good Morning
Welcome
Hello
Good Morning
Hello
Good Morning
Welcome
Good Morning
Hello
Good Morning
Good Morning
Hello
^C
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() {
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]
Good Morning
Welcome
Hello
ADITYA UNIVERSITY Page No:65
Exp. No: Roll. No:
Date:
Good Morning
Hello
Good Morning
Welcome
Good Morning
Hello
^C
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();
}
}
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:
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
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:
[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:
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
10 chakri 100000.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: 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
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...