Program_Reference_OO
Program_Reference_OO
1.0 Aim
To develop a Java application to Sequential search, Binary search and quadratic
sorting algorithms.
Sequential Search:
class Sequential_Search {
// Driver Code
public static void main(String args[])
{
// Given arr[]
int arr[] = { 2, 3, 4, 10, 40 };
// Element to search
int x = 10;
// Function Call
int result = search(arr, x);
if (result == -1)
System.out.print(
"Element is not present in array");
else
System.out.print("Element is present"
+ " at index "
+ result);
}
}
PAGE \* MERGEFORMAT 1
Binary Search:
class BinarySearch {
// Function that returns index of
// x if it is present in arr[l, r]
int binarySearch(int arr[], int l,
int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
// If the element is present
// at the middle itself
if (arr[mid] == x)
return mid;
// If element is smaller than
// mid, then it can only be
// present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l,mid - 1, x);
// Else the element can only be
// present in right subarray
return binarySearch(arr, mid + 1,r, x);
}
// Driver Code
public static void main(String args[])
{
// Function Call
int result = ob.binarySearch(arr, 0,n - 1, x);
if (result == -1)
System.out.println("Element "+ "not present");
else
System.out.println("Element found"+ " at index "+ result);
}
}
PAGE \* MERGEFORMAT 1
Selection Sort:
Algorithm:
Lets consider the following array as an example: arr[] = {64, 25, 12, 22, 11}
First pass:
For the first position in the sorted array, the whole array is traversed from index 0 to 4
sequentially. The first position where 64 is stored presently, after traversing whole array it is
clear that 11 is the lowest value.
64 25 12 22 11
Thus, replace 64 with 11. After one iteration 11, which happens to be the least value in the
array, tends to appear in the first position of the sorted list.
11 25 12 22 64
Second Pass:
For the second position, where 25 is present, again traverse the rest of the array in a sequential
manner.
11 25 12 22 64
After traversing, we found that 12 is the second lowest value in the array and it should appear
at the second place in the array, thus swap these values.
11 12 25 22 64
Third Pass:
Now, for third place, where 25 is present again traverse the rest of the array and find the third
least value present in the array.
11 12 25 22 64
While traversing, 22 came out to be the third least value and it should appear at the third place
in the array, thus swap 22 with element present at third position.
11 12 22 25 64
Fourth pass:
Similarly, for fourth position traverse the rest of the array and find the fourth least element in
the array
As 25 is the 4th lowest value hence, it will place at the fourth position.
11 12 22 25 64
Fifth Pass:
At last the largest value present in the array automatically get placed at the last position in the
array
The resulted array is the sorted array.
PAGE \* MERGEFORMAT 1
11 12 22 25 64
Program:
class SelectionSort
{
void sort(int arr[])
{
int n = arr.length;
Insertion Sort:
12 11 13 5 6
First Pass:
PAGE \* MERGEFORMAT 1
Initially, the first two elements of the array are compared in insertion sort.
12 11 13 5 6
Here, 12 is greater than 11 hence they are not in the ascending order and 12 is not at its
correct position. Thus, swap 11 and 12.
So, for now 11 is stored in a sorted sub-array.
11 12 13 5 6
Second Pass:
Now, move to the next two elements and compare them
11 12 13 5 6
Here, 13 is greater than 12, thus both elements seems to be in ascending order, hence, no
swapping will occur. 12 also stored in a sorted sub-array along with 11
Third Pass:
Now, two elements are present in the sorted sub-array which are 11 and 12
Moving forward to the next two elements which are 13 and 5
11 12 13 5 6
Both 5 and 13 are not present at their correct place so swap them
11 12 5 13 6
After swapping, elements 12 and 5 are not sorted, thus swap again
11 5 12 13 6
5 11 12 13 6
5 11 12 13 6
Clearly, they are not sorted, thus perform swap between both
5 11 12 6 13
5 11 6 12 13
5 6 11 12 13
Code:
// Java program for implementation of Insertion Sort
class InsertionSort {
PAGE \* MERGEFORMAT 1
/*Function to sort array using insertion sort*/
void sort(int arr[])
{
int n = arr.length;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
System.out.println();
}
// Driver method
public static void main(String args[])
{
int arr[] = { 12, 11, 13, 5, 6 };
printArray(arr);
}
}
PAGE \* MERGEFORMAT 1
Ex. No. 2 PROGRAM TO DEVELOP STACK AND QUEUE
DATA STRUCTURES USING CLASSES AND OBJECTS
Date :
1.0 Aim
To develop a stack and queue data structures using classes and objects.
2.0 Algorithm:
Step 1: push inserts an item at the top of the stack (i.e., above its current top element).
Step 2: pop removes the object at the top of the stack and returns that object from the function. The
stack size will be decremented by one.
Step 3: isEmpty tests if the stack is empty or not.
Step 4: isFull tests if the stack is full or not.
Step 5: peek returns the object at the top of the stack without removing it from the stack or
modifying the stack in any way.
Step 6: size returns the total number of elements present in the stack.
3.0 Program:
class Stack
{
private int arr[];
private int top;
private int capacity;
PAGE \* MERGEFORMAT 1
System.out.println("Inserting " + x);
arr[++top] = x;
}
return -1;
}
class Main
{
public static void main (String[] args)
{
Stack stack = new Stack(3);
PAGE \* MERGEFORMAT 1
stack.push(1); // inserting 1 in the stack
stack.push(2); // inserting 2 in the stack
OUTPUT:
Inserting 1
Inserting 2
Removing 2
Removing 1
Inserting 3
The top element is 3
The stack size is 1
Removing 3
The stack is empty
Queue Implementation:
import java.util.LinkedList;
import java.util.Queue;
class Main
{
public static void main(String[] args)
{
Queue<String> queue = new LinkedList<String>();
PAGE \* MERGEFORMAT 1
queue.add("B"); // Insert `B` into the queue
queue.add("C"); // Insert `C` into the queue
queue.add("D"); // Insert `D` into the queue
Output:
PAGE \* MERGEFORMAT 1
4. 0 Result:
Thus above program was executed and output is verified.
REVIEW QUESTIONS:
1. Explain public static void main(String args[])
Java main() Method – public static void main(String[] args) In Java programs, the
point from where the program starts its execution or simply the entry point of Java programs is
the main() method.
There are 3 types of Access Specifiers available in PHP, Public, Private and Protected.
1.0 Aim
PAGE \* MERGEFORMAT 1
To develop a java application to generate pay slip for different category of employees using the
concept of 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
2.0 Procedure:
STEP 1: Create the specified classes
STEP 2: Add members of the inherited class
STEP 3: Calculate gross salary and net salary with the given equation
STEP 4: Display the pay slip with net salary and gross salary
3.0 Program:
package employee;
import java.io.IOException;
import java.util.Scanner;
class Emp
{
String ename,Address,email;
int eid;
int mobile;
void getEmployeedetails()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the Emp_id. :");
eid=in.nextInt();
System.out.println("Enter the Employee Name:");
ename=in.next();
System.out.println("Enter the Employee Address:");
Address=in.next();
System.out.println("Enter the Employee Email id :");
email=in.next();
}
void display()
{
System.out.println("Emp_id:"+eid);
System.out.println("Employee Name:"+ename);
System.out.println("Employee Address:"+Address);
System.out.println("Employee Email id :"+email);
System.out.println("Employee Mobile No:"+mobile);
}
}
class Programmer extends Emp
{
double BasicPay;
void Programmerdetails()
{
getEmployeedetails();
Scanner in = new Scanner(System.in);
System.out.println("Enter the Basic Pay of the Programmer:");
BasicPay=in.nextInt();
display();
pay_calulation(BasicPay);
}
}
class AssistantProfessor extends Emp
{
void APDetails()
{
double BasicPay;
getEmployeedetails();
Scanner in = new Scanner(System.in);
PAGE \* MERGEFORMAT 1
}
class AssociateProfessor extends Emp
{
double BasicPay;
void ASPDetails()
{
getEmployeedetails();
Scanner in = new Scanner(System.in);
System.out.println("Enter the Basic Pay of the AssociateProfessor:");
BasicPay=in.nextInt();
display();
pay_calulation(BasicPay);
}
}
class Professor extends Emp
{
double BasicPay;
void profDetails()
{
getEmployeedetails();
Scanner in = new Scanner(System.in);
System.out.println("Enter the Basic Pay of the Professor:");
BasicPay=in.nextInt();
display();
pay_calulation(BasicPay);
}
}
}}
OUTPUT:
PAGE \* MERGEFORMAT 1
4.0 Result:
REVIEW QUESTIONS:
1. Can a top-level class be private or protected?
PAGE \* MERGEFORMAT 1
No, we cannot declare a top-level class as private or protected. It can be either public
or default (no modifier).
Java doesn't support multiple inheritances in classes because it can lead to diamond
problem and rather than providing some complex way to solve it, there are better ways through
which we can achieve the same result as multiple inheritances.
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
4. If a class is declared without any access modifiers, where may the class be accessed?
A class that is declared without any access modifiers is said to have package or
friendly access. This means that the class can only be accessed by other classes and
interfaces that are defined within the same package.
PAGE \* MERGEFORMAT 1
1.0 Aim
To write a java program to calculate the area of rectangle,circle and triangle using the concept of
abstract class.
Write a Java Program to create an abstract class named Shape that contains two integers and
an empty method named print Area(). 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 print Area () that prints the area of the given shape.
2.0 Algorithm:
STEP 1: Create an abstract class with the name shape
STEP 1.1: Let sides of shape be Side1 and Side2, create variables Side1, Side2
STEP 1.2: Define an empty method PrintArea()
STEP 2: Create three classes with names Rectangle, Triangle and Circle
STEP 2.1: Extend the Shape class in each of these classes
STEP 2.2: Develop the implementation of Area in each class appropriately
STEP 2.3: For Eg: PrintArea() of Circle would be 3.14*Side1*Side1 ; here Side1 is
considered as circle’s radius
STEP 3: Write a class with main method
STEP 4: Create instance of all three classes
STEP 5: Calculate the Area for each shape
STEP 6: Display the area
3.0 Program:
package javaapplication3;
abstract class shape
{
int a=3,b=4;
abstract public void print_area();
}
class rectangle extends shape
{
public int area_rect;
@Override
public void print_area()
PAGE \* MERGEFORMAT 1
{
area_rect=a*b;
System.out.println("The area ofrectangle is:"+area_rect);
}
}
class triangle extends shape
{
int area_tri;
@Override
public void print_area()
{
area_tri=(int) (0.5*a*b);
System.out.println("The area oftriangle is:"+area_tri);
}
}
class circle extends shape
{
int area_circle;
@Override
public void print_area()
{
area_circle=(int) (3.14*a*a);
System.out.println("The area ofcircle is:"+area_circle);
}
}
public class JavaApplication3 {
public static void main(String[] args) {
rectangle r=new rectangle();
r.print_area();
triangle t=new triangle();
t.print_area();
circle r1=new circle();
r1.print_area();
}
}
PAGE \* MERGEFORMAT 1
Using Interface:
interface Shape
{
void input();
void area();
}
class Circle implements Shape
{
int r = 0;
double pi = 3.14, ar = 0;
@Override
public void input()
{
r = 5;
}
@Override
public void area()
{
ar = pi * r * r;
System.out.println("Area of circle:"+ar);
}
}
class Rectangle extends Circle
{
int l = 0, b = 0;
double ar;
public void input()
{
super.input();
l = 6;
b = 4;
}
PAGE \* MERGEFORMAT 1
public void area()
{
super.area();
ar = l * b;
System.out.println("Area of rectangle:"+ar);
}
}
public class Demo
{
public static void main(String[] args)
{
Rectangle obj = new Rectangle();
obj.input();
obj.area();
}
}
OUTPUT:
PAGE \* MERGEFORMAT 1
4.0 Result:
Points to remember:
1. Abstract classes are not Interfaces. They are different, we will study this when we will study
Interfaces.
2. An abstract class may or may not have an abstract method. But if any class has even a single
abstract method, then it must be declared abstract.
PAGE \* MERGEFORMAT 1
3. Abstract classes can have Constructors, Member variables and Normal methods.
4. Abstract classes are never instantiated.
5. When you extend Abstract class with abstract method, you must define the abstract method in
the child class, or make the child class abstract.
REVIEW QUESTIONS:
PAGE \* MERGEFORMAT 1
Yes, static methods can exist in abstract classes. They are frequently used to
implement utility functions or other class-level features.
An abstract class may contain abstract methods, that is, methods with no
implementation.
PAGE \* MERGEFORMAT 1
1.0 Aim
To write a java program to implement user defined exception handling
2.0 Algorithm:
STEP 1: Create a class that extends Exception class
STEP 1.1: Let the name be MyException
STEP 1.2: Define a constructor that calls super()
STEP 2: Create a class with main method
STEP 2.1: Use the MyException in the try catch clause
3.0 Program:
package example1;
{
try{
System.out.println("Starting of try block");
// I'm throwing the custom exception using throw
throw new MyException("This is My error Message");
}
catch(MyException exp){
System.out.println("Catch Block") ;
System.out.println(exp) ;
}
}
OUTPUT:
PAGE \* MERGEFORMAT 1
4.0 Result:
Thus above program executed and output is verified.
Points to remember:
1. Extend the Exception class to create your own exception class.
2. You don't have to implement anything inside it, no methods are required.
3. You can have a Constructor if you want.
4. You can override the toString() function, to display customized message.
PAGE \* MERGEFORMAT 1
REVIEW QUESTIONS:
1. What is difference between Checked and Unchecked Exception in Java?
BASIS FOR UNCHECKED
CHECKED EXCEPTION
COMPARISON EXCEPTION
The compiler checks the The compiler does not check
Basic
checked exception. the Unchecked exception.
Except "RuntimeException"
class all the child classes of the "RuntimeException" class and
Class of
class "Exception", and the its child classes,are"Unchecked
Exception
"Error" class and its child Exceptions".
classes are Checked Exception.
If we do not handle the checked Even if we do not handle the
Handling exception, then the compiler unchecked exception, the
objects. compiler doesn't object.
The program compiles
The program doesn't compile if
successfully even if there is an
Compilation there is an unhandled checked
unhandled unchecked
exception in the program code.
exception in the program code.
PAGE \* MERGEFORMAT 1
Yes, we can have an empty catch block. But this is a bad practice to implement in Java.
BASIS FOR
COMPARISO ERROR EXCEPTION
N
An error is caused due to lack An exception is caused because
Basic
of system resources. of the code.
Recovery An error is irrecoverable. An exception is recoverable.
Exceptions are handled using
There is no means to handle
Keywords three keywords "try", "catch",
an error by the proram code.
and "throw".
As an exception is detected, it is
As the error is detected the
thrown and caught by the
Consequences program will terminated
"throw" and "catch" keywords
abnormally.
correspondingly.
Errors are classified as Exceptions are classified as
Types
unchecked type. checked or unchecked type.
In Java, errors are defined In Java, an exceptions are
Package
"java.lang.Error" package. defined in"java.lang.Exception".
Checked
Exceptions :NoSuchMethod,
OutOfMemory, ClassNotFound.
Example
StackOverFlow. Unchecked
Exceptions :NullPointer,
IndexOutOfBounds.
PAGE \* MERGEFORMAT 1
1.0 Aim
To write a java program that implements a multi-threaded application .
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, second thread
computes the square of the number and prints. If the value is odd, the third thread will print the
value of cube of the number.
2.0 Algorithm:
STEP 1: Create three classes ,IntThread, SqThread, CubeThread
STEP 1.1: Let the classes extend the Thread Class
STEP 1.2: Let the run method of IntTheadhave random no generator
STEP 1.3: Let the run method of SqThread have square generator
STEP 1.4: Let the run method of CubeThread have cube generator
STEP 2: Create a class with main method
STEP 2.1: Create instances of IntThread, SqThread, CubeThread
STEP 2.2: Synchronize all the threads and print no, then square and then cube
3.0 Program:
package mtherad;
import java.util.*;
@Override
public void run()
{
System.out.println("Thread Name:Even Thread and square is: " + x * x);
}
class A extends Thread{
public String tname;
public Random r;
public Thread t1,t2;
public A(String s){
tname=s;
}
@Override
public void run()
{
int num=0;
r=new Random();
try {
for(int i=0;i<50;i++){
num=r.nextInt(100);
System.out.println("main thread and generated number is"+num);
if(num%2==0)
{
t1=new Thread(new even(num));
t1.start();
}else{
t2=new Thread(new odd(num));
t2.start();
}
Thread.sleep(1000);
System.out.println("------------------------------------");
}
}
catch(InterruptedException ex)
{
System.out.println(ex.getMessage());
}
}
}
OUTPUT:
4.0 Result:
Thus above program executed and output is verified.
REVIEW QUESTIONS:
PAGE \* MERGEFORMAT 1
A process is an instance of a program that is being executed or processed. Thread is a
segment of a process or a lightweight process that is managed by the scheduler independently.
Java offers two types of threads: user threads and daemon threads. User threads are high-
priority threads. The JVM will wait for any user thread to complete its task before
terminating it. On the other hand, daemon threads are low-priority threads whose only role
is to provide services to user threads.
3. Why wait(), notify() and notifyAll() methods have to be called from synchronized
method or block?
This is because they require a lock on the object's monitor, and if the lock is not held,
an IllegalMonitorStateException will be thrown. Additionally, synchronization ensures that
the changes made by one thread are visible to all other threads, which is necessary for the
correct functioning of wait and notify.
PAGE \* MERGEFORMAT 1
Date :
1.0 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.
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.
2.0 Algorithm:
STEP 1: Create a text file with some contents
STEP 1.1: Let the name of file be ‘Example.txt’
STEP 1.2: Enter some content and save in the same folder as java program
STEP 2: Create a class with main method
STEP 2.1: Create a file object
STEP 2.2: Print all the attributes of the file objects
3.0 Program:
import java.util.Scanner;
import java.io.File;
PAGE \* MERGEFORMAT 1
}
Fib.java
for(i=2;i<count;++i)
{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}
}
OUTPUT:
PAGE \* MERGEFORMAT 1
4.0 Result:
Thus above program executed and output is verified.
REVIEW QUESTIONS:
PAGE \* MERGEFORMAT 1
1. What are flush() and close() used for ?
flush() to empty the buffers. For example, again assuming out is an OutputStream of
some sort, calling out. close() closes the stream and implicitly flushes it.
2. What is the difference between the Reader/Writer class hierarchy and the Input
Stream/Output Stream class hierarchy?
The Reader/Writer class hierarchy is character-oriented, and the Input Stream/Output
Stream class hierarchy is byte-oriented.
3. Which class is used to read streams of characters from a file? Which class is used to
read streams of raw bytes from a file?
FileInputStream class is useful to read data from a file in the form of sequence of
bytes. FileInputStream is meant for reading streams of raw bytes such as image data.
PAGE \* MERGEFORMAT 1
1.0 Aim
To develop applications to demonstrate the features of generics classes
2.0 Algorithm:
Step 1: To create an instance of generic class
Step 2: BaseType <Type> obj = new BaseType <Type>()
Step 3: We use < > to specify Parameter type
Step 4: An object of type T is declared
3.0 Program:
// constructor
Test(T obj1, U obj2)
{
this.obj1 = obj1;
this.obj2 = obj2;
}
obj.print();
}
}
PAGE \* MERGEFORMAT 1
OUTPUT:
15
KCG
4.0 Result:
Thus above program executed and output is verified.
REVIEW QUESTIONS:
PAGE \* MERGEFORMAT 1
4. Can you give an example of a Generic Method?
<String>genericMethod("Java Programming"); demo.
<Integer>genericMethod(25);
PAGE \* MERGEFORMAT 1
Date:
1.0 Aim
To demonstrate the features of generics classes.
2.0 Program
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();
}
public static void main(String[] args) {
launch(args);
}
OUTPUT:
PAGE \* MERGEFORMAT 1
Menu:
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");
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);
PAGE \* MERGEFORMAT 1
primaryStage.show();
}
}
OUTPUT:
PAGE \* MERGEFORMAT 1