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

OOPS Manual Updated-2

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

OOPS Manual Updated-2

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

Ex.No.

:1 Sorting algorithms
Date:
Aim:

Procedure :

1.Selection Sort in Java

We can create a java program to sort array elements using selection sort.

Selection Sort Java Example Program1:

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+" ");
}
}
}
Output:

Before Selection Sort


9
14
3
2
43
11
58
22
After Selection Sort
2
3
9
11
14
22
43
58

Selection Sort Java Example Program2:

element in the temp and the second element in the first, and then temp in the second
number and continue for the next match to sort the whole array in ascending order.

import java.util.Scanner;

public class SelectionSortExample2


{
public static void main(String args[])
{
int size, i, j, temp;
int arr[] = new int[50];
Scanner scan = new Scanner(System.in);

System.out.print("Enter Array Size : ");


size = scan.nextInt();

System.out.print("Enter Array Elements : ");


for(i=0; i<size; i++)
{
arr[i] = scan.nextInt();
}

System.out.print("Sorting Array using Selection Sort Technique..\n");


for(i=0; i<size; i++)
{
for(j=i+1; j<size; j++)
{
if(arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

System.out.print("Now the Array after Sorting is :\n");


for(i=0; i<size; i++)
{
System.out.print(arr[i]+ " ");
}
}
}
Output:

Before Selection Sort


9
14
3
2
43
11
58
22

After Selection Sort


2
3
9
11
14
22
43
58

2.Insertion Sort in Java

Simple java program to sort an array using insertion sort algorithm.

public class InsertionSortExample {

public static void insertionSort(int array[]) {

int n = array.length;

for (int j = 1; j < n; j++) {

int key = array[j];

int i = j-1;

while ( (i > -1) && ( array [i] > key ) ) {

array [i+1] = array [i];

i--;

array[i+1] = key;

public static void main(String a[]){

int[] arr1 = {9,14,3,2,43,11,58,22};

System.out.println("Before Insertion Sort");

for(int i:arr1){

System.out.print(i+" ");

System.out.println();
insertionSort(arr1);//sorting array using insertion sort

System.out.println("After Insertion Sort");

for(int i:arr1){

System.out.print(i+" ");

Output:

Before Insertion Sort

14

43

11

58

22

After Insertion Sort

11
14

22

43

58

3.Quick Sort Algorithm

Algorithm

QUICKSORT (array A, start, end)

1 if (start < end)

2{

3 p = partition(A, start, end)

4 QUICKSORT (A, start, p - 1)

5 QUICKSORT (A, p + 1, end)

6}

Quick Sort Algorithm

Program: Write a program to implement quicksort in Java.

public class Quick

/* function that consider last element as pivot,

place the pivot at its exact position, and place

smaller elements to left of pivot and greater


elements to right of pivot. */

int partition (int a[], int start, int end)

int pivot = a[end]; // pivot element

int i = (start - 1);

for (int j = start; j <= end - 1; j++)

// If current element is smaller than the pivot

if (a[j] < pivot)

i++; // increment index of smaller element

int t = a[i];

a[i] = a[j];

a[j] = t;

int t = a[i+1];

a[i+1] = a[end];

a[end] = t;

return (i + 1);

/* function to implement quick sort */


void quick(int a[], int start, int end) /* a[] = array to be sorted, start = Starting
index, end = Ending index */

if (start < end)

int p = partition(a, start, end); //p is partitioning index

quick(a, start, p - 1);

quick(a, p + 1, end);

/* function to print an array */

void printArr(int a[], int n)

int i;

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

System.out.print(a[i] + " ");

public static void main(String[] args) {

int a[] = { 13, 18, 27, 2, 19, 25 };

int n = a.length;

System.out.println("\nBefore sorting array elements are - ");

Quick q1 = new Quick();

q1.printArr(a, n);

q1.quick(a, 0, n - 1);
System.out.println("\nAfter sorting array elements are - ");

q1.printArr(a, n);

System.out.println();

Output:

Result :

Thus the sorting algorithm was created and executed successfully.

Ex.No.2 Factorial Program in Java

Date:

Factorial Program in Java

Factorial Program in Java: Factorial of n is the product of all positive descending


integers. Factorial of n is denoted by n!. For example:

4! = 4*3*2*1 = 24

5! = 5*4*3*2*1 = 120

There are many ways to write the factorial program in java language. Let's see the 2
ways to write the factorial program in java.

1.Factorial Program using loop

2.Factorial Program using recursion


Facltorial Program using loop in java.

class FactorialExample{

public static void main(String args[]){

int i,fact=1;

int number=5;//It is the number to calculate factorial

for(i=1;i<=number;i++){

fact=fact*i;

System.out.println("Factorial of "+number+" is: "+fact);

Output:

Factorial of 5 is: 120

Factorial program in java using recursion.

class FactorialExample2{

static int factorial(int n){

if (n == 0)

return 1;

else

return(n * factorial(n-1));

public static void main(String args[]){

int i,fact=1;
int number=4;//It is the number to calculate factorial

fact = factorial(number);

System.out.println("Factorial of "+number+" is: "+fact);

Output:

Factorial of 4 is: 24

Ex.No:3 To calculate mileage

Date:

Aim:

Program:

import java.util.Scanner;

class MpgCal

double mpg;

MpgCal(double k,double g)

double m=k/1.609344;

mpg= m/g;

}
}

class Mpg

public static void main(String arg[])

Scanner scan = new Scanner(System.in);

System.out.println("Enter kilo meters travelled : ");

double km = scan.nextDouble();

System.out.println("Enter gallons : ");

double gallons= scan.nextDouble();

MpgCal n=new MpgCal(km,gallons);

System.out.println("miles per gallons = "+Math.round(n.mpg));

Output:

Enter kilo meters travelled :

20

Enter gallons :

miles per gallons = 3

Another program

import java.util.Scanner;

public class MagicNumber


{

public static void main(String[] args)

float AvgMPG = 0;

int MilesDriven = 0;

int totalTrips = 0;

int GallonsUsed = 0;

int totalMilesPerGallon = 0;

int MilesPerGallon = 0;

Scanner input = new Scanner(System.in);

System.out.println("Enter Miles Driven or -1 to quit: ");

MilesDriven = input.nextInt();

System.out.println("Enter Gallons used to fill tank or -1 to quit: ");

GallonsUsed = input.nextInt();

while ( MilesDriven != -1)

MilesPerGallon = MilesDriven / GallonsUsed;

System.out.println("Miles Per Gallon for this trip: "


+MilesPerGallon);

totalMilesPerGallon = MilesPerGallon + totalMilesPerGallon;


totalTrips = totalTrips + 1;

System.out.println("Enter Miles Driven or -1 to quit: ");

MilesDriven = input.nextInt();

System.out.println("Enter Gallons used to fill tank or -1 to quit: ");

GallonsUsed = input.nextInt();

if (totalTrips != 0)

System.out.println("Number of trips taken: "+ totalTrips);

AvgMPG = (float) totalMilesPerGallon / totalTrips;

System.out.println("Total Miles Per Gallon for all trips is :"


+totalMilesPerGallon);

System.out.println("Average Miles Per Gallon Per Trip is :" +AvgMPG);

else

System.out.println("No data entered");

}
}

Output:-

Result:-

Ex.no:4

Date:

String stringDate="2019-07-15";

Date date1=new SimpleDateFormat("yyyy-MM-dd").parse(stringDate);

Calendar cal = Calendar.getInstance();

cal.setTime(date1);

// manipulate date

cal.add(Calendar.DATE, 5);

Date dateWith5Days = cal.getTime();


System.out.println(dateWith5Days);

Ex.no:5 Package

Date:

//save as Simple.java

package mypack;

public class Simple{

public static void main(String args[]){

System.out.println("Welcome to package");

How to compile and run java package

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

Output:
Welcome to package

Ex.no:6 Interface

Date:

Program:

interface Printable

void print();

interface Showable extends Printable

void show();

class TestInterface4 implements Showable

public void print()

System.out.println("Hello");

}
public void show()

System.out.println("Welcome");

public static void main(String args[])

TestInterface4 obj = new TestInterface4();

obj.print();

obj.show();

Output:

Hello

Welcome

Ex.no:7 Implements a Stack ADT that Converts the infix expression into postfix
expression

Date:

Aim:-
Algorithm:-

1. Scan the infix notation from left to right one character at a time.
2. If the next symbol scanned as an operand, append it to the postfix string.
3. If the next symbol scanned as an operator, the:
4. Pop and append to the postfix string every operator on the stack that:
5. Is above the most recently scanned left parenthesis, and
6. Has precedence higher than or is a right-associative operator of equal
precedence to that of the new operator symbol.
7. Push the new operator onto the stack
8. If a left parenthesis is scanned, push it into the stack.
9. If a right parenthesis is scanned, all operators down to the most recently
scanned left parenthesis must be popped and appended to the postfix string.
Furthermore, the pair of parentheses must be discarded.
10. When the infix string is fully scanned, the stack may still contain some
operators. All the remaining operators should be popped and appended to the
postfix string.

Program:-

import java.io.*;

class Stack

char a[]=new char[100];

int top=-1;

void push(char c)

try

a[++top]= c;

catch(StringIndexOutOfBoundsException e)
{

System.out.println("Stack full, no room to push, size=100");

System.exit(0);

char pop()

return a[top--];

boolean isEmpty()

return (top==-1)?true:false;

char peek()

return a[top];

public class InfixToPostfix

static Stack operators = new Stack();

public static void main(String argv[]) throws IOException

String infix;

//create an input stream object


BufferedReader keyboard = new BufferedReader (new
InputStreamReader(System.in));

//get input from user

System.out.print("\nEnter the infix expression you want to convert: ");

infix = keyboard.readLine();

//output as postfix

System.out.println("Postfix expression for the given infix expression is:" +


toPostfix(infix));

private static String toPostfix(String infix)

//converts an infix expression to postfix

char symbol;

String postfix = "";

for(int i=0;i<infix.length();++i)

//while there is input to be read

symbol = infix.charAt(i);

//if it's an operand, add it to the string

if (Character.isLetter(symbol))

postfix = postfix + symbol;

else if (symbol=='(')

//push (

operators.push(symbol);

}
else if (symbol==')')

//push everything back to (

while (operators.peek() != '(')

postfix = postfix + operators.pop();

operators.pop(); //remove '('

else

//print operators occurring before it that have greater precedence

while (!operators.isEmpty() && !(operators.peek()=='(') && prec(symbol) <=


prec(operators.peek()))

postfix = postfix + operators.pop();

operators.push(symbol);

while (!operators.isEmpty())

postfix = postfix + operators.pop();

return postfix;

static int prec(char x)

if (x == '+' || x == '-')
return 1;

if (x == '*' || x == '/' || x == '%')

return 2;

return 0;

Output:

Result:-

Ex.no:8 Read a file line by line.

Date:

There are following ways to

BufferedReader Class

Scanner class

Using BufferedReader Class

Using the Java BufferedRedaer class is the most common and simple way to read a
file line by line in Java. It belongs to java.io package. Java BufferedReader class
provides readLine() method to read a file line by line. The signature of the method
is:

public String readLine() throws IOException


The method reads a line of text. It returns a string containing the contents of the
line. The line must be terminated by any one of a line feed ("\n") or carriage return
("\r").

Example of read a file line by line using BufferedReader class

In the following example, Demo.txt is read by FileReader class. The readLine()


method of BufferedReader class reads file line by line, and each line appended to
StringBuffer, followed by a linefeed. The content of the StringBuffer are then
output to the console.

Program:-

import java.io.*;

public class ReadLineByLineExample1

public static void main(String args[])

try

File file=new File("Demo.txt"); //creates a new file instance

FileReader fr=new FileReader(file); //reads the file

BufferedReader br=new BufferedReader(fr); //creates a buffering character input


stream

StringBuffer sb=new StringBuffer(); //constructs a string buffer with no


characters

String line;

while((line=br.readLine())!=null)
{

sb.append(line); //appends line to string buffer

sb.append("\n"); //line feed

fr.close(); //closes the stream and release the resources

System.out.println("Contents of File: ");

System.out.println(sb.toString()); //returns a string that textually represents the


object

catch(IOException e)

e.printStackTrace();

Output:

Example of read a file line by line using Scanner class

import java.io.*;

import java.util.Scanner;

public class ReadLineByLineExample2


{

public static void main(String args[])

try

//the file to be opened for reading

FileInputStream fis=new FileInputStream("Demo.txt");

Scanner sc=new Scanner(fis); //file to be scanned

//returns true if there is another line to read

while(sc.hasNextLine())

System.out.println(sc.nextLine()); //returns the line that was skipped

sc.close(); //closes the scanner

catch(IOException e)

e.printStackTrace();

Output:
Result:-

Ex.no:9 Copy the content of the one file to another file using fileinput streams

Date:

FileInputStream fin = new FileInputStream(filename);

This creates a FileInputStream object fin given a filename to it from where it will
copy the content or do read operation.

Methods used:

1. read(): This method is used to read a byte of data. It returns that byte as an
integer value or return -1 if the end of file is reached.

2. close(): This method is used to close the FileInputStream.

FileOutputStream Class

It is a byte output stream class which helps in writing the bytes to a file. It provides
different functions to write the data to a file.

FileOutputStream fout = new FileOutputStream(filename);


This creates a FileOutputStream object fout given a filename to which it will write
the read content.

Methods used:

1. write(): This method is used to write a byte of data to the FileOutputStream.

2. close(): This method is used to close the FileInputStream.

File Class

File f = new File(filename);

Program:-

import java.io.*;

import java.util.*;

public class CopyFromFileaToFileb {

public static void copyContent(File a, File b) throws Exception

FileInputStream in = new FileInputStream(a);

FileOutputStream out = new FileOutputStream(b);

try {

int n;

// read() function to read the


// byte of data

while ((n = in.read()) != -1) {

// write() function to write

// the byte of data

out.write(n);

finally {

if (in != null) {

// close() function to close the

// stream

in.close();

// close() function to close

// the stream

if (out != null) {

out.close();

System.out.println("File Copied");

public static void main(String[] args) throws Exception

Scanner sc = new Scanner(System.in);

// get the source file name


System.out.println(

"Enter the source filename from where you have to read/copy :");

String a = sc.nextLine();

// source file

File x = new File(a);

// get the destination file name

System.out.println(

"Enter the destination filename where you have to write/paste :");

String b = sc.nextLine();

// destination file

File y = new File(b);

// method called to copy the

// contents from x to y

copyContent(x, y);

Output:-

Enter the source filename from where you have to read/copy :

sourcefile.txt

Enter the destination filename where you have to write/paste :

destinationfile.txt

File Copied

Another program:-

import java.io.File;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.io.IOException;

public class CopyExample {

public static void main(String[] args) {

FileInputStream ins = null;

FileOutputStream outs = null;

try {

File infile = new File("C:\\Users\\TutorialsPoint7\\Desktop\\abc.txt");

File outfile = new File("C:\\Users\\TutorialsPoint7\\Desktop\\bbc.txt");

ins = new FileInputStream(infile);

outs = new FileOutputStream(outfile);

byte[] buffer = new byte[1024];

int length;

while ((length = ins.read(buffer)) > 0) {

outs.write(buffer, 0, length);

ins.close();

outs.close();

System.out.println("File copied successfully!!");

} catch(IOException ioe) {

ioe.printStackTrace();

}
}

Output:-

File copied successfully!!

Result:-

Ex.no:10 Array Index out of bound Exception

Date:

Aim:-

Procedure :-

Program:-

public class ArrayIndexOutOfBoundException {

public static void main(String[] args) {

String[] arr = {"Rohit","Shikar","Virat","Dhoni"};

//Declaring 4 elements in the String array

for(int i=0;i<=arr.length;i++) {

//Here, no element is present at the iteration number arr.length, i.e 4


System.out.println(arr[i]);

//So it will throw ArrayIndexOutOfBoundException at iteration 4

Output:

Result:-

Ex.no:-11 Custom Exception

Date:

class representing custom exception

class InvalidAgeException extends Exception

public InvalidAgeException (String str)

// calling the constructor of parent Exception

super(str);

}
// class that uses custom exception InvalidAgeException

public class TestCustomException1

// method to check the age

static void validate (int age) throws InvalidAgeException{

if(age < 18){

// throw an object of user defined exception

throw new InvalidAgeException("age is not valid to vote");

else {

System.out.println("welcome to vote");

// main method

public static void main(String args[])

try

// calling the method

validate(13);

catch (InvalidAgeException ex)


{

System.out.println("Caught the exception");

// printing the message from InvalidAgeException object

System.out.println("Exception occured: " + ex);

System.out.println("rest of the code...");

Output:

Anorher program :-

public class JavaExceptionExample{

public static void main(String args[]){

try{

//code that may raise exception

int data=100/0;

}catch(ArithmeticException e){System.out.println(e);}

//rest code of the program

System.out.println("rest of the code...");

}
Test it Now

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero

rest of the code...

Result :-

Ex.no:12 Multithreading

Date :

Program:-

File Name : DisplayMessage.java

// Create a thread to implement Runnable

public class DisplayMessage implements Runnable {

private String message;

public DisplayMessage(String message) {

this.message = message;

public void run() {

while(true) {

System.out.println(message);

}
}

}
Following is another class which extends the Thread class −

// File Name : GuessANumber.java

// Create a thread to extentd Thread

public class GuessANumber extends Thread {

private int number;

public GuessANumber(int number) {

this.number = number;

public void run() {

int counter = 0;

int guess = 0;

do {

guess = (int) (Math.random() * 100 + 1);

System.out.println(this.getName() + " guesses " + guess);

counter++;

} while(guess != number);

System.out.println("** Correct!" + this.getName() + "in" + counter +


"guesses.**");

}
Following is the main program, which makes use of the
above-defined classes −

// File Name : ThreadClassDemo.java

public class ThreadClassDemo {

public static void main(String [] args) {

Runnable hello = new DisplayMessage("Hello");

Thread thread1 = new Thread(hello);

thread1.setDaemon(true);

thread1.setName("hello");

System.out.println("Starting hello thread...");

thread1.start();

Runnable bye = new DisplayMessage("Goodbye");

Thread thread2 = new Thread(bye);

thread2.setPriority(Thread.MIN_PRIORITY);

thread2.setDaemon(true);

System.out.println("Starting goodbye thread...");

thread2.start();

System.out.println("Starting thread3...");

Thread thread3 = new GuessANumber(27);

thread3.start();

try {
thread3.join();

} catch (InterruptedException e) {

System.out.println("Thread interrupted.");

System.out.println("Starting thread4...");

Thread thread4 = new GuessANumber(75);

thread4.start();

System.out.println("main() is ending...");

This will produce the following result. You can try this example again and again
and you will get a different result every time.

Output:-

Starting hello thread...

Starting goodbye thread...

Hello

Hello

Hello

Hello

Hello

Hello

Goodbye

Goodbye
Goodbye

Goodbye

Goodbye

.......

Result:-

Ex.no:13 Applet

Date:

Program:

//First.java

import java.applet.Applet;

import java.awt.Graphics;

public class First extends Applet{

public void paint(Graphics g){

g.drawString("welcome",150,150);

Note: class must be public because its object is created by Java Plugin software that
resides on the browser.
myapplet.html

<html>

<body>

<applet code="First.class" width="300" height="300">

</applet>

</body>

</html>

Simple example of Applet by appletviewer tool:

To execute the applet by appletviewer tool, create an applet that contains applet tag
in comment and compile it. After that run it by: appletviewer First.java. Now Html
file is not required but it is for testing purpose only.

//First.java

import java.applet.Applet;

import java.awt.Graphics;

public class First extends Applet{

public void paint(Graphics g){

g.drawString("welcome to applet",150,150);

/*

<applet code="First.class" width="300" height="300">

</applet>
*/

To execute the applet by appletviewer tool, write in command prompt:

c:\>javac First.java

c:\>appletviewer First.java

Result:

You might also like