0% found this document useful (0 votes)
3 views42 pages

Program_Reference_OO

Prgm

Uploaded by

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

Program_Reference_OO

Prgm

Uploaded by

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

Ex. No.

1 PROGRAM TO SEQUENTIAL SEARCH, BINARY


SEARCH, AND QUADRATIC SORTING ALGORITHMS
Date:

1.0 Aim
To develop a Java application to Sequential search, Binary search and quadratic
sorting algorithms.

Sequential Search:
class Sequential_Search {

// Function for linear search


public static int search(int arr[], int x)
{
int n = arr.length;

// Traverse array arr[]


for (int i = 0; i < n; i++) {

// If element found then


// return that index
if (arr[i] == x)
return i;
}
return -1;
}

// 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);
}

// Reach here when element is


// not present in array
return -1;
}

// Driver Code
public static void main(String args[])
{

// Create object of this class


BinarySearch ob = new BinarySearch();

// Given array arr[]


int arr[] = { 2, 3, 4, 10, 40 };
int n = arr.length;
int x = 10;

// 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;

// One by one move boundary of unsorted subarray


for (int i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

// Swap the found minimum element with the first


// element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}

// Prints the array


void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}

// Driver code to test above


public static void main(String args[])
{
SelectionSort ob = new SelectionSort();
int arr[] = {64,25,12,22,11};
ob.sort(arr);
System.out.println("Sorted array");
ob.printArray(arr);
}
}

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

 Here, again 11 and 5 are not sorted, hence swap again

5 11 12 13 6

 here, it is at its correct position


Fourth Pass:
 Now, the elements which are present in the sorted sub-array are 5, 11 and 12
 Moving to the next two elements 13 and 6

5 11 12 13 6

 Clearly, they are not sorted, thus perform swap between both

5 11 12 6 13

 Now, 6 is smaller than 12, hence, swap again

5 11 6 12 13

 Here, also swapping makes 11 and 6 unsorted hence, swap again

5 6 11 12 13

 Finally, the array is completely sorted.

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;

/* Move elements of arr[0..i-1], that are


greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

/* A utility function to print array of size n*/


static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");

System.out.println();
}

// Driver method
public static void main(String args[])
{
int arr[] = { 12, 11, 13, 5, 6 };

InsertionSort ob = new InsertionSort();


ob.sort(arr);

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;

// Constructor to initialize the stack


Stack(int size)
{
arr = new int[size];
capacity = size;
top = -1;
}

// Utility function to add an element `x` to the stack


public void push(int x)
{
if (isFull())
{
System.out.println("Overflow\nProgram Terminated\n");
System.exit(-1);
}

PAGE \* MERGEFORMAT 1
System.out.println("Inserting " + x);
arr[++top] = x;
}

// Utility function to pop a top element from the stack


public int pop()
{
// check for stack underflow
if (isEmpty())
{
System.out.println("Underflow\nProgram Terminated");
System.exit(-1);
}

System.out.println("Removing " + peek());

// decrease stack size by 1 and (optionally) return the popped element


return arr[top--];
}

// Utility function to return the top element of the stack


public int peek()
{
if (!isEmpty()) {
return arr[top];
}
else {
System.exit(-1);
}

return -1;
}

// Utility function to return the size of the stack


public int size() {
return top + 1;
}

// Utility function to check if the stack is empty or not


public boolean isEmpty() {
return top == -1; // or return size() == 0;
}

// Utility function to check if the stack is full or not


public boolean isFull() {
return top == capacity - 1; // or return size() == capacity;
}
}

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

stack.pop(); // removing the top element (2)


stack.pop(); // removing the top element (1)

stack.push(3); // inserting 3 in the stack

System.out.println("The top element is " + stack.peek());


System.out.println("The stack size is " + stack.size());

stack.pop(); // removing the top element (3)

// check if the stack is empty


if (stack.isEmpty()) {
System.out.println("The stack is empty");
}
else {
System.out.println("The stack is not empty");
}
}
}

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>();

queue.add("A"); // Insert `A` into the queue

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

// Prints the front of the queue (`A`)


System.out.println("The front element is " + queue.peek());

queue.remove(); // removing the front element (`A`)


queue.remove(); // removing the front element (`B`)

// Prints the front of the queue (`C`)


System.out.println("The front element is " + queue.peek());

// Returns the total number of elements present in the queue


System.out.println("The queue size is " + queue.size());

// check if the queue is empty


if (queue.isEmpty()) {
System.out.println("The queue is empty");
}
else {
System.out.println("The queue is not empty");
}
}
}

Output:

The front element is A


The front element is C
The queue size is 2
The queue is not empty

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.

2. Why Java is platform independent?

Java is platform-independent because it uses a virtual machine. The Java


programming language and all APIs are compiled into bytecodes. Bytecodes are effectively
platform-independent.

3. What are constructors in Java?


Constructor in java is used to create the instance of the class. Constructors are almost
similar to methods except for two things - its name is the same as the class name and it has no
return type. Sometimes constructors are also referred to as special methods to initialize an object.

4. What are the access specifies in OOPS

There are 3 types of Access Specifiers available in PHP, Public, Private and Protected.

Ex.No. 3 PROGRAM TO GENERATE PAYSLIP USING


INHERITANCE
Date:

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();

System.out.println("Enter the Mobile No:");


mobile=in.nextInt();
}
void pay_calulation(double BasicPay)
{
double DA,HRA,PF,Sfund,Gross_Salary,Netsalary;
PAGE \* MERGEFORMAT 1
DA=BasicPay*0.97;
HRA=BasicPay*0.10;
PF=BasicPay*0.12;
Sfund=BasicPay*0.1;
Gross_Salary=BasicPay+DA+HRA;
Netsalary=Gross_Salary-(PF+Sfund);
System.out.println("Gross salary of the Employee"+Gross_Salary);
System.out.println("Net salary of the Employee: "+Netsalary);

}
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);

System.out.println("Enter the Basic Pay of the AssistantProfessor:");


BasicPay=in.nextInt();
display();
pay_calulation(BasicPay);
}

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);
}

public class Employee


{

public static void main(String[] args)


{

Scanner in = new Scanner(System.in);


System.out.println("Choose the type Employee");

System.out.println("1.Programmer ,2.Assistant Professor,3.Associate


Professor ,4.Professor: ");
int ch=in.nextInt();
switch(ch)
{
case 1: System.out.println("PROGRAMMER DETAILS");
PAGE \* MERGEFORMAT 1
Programmer p=new Programmer();
p.Programmerdetails();
break;
case 2: System.out.println("Assistant Professor DETAILS");
AssistantProfessor ap=new AssistantProfessor();
ap.APDetails();
break;
case 3: System.out.println("Associate Professor DETAILS");
AssociateProfessor asp=new AssociateProfessor();
asp.ASPDetails();
break;
case 4: System.out.println("Professor DETAILS");
Professor pf=new Professor();
pf.profDetails();
break;

}
}}

OUTPUT:

PAGE \* MERGEFORMAT 1
4.0 Result:

Thus above program executed and output is verified.

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).

2. Will java support multiple inheritance?

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.

3. What is Method Overriding? What restrictions are placed on method overriding?

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.

5. Does a class inherit the constructors of its superclass?

Constructors cannot be inherited, basically a constructor is not a method.


Constructors are used to give a valid state for an object at creation.

Ex. No. 4 PROGRAM TO CALCULATE AREA USING

ABSTRACT CLASS &INTERFACE


Date:

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:

Using abstract class:

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:

Thus above program executed and output is verified.

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:

1. Can abstract class have constructors in Java?


Like any other classes in Java, abstract classes can have constructors even when they
are only called from their concrete subclasses.

2. Can abstract class be final in Java?


since both contradict with each other you cannot declare a class both abstract and
final if you do so a compile time error will be generated.

3. Difference between abstract class and interface in Java?


Abstract class Interface
Interface can have only abstract
Abstract class can have both an abstract methods. Java 8 onwards, it can
as well as concrete methods. have default as well as static
methods.
Interface supports Multiple
Multiple Inheritance is not supported.
Inheritance.
final, non-final, static and non-static Only static and final variables are
variables supported. permitted.
Interface can not implement an
Abstract class can implement an
interface, it can extend an
interface.
interface.
Abstract class declared using abstract Interface is declared using
keyword. interface keyword.
Abstract class can inherit another class
Interface can inherit only an
using extends keyword and implement
inteface.
an interface.
Abstract class can be inherited using Interface can only be implemented
extends keyword. using implements keyword.
Abstract class can have any type of Abstract class can have any type
members like private, public. of members like private, public.
Example: Example:
public abstract class Shape{ public abstract class Shape{
public abstract void draw(); public abstract void draw();
} }

4. Can abstract class have static methods in Java?

PAGE \* MERGEFORMAT 1
Yes, static methods can exist in abstract classes. They are frequently used to
implement utility functions or other class-level features.

5. Can you create instance of abstract class?


Abstract classes cannot be instantiated, but they can be subclassed. When an abstract
class is subclassed, the subclass usually provides implementations for all of the abstract
methods in its parent class.

6. Are all the methods in an abstract class are abstract?

An abstract class may contain abstract methods, that is, methods with no
implementation.

Ex. No. 5 PROGRAM TO IMPLEMENT USER


DEFINED EXCEPTION HANDLING
Date :

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;

class MyException extends Exception{


String str1;
MyException(String str2) {
str1=str2;
}
public String toString(){
return ("MyException Occurred: "+str1) ;
}
}
public class Example1 {

public static void main(String[] args)

{
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.

2. What is difference between throw and throws keyword in Java?


BASIS OF
THROW THROWS
COMPARISON
The throw keyword
The throws keyword is used to delegate
handover our created
Basic the responsibility of exception handling
exception object to
to the caller of the method.
JVM manually.
return_typemethod_name(parameter-list)
throws ExceptionClass_list
throw Throwable-
Syntax {
instance;
// body of method
}
The throw keyword is The throws keyword is followed by the
Followed by followed by exception list of the exception classes that can
object. occur in the method.
Number of The throw keyword The throws keyword can declare
Exception can throw a single multiple exception classes separated by a
thrown exception instance. comma.

3. Can we have an empty catch block?

PAGE \* MERGEFORMAT 1
Yes, we can have an empty catch block. But this is a bad practice to implement in Java.

4. What happens when exception is thrown by main method?


The main method should simply terminate if any exception occurs. The throws clause
only states that the method throws a checked FileNotFoundException and the calling
method should catch or rethrow it. If a non-checked exception is thrown (and not catch) in
the main method, it will also terminate.

5. What is the difference between error and exception 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.

Ex. No. 6 PROGRAM TO IMPLEMENT


MULTITHREADED APPLICATION
Date :

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.*;

class even implements Runnable{


public int x;
public even(int x){
this.x=x;
}

@Override
public void run()
{
System.out.println("Thread Name:Even Thread and square is: " + x * x);

class odd implements Runnable{


public int x;
public odd(int x){
this.x=x;
}
@Override
PAGE \* MERGEFORMAT 1
public void run()
{
System.out.println("Thread Name:Odd Thread and cube is :"+ x * 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());
}
}
}

public class Mtherad {

public static void main(String[] args) {


A a=new A("one");
PAGE \* MERGEFORMAT 1
a.start();
}

OUTPUT:

4.0 Result:
Thus above program executed and output is verified.

REVIEW QUESTIONS:

1. What is the difference between Process and Thread?

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.

2. What is difference between user Thread and daemon Thread?

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.

4. Which is more preferred – Synchronized method or Synchronized block?


The system performance may degrade because of the slower working of
synchronized keyword. Java synchronized block is more efficient than Java synchronized
method.

5. Why Thread sleep() and yield() methods are static?


This is because whenever you are calling these methods, those are applied on
the same thread that is running. You can't tell another thread to perform some operation like,
sleep() or wait

Ex. No. 7 PROGRAM FOR DISPLAYING FILE INFORMATION

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;

public 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());

PAGE \* MERGEFORMAT 1
}

Fib.java

public class Fib {

public static void main(String[] args) {


int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);

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.

4. What is the difference between System.out , System.err and System.in?


System.in is the input stream connected to the console, much as System. out is the
output stream connected to the console.

5. Which exceptions should be handled with the following code?

File Output Streamfile Output Stream = new FileOutputStream(new


File("newFile.txt"));

Ex. No. 8 DEVELOP APPLICATIONS TO DEMONSTRATE THE


FEATURES OF GENERICS CLASSES
Date :

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:

// Java program to show multiple


// type parameters in Java Generics

// We use < > to specify Parameter type


class Test<T, U>
{
T obj1; // An object of type T
U obj2; // An object of type U

// constructor
Test(T obj1, U obj2)
{
this.obj1 = obj1;
this.obj2 = obj2;
}

// To print objects of T and U


public void print()
{
System.out.println(obj1);
System.out.println(obj2);
}
}

// Driver class to test above


class Main
{
public static void main (String[] args)
{
Test <String, Integer> obj =
new Test<String, Integer>("KCG", 15);

obj.print();
}
}
PAGE \* MERGEFORMAT 1
OUTPUT:

15
KCG

4.0 Result:
Thus above program executed and output is verified.

REVIEW QUESTIONS:

1. What are advantages of using Generics?


Generics shift the burden of type safety from you to the compiler. There is no need to write
code to test for the correct data type because it is enforced at compile time.

2. How Can We Restrict Generics To A Super Class Of Particular Class?


Whenever you want to restrict the type parameter to subtypes of a particular
class you can use the bounded type parameter.

3. How To Write Parameterized Class In Java Using Generics ?


1. Syntax. public class Box<T> { private T t; } ...
2.Description. The T is a type parameter passed to the generic class Box and
should be passed when a Box object is created.

PAGE \* MERGEFORMAT 1
4. Can you give an example of a Generic Method?
<String>genericMethod("Java Programming"); demo.
<Integer>genericMethod(25);

EX NO: 9 JAVA FX CONTROLS,LAYOUTS AND MENU

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

You might also like