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

CS3381-OOPS-lab manual

Lab manual of oops

Uploaded by

shivani20.dsp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

CS3381-OOPS-lab manual

Lab manual of oops

Uploaded by

shivani20.dsp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

ACADEMIC YEAR: 2022-2023


ODD SEMESTER

LAB MANUAL

CS3381 OBJECT ORIENTED PROGRAMMING


LABORATORY
(REGULATION - 2021)

III SEMSTER

B.E – Computer Science and Engineering


NEW PRINCE SHRI BHAVANI
COLLEGE OF ENGINEERING & TECHNOLOGY
Vengaivasal Main Road, Gowrivakkam, Chennai – 600073

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

ACADEMIC YEAR: 2022-2023


ODD SEMESTER

LAB MANUAL

CS3381 OBJECT ORIENTED PROGRAMMING


LABORATORY
(REGULATION - 2021)

III SEMSTER

B.E – Computer Science and Engineering

Prepared By
Mrs. V. Thirumani Thangam, AP/CSE

\
Vision and Mission of the Institute and Department

Vision of the Institute:


To strive for excellence in imparting technical education by promoting innovation, creativity and
entrepreneurial abilities of the students.

Mission of the Institute:


 Enhancing the effectiveness of teaching-learning process by providing a stimulating learning
environment
 To establish R&D centers, incubation centers and centers of excellences in latest technologies
and provide a platform for students to interact with the industry.
 Achieving Academic excellence by imparting knowledge and skills through problem solving,
practical training and design & development of innovative projects.
 Sensitizing students to social and environmental issues.
 Inculcating discipline in students and make them technologically and ethically strong

Vision of the Department


To foster competent professional with ethical codes and make them technologically adept, self-
motivated, and socially responsible innovators.

Mission of the Department

M1: To stimulate challenging professional by imparting proficient education and the zest of higher
studies.
M2: Provide learning ambience to generate innovative and problem-solving skills with professionalism.
M3: To imbibe leadership quality, thereby making them expertise in their career.
M4: To inculcate independent and lifelong learning with ethical and social responsibilities.
M5: To prepare highly qualified, sought-after, and technical intelligent strategists who can
expand the effectiveness.
Program Educational Objectives (PEO’S)
PEO1: To provide graduating students with core competencies by strengthening their mathematical,
scientific, and engineering fundamentals thereby pursue higher education and research or have a
successful career in industries associated with Computer Science and Engineering, or as entrepreneurs.

PEO2: To train graduates in diversified and applied areas with analysis, design, and synthesis of data to
create novel products and solutions to meet current industrial and societal needs.

PEO3: To promote collaborative learning and spirit of teamwork through multidisciplinary projects and
diverse professional activities. Also, inculcate high professionalism among the students by providing
technical and soft skills with ethical standards

Program Outcomes (POs)


After going through the four years of study, Computer Science and Engineering Graduates will exhibit
ability to:
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals and
an engineering specialization to the solution of complex engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering
and IT tools including prediction and modeling to complex engineering activities with an understanding
of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and
design documentation, make effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one‘s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.

Program Specific Objectives (PSO’s)

By the completion of Information Technology program the student will have following Program specific
outcomes

 To analyze, design and develop computing solutions by applying foundational concepts of


Computer Science and Engineering.
 To apply software engineering principles and practices for developing quality software for
scientific and business applications.
CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY LTPC
0 0 3 1.5
COURSE OBJECTIVES:
 To build software development skills using java programming for real-world
applications.
 To understand and apply the concepts of classes, packages, interfaces, inheritance,
exception handling and file processing.
 To develop applications using generic programming and event handling

LIST OF EXPERIMENTS:
1. Solve problems by using sequential search, binary search, and quadratic sorting algorithms
(selection, insertion)
2. Develop stack and queue data structures using classes and objects.
3. Develop a java application with an Employee class with Emp_name, Emp_id, Address,
Mail_id, Mobile_no as members. Inherit the classes, Programmer, Assistant Professor, Associate
Professor and Professor from employee class. Add Basic Pay (BP) as the member of all the
inherited classes with 97% of BP as DA, 10 % of BP as HRA, 12% of BP as PF, 0.1% of BP for
staff club funds. Generate pay slips for the employees with their gross and net salary.
4. Write a Java Program to create an abstract class named Shape that contains two integers and
an empty method named printArea(). Provide three classes named Rectangle, Triangle and Circle
such that each one of the classes extends the class Shape. Each one of the classes contains only
the method printArea( ) that prints the area of the given shape.
5. Solve the above problem using an interface.
6. Implement exception handling and creation of user defined exceptions.
7. Write a java program that implements a multi-threaded application that has three threads. First
thread generates a random integer every 1 second and if the value is even, the second thread
computes the square of the number and prints. If the value is odd, the third thread will print the
value of the cube of the number.
8. Write a program to perform file operations.
9. Develop applications to demonstrate the features of generics classes.
10. Develop applications using JavaFX controls, layouts and menus.
11. Develop a mini project for any application using Java concepts.

Lab Requirements: for a batch of 30 students


Operating Systems: Linux / Windows
Front End Tools: Eclipse IDE / Netbeans IDE
TOTAL: 45 PERIODS
COURSE OUTCOMES:
At the end of the course, the students will be able to:
CO1 Use different constructs of C and develop applications
CO2 Write functions to implement linear and non-linear data structure operations
CO3 Suggest and use the appropriate linear / non-linear data structure operations for a given
problem
CO4 Apply appropriate hash functions that result in a collision free scenario for data storage and
Retrieval
CO5 Implement Sorting and searching algorithms for a given application
CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY
CONTENTS

Page
Sl.No Name of the Experiment
No
Solve problems by using sequential search, binary search, and 1
1 quadratic sorting algorithms (selection, insertion)

2.a Stack Implementation Using Java 4

2.b Queue Implementation Using Java 6

3 Payroll Processing Using Hierarchical Inheritance 9

4 Abstract Class 13

5 Interface 15

6 User Defined Exception handling 17

7 Multi-Threading 19

8 File handling 21

9 Generic Function 23

10 Create a JAVAFX Controls, Layouts & Menus 25

11 Student Mark System-Mini Project 29


CONTENT BEYOND SYLLABUS

12 Implementation of String Operation using Array List 31

13 Implementation of Generic Function 34

14 Implementation of JDBC 37
Ex.No:1 Solve problems by using sequential search, binary search, and
quadratic sorting algorithms (selection, insertion)

1a).Sequential search

Aim:
To write a program to solve problem by using sequential search, binary search and sorting
algorithm using java

Algorithm:

Step 1: Traverse the array


Step 2: Match the key element with array element
Step 3: If key element is found, return the index position of the array element
Step 4: If key element is not found, return -1

Program:

public class LinearSearchExample{


public static int linearSearch(int[] arr, int key){
for(int i=0;i<arr.length;i++){
if(arr[i] == key){
return i;
}
}
return -1;
}
public static void main(String a[]){
int[] a1= {10,20,30,50,70,90};
int key = 50;
System.out.println(key+" is found at index: "+linearSearch(a1, key));
}
}

Sample Output:
50 is found at index: 3

1
1b).BINARY SEARCH
import java.util.Arrays;
class BinarySearchExample2{
public static void main(String args[]){
int arr[] = {10,20,30,40,50};
int key = 30;
int result = Arrays.binarySearch(arr,key);
if (result < 0)
System.out.println("Element is not found!");
else
System.out.println("Element is found at index: "+result);
}
}

Sample Output:
Element is found at index: 2

1C).INSERTION SORTING
public class InsertionSortExample {
public static void insertionSort(int array[]) {
int n = array.length;
for (int j = 1; j < n; j++) {
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) ) {
array [i+1] = array [i];
i--;
}
array[i+1] = key;
} }

public static void main(String a[]){


int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Insertion Sort");
for(int i:arr1){
System.out.print(i+" ");
}
System.out.println();
insertionSort(arr1);//sorting array using insertion sort
System.out.println("After Insertion Sort");
for(int i:arr1){
System.out.print(i+" ");
} } }

2
Sample Output:
Before Insertion Sort
9 14 3 2 43 11 58 22
After Insertion Sort
2 3 9 11 14 22 43 58

1D).SELECTION SORTING
public class SelectionSortExample {
public static void selectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++){
if (arr[j] < arr[index]){
index = j;//searching for lowest index
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
} }
public static void main(String a[]){
int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
System.out.println();
selectionSort(arr1);//sorting array using selection sort
System.out.println("After Selection Sort");
for(int i:arr1)
{
System.out.print(i+" ");
} }}

Sample Output:
Before Selection Sort
9 14 3 2 43 11 58 22
After Selection Sort
2 3 9 11 14 22 43 58

Result:
Thus the program to solve a searching and sorting is successfully executed and verified.

3
Ex.No :2A STACK IMPLEMENTATION USING JAVA.

AIM:

To create a program which implements ADT stack using Java.

ALGORITHM:

Step 1: Declare a stackArray object which implements an interface

. Step 2: Display menu of operations in stack for user.

Step 3: Perform push, pop and display operations on the stack upon user’s choice.

Step 4: Terminate the process after the exit is chosen.

PROGRAM:

class Stack <V> {


private int maxSize;
private int top;
private V array[];
public Stack(int max_size) {
this.maxSize = max_size;
this.top = -1; //initially when stack is empty
array = (V[]) new Object[max_size];
}
public int getMaxSize() {
return maxSize;
}

public boolean isEmpty(){


return top == -1;
}
public boolean isFull(){
return top == maxSize -1;
}
public V top(){
if(isEmpty())
return null;
return array[top];
}
public void push(V value){
if(isFull()) {
System.err.println("Stack is Full!");
return;

4
}
array[++top] = value; //increments the top and adds value to updated top
}
public V pop(){
if(isEmpty())
return null;
return array[top--]; //returns value and top and decrements the top
}}
class StackDemo {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>(5);
System.out.print("Elements pushed in the Stack: ");
for (int i = 0; i < 5; i++) {
stack.push(i); //pushes 5 elements (0-4 inclusive) to the stack
System.out.print(i + " ");
}
System.out.println("\nIs Stack full? \n" + stack.isFull());
System.out.print("Elements popped from the Stack: ");
for (int i = 0; i < 5; i++) {
System.out.print(stack.pop()+" "); //pops all 5 elements from the stack and prints them
}
System.out.println("\nIs Stack empty? \n" + stack.isEmpty());
}}

Sample Output:
java -cp /tmp/4zx4UbDxFp StackDemo
Elements pushed in the Stack: 0 1 2 3 4 Is Stack full?
trueElements popped from the Stack: 4 3 2 1 0 Is Stack empty?
True

RESULT:
Thus the program for Stack implementation using java is executed and implemented
successfully.

5
EX.NO :2B QUEUE IMPLEMENTATION USING JAVA.

AIM:

To create a program which implements ADT Queue using Java

ALGORITHM:

Step-1: Start the program


Step-2: Inserts an item at the rear of the queue.
Step-3: Removes the object from the front of the queue and returns it, thereby Step-
1decrementing queue size by one.
Step-4: Returns the object at the front of the queue without removing it.
Step-5: Tests if the queue is empty or not.
Step-6: Returns the total number of elements present in the queue.

PROGRAM:

class Queue {
int SIZE = 5;
int items[] = new int[SIZE];
int front, rear;
Queue() {
front = -1;
rear = -1;
}
boolean isFull() {
if (front == 0 && rear == SIZE - 1) {
return true;
}
return false;
}
boolean isEmpty() {
if (front == -1)
return true;
else
return false;
}
void enQueue(int element) {
if (isFull()) {
System.out.println("Queue is full");
}
else {
if (front == -1) {
front = 0;
}
6
rear++;
items[rear] = element;
System.out.println("Insert " + element);
} }
int deQueue() {
int element;
if (isEmpty()) {
System.out.println("Queue is empty");
return (-1);
}
else {
element = items[front];
if (front >= rear) {
front = -1;
rear = -1;
}
else {
front++;
}
System.out.println( element + " Deleted");
return (element);
} }
void display() {
int i;
if (isEmpty()) {
System.out.println("Empty Queue");
}
else {
System.out.println("\nFront index-> " + front);

System.out.println("Items -> ");


for (i = front; i <= rear; i++)
System.out.print(items[i] + " ");

System.out.println("\nRear index-> " + rear);


} }
public static void main(String[] args) {
Queue q = new Queue();
q.deQueue();
for(int i = 1; i < 6; i ++) {
q.enQueue(i);
}
q.enQueue(6);
q.display();
q.deQueue();
q.display();
}}
7
Sample Output:
java -cp /tmp/ioJDH0s8f4 Queue
Queue is empty
Insert 1
Insert 2
Insert 3
Insert 4
Insert 5
Queue is full

Front index-> 0
Items ->
12 3 4 5
Rear index-> 4
1 Deleted

Front index-> 1
Items ->
2 3 4 5
Rear index-> 4

RESULT:

Thus the program for queue implementation using java is executed and implemented
successfully.

8
EX. NO: 3 PAYROLL PROCESSING USING HIERARCHICAL
INHERITANCE

Develop a java application with Employee class with Emp_name, Emp_id, Address, Mail_id,
Mobile_no as members. Inherit the classes, Programmer, Assistant Professor, Associate
Professor and Professor from employee class. Add Basic Pay (BP) as the member of all the
inherited classes with 97% of BP as DA, 10 % of BP as HRA, 12% of BP as PF, 0.1% of BP for
staff club fund. Generate pay slips for the employees with their gross and net salary.

AIM:

To write a program in java which generates pay slips for the employees depending on their
profession.

ALGORITHM:

Step-1: Declare All Necessary Object


Step-2: Ask the User for the Employee Profession.
Step-3: Get the Details of the Employee from the User
Step-4: Calculate DA, HRA, PF, SC for the Employee
Step-5: Generate Pay-Slip and Display it to the User
Step-6: Terminate the Process

PROGRAM:

import java.util.Scanner;
class Employee{
String Emp_name;
int Emp_id;
String Address;
String Mail_id;
int Mobile_no;
void display(){
System.out.println(Emp_name);
//Syetem.out.println(Address);
System.out.println(Emp_id);
System.out.println(Mail_id);
System.out.println(Mobile_no);
}}
class Programmer extends Employee{
int BP;
/*int DA= (int) (0.97*BP);
HRA=(int) (0.10*BP);
PF=(int) (0.12*BP); */
void display(){
9
System.out.println(BP);
System.out.println("DA"+0.97*BP);
System.out.println("HRA"+0.10*BP);
System.out.println("PF"+0.12*BP);
System.out.println("SATFF CLUD FUND"+0.001*BP);
}}
class Assistant_Professor extends Employee{
int BP;
void display(){
System.out.println(BP);
System.out.println("DA"+0.97*BP);
System.out.println("HRA"+0.10*BP);
System.out.println("PF"+0.12*BP);
System.out.println("SATFF CLUD FUND"+0.001*BP);
}}
class Associate_Professor extends Employee{
int BP;

void display(){
System.out.println(BP);
System.out.println("DA"+0.97*BP);
System.out.println("HRA"+0.10*BP);
System.out.println("PF"+0.12*BP);
System.out.println("SATFF CLUD FUND"+0.001*BP);
}}
class Professor extends Employee{
int BP;
void display(){
System.out.println(BP);
System.out.println("DA"+0.97*BP);
System.out.println("HRA"+0.10*BP);
System.out.println("PF"+0.12*BP);
System.out.println("SATFF CLUD FUND"+0.001*BP);
}}
class Main{
public static void main(String args[]){
System.out.println("\n
1.Programmer\n2.Assistant_Professor\n3.Associate_Professor\n4.Professor");
Scanner input=new Scanner(System.in);
System.out.print("Enter an integer: ");
int ch=input.nextInt();
switch (ch) {
case 1:
Employee e1=new Employee();
Programmer p1=new Programmer();
e1.Emp_name="ABC";
e1.Address="y-city";
10
e1.Mail_id="[email protected]";
e1.Emp_id=567;
e1.Mobile_no=2345678;
p1.BP=15000;
p1.display();
e1.display();
break;
case 2:
Employee e2=new Employee();
Assistant_Professor p2=new Assistant_Professor();
e2.Emp_name="DEF";
e2.Address="A-city";
e2.Mail_id="[email protected]";
e2.Emp_id=123;
e2.Mobile_no=987321;
p2.BP=30000;
p2.display();
e2.display();
break;
case 3:
Employee e3=new Employee();
Associate_Professor p3=new Associate_Professor();
e3.Emp_name="GHF";
e3.Address="B-city";
e3.Mail_id="[email protected]";
e3.Emp_id=456;
e3.Mobile_no=98710;
p3.BP=30000;
p3.display();
e3.display();
break;
case 4:
Employee e4=new Employee();
Professor p4=new Professor();
e4.Emp_name="KANNAN";
e4.Address="TRICHY";
e4.Mail_id="[email protected]";
e4.Emp_id=789;
e4.Mobile_no=9810;
p4.BP=30000;
p4.display();
e4.display();
break;
case 5:
//exit(1);

default:
11
System.out.println("enter correct choice");

} }}

Sample Output:
1.Programmer
2.Assistant_Professor
3.Associate_Professor
4.Professor
Enter an integer: 1
15000
DA14550.0
HRA1500.0
PF1800.0
SATFF CLUD FUND15.0
ABC
567
[email protected]
2345678

RESULT:

The Pay Slip Was Generated From the Given Information and Displayed Successfully To The
User.

12
Ex.No:4 ABSTRACT CLASS

Aim:
To write a Java Program to create an abstract class named Shape and provide three classes
named Rectangle, Triangle and Circle such that each one of the classes extends the class Shape.

Procedure:
1. Import necessary packages.
2. Define the abstract class shape.
3. Define the class Rectangle with PrintArea() method that extends(makes use of)
Shape.
4. Define the class Triangle with PrintArea() method that extends(makes use of) Shape.
5. Define the class Circle with PrintArea() method that extends(makes use of) Shape.
6. Compile and run the program.
7. Print the area of the Rectangle,Triangle and Circle .
Program:
import java.io.*; abstract class shape
{
int a=10,b=20;
abstract void printArea();
}
class Circle extends shape
{
void printArea()
{
double pi=3.14; double area=pi*a*a;
System.out.println("circle area is"+area);
}
}
class Rectangle extends shape
{
void printArea()
{
double area=a*b; System.out.println("Rectangle area is"+area);
}
}
class Triangle extends shape
{
void printArea()
{
13
double area=0.5*a*b;
System.out.println("Triangle area is"+area);
}
}
class Demo
{
public static void main(String[] args)
{
Circle c1=new Circle(); c1.printArea();
Rectangle r1=new Rectangle(); r1.printArea();
Triangle t1=new Triangle(); t1.printArea();
}
}

Sample Output:
C:\Program Files\Java\jdk1.8.0\bin>javac Demo.java C:\Program Files\Java\jdk1.8.0\bin>java
Demo circle area is314.0

Rectangle area is200.0 Triangle area is100.0

Result:
Thus the design and implementation of Abstract class has been successfully executed.

14
EX.NO:5 INTERFACE

Aim:
To write a Java program to implement interface.

Program:
interface Shapei
{
void input():
void area():
}
class Circle implements Shape
{
int r = 0:
double pi - 3.14. ar =0:
public void input(){
r=5:
}
public void area(){
ar pi *r *rr
System.out.println(""Area of circle:"+ar):
}
}
class Rectangle extends Circle
{
int I = 0. b = 0:
double ar:
public void input()
{
super.input():
1=6:
b =4:
public void area(){
super.area():
ar = Ib;
System.out.println("Area of rectangle:"+ar):
}
}
public class Demo
public static void main(String[] args)
{

Rectangle obj = 15 new Rectangle0:


15
obj.input()
obj.area0

}}

SAMPLE OUTPUT:

Area of circle:78.5
Area of rectangle:24.0

Result:
Thus the interface has been successfully executed.

16
Ex.No:6 USER DEFINED EXCEPTION HANDLING

Aim:
To write a Java program to implement user defined exception handling.

Procedure:
1. Import necessary packages.
2. Define NumberFormat Exception within Nested try block.
3. Define NullPointerException, ArrayIndexOutOfBoundsException within Main
tryblock.
4. Define Multiple catch statements followed by Main try block.
5. Compile and run the program.
6. Print the exception which are thrown by try blocks in the output screen.

Program:
import java.lang.*; public class Demo
{
public static void main(String[] args)
{
try
{
try
{
int b=20/0; //ArithmeticException
}
catch(ArithmeticException e)
{
System.out.println("ArithmeticException is Found");
}
int a[]=new int[5];
a[5]=30; //ArrayIndexOutOfBoundsException String s="abc";
int i=Integer.parseInt(s); //NumberFormatException String s1=null;
System.out.println(s1.length()); //NullPointerException
}
catch(NumberFormatException e)
{
System.out.println("NumberFormatException is Found");
}
catch(ArrayIndexOutOfBoundsException e)
17
{
System.out.println("ArrayIndexOutOfBoundsException is Found");
}
catch(NullPointerException e)
{
System.out.println("NullPointerException is Found");
}
catch(Exception e)
{
System.out.println("Exception is found");
}
finally
{
System.out.println("finally block is always executed");
}}}

Sample Output:
ArithmeticException is Found

ArrayIndexOutOfBoundsException is Found

finally block is always executed

Result:
Thus the user defined exception has been successfully implemented.

18
Ex.No:7 MULTI-THREADING

Aim:
To write a java program that implements a Multi-Threaded application.

Procedure:
1. Import necessary packages.
2. Design the first thread that generates a random integer for every 1 second.
3. If the first thread value is even, design the second thread as the square of the number
and then print it.
4. Compile and run the program.
5. If the first thread value is odd, then third thread will print the value of cube of the
number.

Program:
import java.util.*;
class even implements Runnable
{public int x; public even(int x)
{this.x=x;
}
public void run()
{
System.out.println("New Thread"+x+"is Even and Square of"+x+"is:"+x*x);
}}
class odd implements Runnable
{
public int x; public odd(int x)
{
this.x=x;
}
public void run()
{
System.out.println("New Thread"+x+"is Odd and Square of"+x+"is:"+x*x*x);
}}
class A extends Thread
{
public void run()
{
int num=0;
Random r=new Random(); try
{
19
for(int i=0;i<5;i++)
{
num=r.nextInt(100);
System.out.println("Main Thread and Generated Number is"+num); if(num%2==0)
{Thread t1=new Thread(new even(num)); t1.start();
}
else
{
Thread t2=new Thread(new odd(num)); t2.start();
}
Thread.sleep(1000);
}}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}}}
public class Demo
{
public static void main(String[] args)
{
A a=new A(); a.start();
}}

Sample Output:
C:\Program Files\Java\jdk1.8.0_131\bin>javac Demo.java C:\Program
Files\Java\jdk1.8.0_131\bin>java Demo

Main Thread and Generated Number is94 New Thread94is Even and Square of94is:8836 Main
Thread and Generated Number is8

New Thread8is Even and Square of8is:64 Main Thread and Generated Number is2 New
Thread2is Even and Square of2is:4 Main Thread and Generated Number is2 New Thread2is
Even and Square of2is:4 Main Thread and Generated Number is66

New Thread66is Even and Square of66is:4356

Result:
Thus the implementation of Multi-Threading has been done using three threads

20
Ex.No:8 FILE HANDLING

Aim:
To write a Java program that reads a file name from the user, displays information about whether
the file exists, whether the file is readable, or writable, the type of file and the length of the file in
bytes.

Procedure:
1. Import necessary packages.
2. Read the filename from the user.
3. Use getName() Method to display the filename.
4. Use getPath() Method to display the path of the file.
5. Use getParent() Method to display its parent’s information.
6. Use exists() Method to display whether the file exist or not
7. Use isFile() and isDirectory() Methods to display whether the file is file or directory.
8. Use canRead() and canWrite) methods to display whether the file is readable or
writable.
9. Use lastModified() Method to display the modified information.
10. Use length() method to display the size of the file.
11. Use isHiddden() Method to display whether the file is hidden or not.

Program:
import java.util.Scanner; import java.io.File; class FileDemo
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in); String s=input.nextLine();
File f1=new File(s);
System.out.println("File Name:"+f1.getName()); System.out.println("Path:"+f1.getPath());
System.out.println("Abs Path:"+f1.getAbsolutePath());
System.out.println("Parent:"+f1.getParent());
System.out.println("This file is:"+(f1.exists()?"Exists":"Does not exists")); System.out.println("Is
file:"+f1.isFile());
System.out.println("Is Directory:"+f1.isDirectory()); System.out.println("Is
Readable:"+f1.canRead()); System.out.println("IS Writable:"+f1.canWrite());
System.out.println("Is Absolute:"+f1.isAbsolute()); System.out.println("File Last
Modified:"+f1.lastModified()); System.out.println("File Size:"+f1.length()+"bytes");
System.out.println("Is Hidden:"+f1.isHidden());
}
}

21
Sample Output:
Fibonacci.java

File Name:Fibonacci.java Path: Fibonacci.java

Abs Path: c:\sameer\Fibonacci.java Parent: Null

This file is:Exists Is file:true

Is Directory:false Is Readable:true Is Writable:true Is Absolute:false

File Last Modified:1206324301937 File Size: 406 bytes

Is Hidden:false

Result:
Thus the information of the file has been displayed successfully using various file methods.

22
Ex.No:9 GENERIC FUNCTION
AIM:

To write a java program to find the maximum value from the given type of elements using a
generic function.

PROCEDURE:

1. Import necessary packages.


2. Define the array with the elements
3. Sets the first value in the array as the current maximum
4. Find the maximum value by comparing each elements of the array
5. Compile and run the program.
6. Display the maximum value.

Program:
import java.io.*; import java.util.*; class A
{
public static <T extends Comparable<T>> T max(T... elements)
{
T max = elements[0];
for (T element : elements)
{
if (element.compareTo(max) > 0)
{
max = element;
}
}
return max;
}
public static void main(String[] args)
{
System.out.println("Integer Max: " + max(Integer.valueOf(32),
Integer.valueOf(56), Integer.valueOf(89), Integer.valueOf(3), Integer.valueOf(456),
Integer.valueOf(78), Integer.valueOf(45)));
System.out.println("Double Max: " + max(Double.valueOf(5.6),
Double.valueOf(7.8), Double.valueOf(2.9), Double.valueOf(18.6),
Double.valueOf(10.25), Double.valueOf(18.6001)));
System.out.println("String Max: " + max("Strawberry", "Mango", "Apple", "Pomegranate",
"Guava", "Blackberry", "Cherry", "Orange", "Date"));
System.out.println("Boolean Max: " + max(Boolean.TRUE, Boolean.FALSE));
System.out.println("Byte Max: " + max(Byte.MIN_VALUE, Byte.MAX_VALUE));
}
}

23
Sample Output:
C:\Program Files\Java\jdk1.8.0_131\bin>javac A.java C:\Program
Files\Java\jdk1.8.0_131\bin>java A Integer Max: 456

Double Max: 18.6001 String Max: Strawberry Boolean Max: true Byte Max: 127

Result:
Thus the implementation of generic function is achieved for finding the maximum value from the
given type of elements.

24
Ex.No:10 CREATE A JAVAFX CONTROLS, LAYOUTS &
MENUS

Aim:
To implement javafx controls, layouts & menus

Procedure:
1. Import necessary packages.
2. Using the swing components design the buttons
3. Use key events and key listener to listen the events
4. Do the necessary manipulations.
5. Compile and run the program.

Program:
JAVAFX CONTROLS:

package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class ButtonTest extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub

StackPane root = new StackPane();


Button btn=new Button("This is a button");
Scene scene=new Scene(root,300,300);
root.getChildren().add(btn);
primaryStage.setScene(scene);
primaryStage.setTitle("Button Class Example");
primaryStage.show();

}
public static void main(String[] args) {
launch(args);
}
25
}

Sample Output:

JAVAFX LAYOUT:

package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class Label_Test extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
BorderPane BPane = new BorderPane();
BPane.setTop(new Label("This will be at the top"));
BPane.setLeft(new Label("This will be at the left"));
BPane.setRight(new Label("This will be at the Right"));
BPane.setCenter(new Label("This will be at the Centre"));
BPane.setBottom(new Label("This will be at the bottom"));
Scene scene = new Scene(BPane,600,400);
primaryStage.setScene(scene);
primaryStage.show();
26
}
public static void main(String[] args) {
launch(args);
}
}
Sample Output:

JAVAFX MENUS

package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class MenuExample extends Application {
public static void main(String[] args) {
launch(args);
}

@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
BorderPane root = new BorderPane();
Scene scene = new Scene(root,200,300);
MenuBar menubar = new MenuBar();
Menu FileMenu = new Menu("File");
MenuItem filemenu1=new MenuItem("new");
MenuItem filemenu2=new MenuItem("Save");
MenuItem filemenu3=new MenuItem("Exit");
27
Menu EditMenu=new Menu("Edit");
MenuItem EditMenu1=new MenuItem("Cut");
MenuItem EditMenu2=new MenuItem("Copy");
MenuItem EditMenu3=new MenuItem("Paste");
EditMenu.getItems().addAll(EditMenu1,EditMenu2,EditMenu3);
root.setTop(menubar);
FileMenu.getItems().addAll(filemenu1,filemenu2,filemenu3);
menubar.getMenus().addAll(FileMenu,EditMenu);
primaryStage.setScene(scene);
primaryStage.show();
}
}

Sample Output:

Result:
Thus the implementation of javafx controls, layouts & menus has been successfully executed.

28
Ex.No:11 STUDENT MARK SYSTEM-MINI PROJECT

Aim:
To develop a Student Mark System as a Mini Project using JDBC.

Procedure:
1. Import necessary packages.
2. Creating Database with necessary information using SQL.
3. Connecting Database with Student Mark System program using JDBC connectivity.
4. Do the necessary manipulations.
5. Compile and run the program.

Program:
import java.sql.*; public class StudInfo
{
public static void main (String args [])
{
try
{
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection ("Jdbc: Odbc: stud"); Statement
st=con.createStatement ();
ResultSet rs=st.executeQuery ("select * from userdet"); While (rs.next ()) {
String name=rs.getString (1);
String rollno=rs.getString (2);
int mark1=rs.getInt (3);
int mark2=rs.getInt (4);
int mark3=rs.getInt (5);
String dept=rs.getString (6);
String year=rs.getString (7); System.out.println ("Name:"+name); System.out.println ("Roll
No:"+rollno); System.out.println ("Mark1:"+mark1); System.out.println ("Mark2 :"+mark2);
System.out.println ("Mark3:"+mark3); System.out.println ("Department:"+dept);
System.out.println ("Year :"+year);
int average= (mark1+mark2+mark3) /3; System.out.println ("Average:"+average);
}
} catch (Exception e) {
System.out.println ("Exception"+e);
}
}
}

29
Sample Output:
Name: Arun Rollno: 123
Mark1: 90
Mark2: 85
Mark3: 98 Dept: IT
Year: Second Year Average: 91

Result:
Thus the student mark system using JDBC has been successfully executed.

30
TOPIC BEYOND SYLLABUS

Ex. No:12 Implementation of String Operation using Array List

AIM
To perform string operations using Array List with the following functions for Append - add at end,
Insert – add at particular index, Search and list all string starts with given letter.

PRELAB DISCUSSION:
Strings, which are widely used in Java programming, are a sequence of characters. In Java
programming language, strings are treated as objects.The Java platform provides the String class to create and
manipulate strings.The most direct way to create a string is to write −String greeting = "Hello
world!";Whenever it encounters a string literal in your code, the compiler creates a String object with its
value in this case, "Hello world!'.As with any other object, you can create String objects by using the new
keyword and a constructor. The String class has 11 constructors that allow you to provide the initial value of
the string using different sources, such as an array of characters.

ALGORITHM:
5. Create an ArrayList named obj.
6. Add elements to the existing ArrayList at a specific position.
7. Insert the String elements at last one by one and display the Arraylist obj elements.
8. To search a specific element,get the input of the element to search.
9. Get the element starting letter from the user and find the position then store in the new ArrayList
10. Display the new Arraylist.
11. Stop the program execution.

PROCEDURE:
To execute a java program we require setting a class path:
1.C:\set path= C:\Program Files\Java\jdk1.6.0\bin;.;
2.C:\javac stringoperation.java
3.C:\java stringoperation

SOURCE CODE:
import java.util.*;
import java.util.ArrayList;
public class stringoperation
{
public static void main(String args[])
{
int choice, i,size;
Scanner sc=new Scanner(System.in);
ArrayList<String> obj = new ArrayList<String>();
System.out.println("Enter the total number of strings to be entered into the arraylist");
size=sc.nextInt();
for (int j=0;j<size;j++)
{
System.out.println("Enter the string"+j);
obj.add(sc.nextLine());
}
System.out.println("Currently the array list has following elements:"+obj);
System.out.println("Type of String Operation");
System.out.println("1. Append - add at end \n2. Insert – add at particular index \n3. Search \n4. List all
string starts with given letter");
System.out.println("Select the Operation");
choice=sc.nextInt();
switch(choice)
{
case 1 :
Scanner scan=new Scanner(System.in);
System.out.println("Enter the String to Append at the end:");
String append=scan.nextLine();
obj.add(append);
System.out.println("Current array list is:"+obj);
break;
case 2 :
Scanner scan1=new Scanner(System.in);
System.out.println("Enter the String to Insert at a particular index:");
String b =scan1.nextLine();
System.out.println("Enter the index:");
i =sc.nextInt();
obj.add(i, b);
System.out.println("Current array list is:"+obj);
break;
case 3 :
Scanner scan2=new Scanner(System.in);
System.out.println("Enter the String to search:");
String st1 =scan2.nextLine();
if (obj.contains(st1))
{
System.out.println("Found the String");
}
else
{
System.out.println("There is no such String");
}
break;
case 4 :
Scanner scan3=new Scanner(System.in);
System.out.println("Enter the character to List all string starts with given letter");
String startString =scan3.nextLine();
for (String str : obj)
{
if(str.startsWith(startString))
System.out.println(str);
}
System.out.println("Current array list is:"+obj);
}
}
}

INPUT AND OUTPUT:


Enter the total number of strings to be entered into the arraylist : 5
Enter the string1: Hari
Enter the string2: ram
Enter the string3: prakash
Enter the string4: sanjeve
Enter the string5: harray
Currently the array list has following elements:[, Hari, ram, prakash, sanjeve, harray]
Type of String Operation
1. Append - add at end
2. Insert – add at particular index
3. Search
4. List all string starts with given letter
Select the Operation:: 1
Enter the String to Append at the end:raj
Current array list is:[, Hari, ram, prakash, sanjeve, harray, raj]

VIVA QUESTIONS (PRELAB & POSTLAB)


1. Can we use String in switch case?
2. How to convert String to byte array and vice versa?
3. Why String is popular HashMap key in Java?
4. Why String is immutable or final in Java
5. What is String in Java? String is a data type?

RESULT
Thus the string operations using Array List with the following functions for Append - add at end,
Insert – add at particular index, Search and list all string starts with given letter.
TOPIC BEYOND SYLLABUS

Ex. No: 13 Implementation of Generic Function

AIM:
To Write a Java program to find maximum value from the given type of elements using generic
functions.

PRELAB DISCUSSION:
Java Generic methods and generic classes enable programmers to specify, with a single method
declaration, a set of related methods, or with a single class declaration, a set of related types, respectively.
Generics also provide compile-time type safety that allows programmers to catch invalid types at compile
time. Using Java Generic concept, we might write a generic method for sorting an array of objects, then
invoke the generic method with Integer arrays, Double arrays, String arrays and so on, to sort the array
elements. You can write a single generic method declaration that can be called with arguments of different
types. Based on the types of the arguments passed to the generic method, the compiler handles each method
call appropriately. Following are the rules to define Generic Methods −

 All generic method declarations have a type parameter section delimited by angle brackets (< and >)
that precedes the method's return type ( < E > in the next example).
 Each type parameter section contains one or more type parameters separated by commas. A type
parameter, also known as a type variable, is an identifier that specifies a generic type name.
 The type parameters can be used to declare the return type and act as placeholders for the types of the
arguments passed to the generic method, which are known as actual type arguments.
 A generic method's body is declared like that of any other method. Note that type parameters can
represent only reference types, not primitive types (like int, double and char)

ALGORITHM:
1. Start the Process
2. Create a array of number and array of strings and pass it to generic function.
3. If the array is Integer type
3.1 Assume first element as MAX
3.2 Compare [Numeric Perspetive] this element with MAX
3.3 If it is greater than MAX then store current element as MAX
3.4 Else do nothing
3.5 Goto step 3.1 until all the elements has been processed.
4. If the array is String type
4.1 Assume first element as MAX
4.2 Compare [Dictionary Perspective] this element with MAX
a. If it is greater than MAX then store current element as MAX
4.4 Else do nothing
4.5 Goto step 3.1 until all the elements has been processed.
5. Stop the Process

PROCEDURE:
To execute a java program we require setting a class path:
1.C:\set path= C:\Program Files\Java\jdk1.6.0\bin;.;
2.C:\javac Genericfunction.java
3.C:\java Genericfunction

SOURCE CODE:
class GenericMax {
public <T extends Comparable<T>> void maxFinder (T[] array){ T max
= array[0];
for(T element: array){
System.out.println(element);
if(element.compareTo(max) > 0)
max = element;
}
System.out.println("Max is : "+max);
}
}

public class Main {

public static void main(String[] args) { GenericMax


max = new GenericMax(); Integer[] numbers
= {14,3,42,5,6,10}; String[] strings =
{"R","Ra","Raj"}; max.maxFinder(numbers);
max.maxFinder(strings);
}

}
INPUT AND OUTPUT:
14
3
42
5
10
Max is 42
Valliammai
Engineering
College
Max is : Engineering

VIVA QUESTIONS(PRELAB & POSTLAB):


1. How to write parametrized class in Java using Generics
2. Can you pass List<String> to a method which accepts List<Object>
3. Can we use Generics with Array?
4. Is it Possible to Declared a Multiple Bounded Type Parameter?
5. What is a Generic Type Parameter

RESULT:
The Java program to find maximum value from the given type of elements using generic functions was
implemented.
TOPIC BEYOND SYLLABUS

Ex.No.14 Implementation of JDBC

AIM
To develop a simple OPAC system for library using event-driven and concurrent programming
paradigms of Java. Use JDBC to connect to a back-end database.

PRELAB DISCUSSION:
The JDBC ( Java Database Connectivity) API defines interfaces and classes for writing database
applications in Java by making database connections. Using JDBC you can send SQL, PL/SQL statements to
almost any relational database. JDBC is a Java API for executing SQL statements and supports basic SQL
functionality. It provides RDBMS access by allowing you to embed SQL inside Java code. Because Java can
run on a thin client, applets embedded in Web pages can contain downloadable JDBC code to enable remote
database access. You will learn how to create a table, insert values into it, query the table, retrieve results, and
update the table with the help of a JDBC Program example. Although JDBC was designed specifically to
provide a Java interface to relational databases, you may find that you need to write Java code to access non-
relational databases as well. Java application calls the JDBC library. JDBC loads a driver which talks to the
database In general, to process any SQL statement with JDBC, you follow these steps: ① Establishing a
connection. ② Create a statement. ③ Execute the query. ④ Process the ResultSet object. ⑤ Close the
connection.

JDBC-ODBC Bridge
As its name JDBC-ODBC bridge, it acts like a bridge between the Java Programming Language and
the ODBC to use the JDBC API. To use the JDBC API with the existing ODBC Sun Microsystems (Now
Oracle Corporation) provides the driver named JdbcOdbcDriver. Full name of this class is
sun.jdbc.odbc.JdbcOdbcDriver.
JDBC ODBC Connection
To Connect the JDBC and ODBC we should have a database. Then we would be required to create a
DSN to use JDBC ODBC Bridge driver. The DSN (Data Source Name) specifies the connection of an ODBC
to a specific server.
How To Create DSN In Java.
To create a DSN we would be required to follow some basic steps. These steps are as follows : Here I am
using the MS-Access as database system. Before creating DSN to use MS-Access with JDBC technology the
database file should be created in advance.
 First step is to go through the Control Panel -> Administrative Tools -> Data Sources (ODBC).
 Go to the tab System DSN in the ODBC Data Source Administrator dialog box then, Click on Add
button -> select MS Access Driver (*.mdb) -> click on Finish button.
 In the next step a dialog box ODBC Microsoft Access Setup will be opened then provide the field's
values corresponding to the field's label (i.e. provide the DSN name as you wish) and then click on the
"Select" button.
 In the next step a new dialog box "Select database" will be opened. Here you have to select the
directory where you have stored your file and provide the name in the place of the Database Name and
then press ok -> ok -> ok.
ALGORITHM:
1. Create a Database
2. Create a table employee in Database created.
3. Insert the fields into the employee table with the following fields: name, rollno, course, subject, marks.
4. Create another panel consisting of buttons UserID, BookID, Return/Renewal,Fine.
5. Associate these buttons with listeners(with Transaction Database).

PROCEDURE:
To execute a java program we require setting a class path:
1.C:\set path= C:\Program Files\Java\jdk1.6.0\bin;.;
2.C:\javac OpacSystem.java
3.C:\javac OpacSystem

SOURCE CODE:
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JdbcOdbcExample
{
public static void main(String args[])
{
Connection con = null;
PreparedStatement stmt = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:swing");

String sql ="INSERT INTO employee (name, rollNo, course, subject, marks) VALUES" +
"('Deepak', 10, 'MCA', 'Computer Science', 85)";
stmt = con.prepareStatement(sql);
int i = stmt.executeUpdate();
if(i > 0 )
{
System.out.println("Record Added Into Table Successfully.");
}
} catch (SQLException sqle) {
System.out.println(sqle.getNextException());
} catch (ClassNotFoundException e) {
System.out.println(e.getException());
} finally {
try {
if (stmt != null) {
stmt.close();
stmt = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (Exception e) {
System.out.println(e);
}
}
}
}

INPUT AND OUTPUT:


Table Before Inserting the record into it.

When you will execute the above example you will get the output at console as follows :

And then the Table after inserting record will be seen as follows :
VIVA QUESTIONS(PRELAB & POSTLAB):
1. What are different types of Statement?
2. What is connection pooling?
3. Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?
4. What are the locking system in JDBC
5. What are the main steps in java to make JDBC connectivity?

RESULT:
A simple OPAC system for library using event-driven and concurrent programming paradigms of Java
with the use JDBC to connect to a back-end database was implemented.

You might also like