CS3381-OOPS-lab manual
CS3381-OOPS-lab manual
LAB MANUAL
III SEMSTER
LAB MANUAL
III SEMSTER
Prepared By
Mrs. V. Thirumani Thangam, AP/CSE
\
Vision and Mission of the Institute and 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
By the completion of Information Technology program the student will have following Program specific
outcomes
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.
Page
Sl.No Name of the Experiment
No
Solve problems by using sequential search, binary search, and 1
1 quadratic sorting algorithms (selection, insertion)
4 Abstract Class 13
5 Interface 15
7 Multi-Threading 19
8 File handling 21
9 Generic Function 23
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:
Program:
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;
} }
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:
ALGORITHM:
Step 3: Perform push, pop and display operations on the stack upon user’s choice.
PROGRAM:
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:
ALGORITHM:
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);
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:
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
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)
{
}}
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
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
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
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:
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;
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
}
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
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);
}
}
}
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
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);
}
}
}
INPUT AND OUTPUT:
14
3
42
5
10
Max is 42
Valliammai
Engineering
College
Max is : Engineering
RESULT:
The Java program to find maximum value from the given type of elements using generic functions was
implemented.
TOPIC BEYOND SYLLABUS
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);
}
}
}
}
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.