You are on page 1of 23

Kautik patel id=20CE087

PART-IV
Exception Handling

WAP to show the try - catch block to catch the different types of exception.
1.
package practical;
Code
public class p4p1 {
public static void main(String[] args) {

try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception
occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the Code");
System.out.println("Created by : Kautik
Patel(20CE087)");
}

Outp
ut

1
CE257 Java Programming
Kautik patel id=20CE087

WAP to generate user defined exception using “throw” and “throws” keyword.
2.
package practical;
Code
public class p4p2 extends Exception{
//store account information
static int accno[] = {1, 2, 3, 4};
static String name[] = {"Kautik", "Suraj", "Pratik", "Raj",
"Ram"};
static double bal[] = {16560.00, 46782.00, 3289.0, 657.00,
8725.55};
// default constructor
p4p2() {}
// parameterized constructor
p4p2(String str) {
super(str);
}
public static void main(String args[])
{
// User Defined Exception - Prac_2
try {
System.out.println("Account No." + "\t" + "Customer Name" + "\
t" + "Balance");
for (int i = 0; i < 5 ; i++)
{
System.out.println(accno[i] + "\t" + name[i] + "\t" + bal[i]);
if (bal[i] < 1000)
{
p4p2 me =
new p4p2("Balance is less than 1000");
throw me;
}
}
}
catch (p4p2 e) {
System.out.println("This is Low Balance Exception - User
Defined");
}
System.out.println("\nprepare by : 20CE087 - Kautik
PATEL");
}

2
CE257 Java Programming
Kautik patel id=20CE087

Outp
ut

Write a program that raises two exceptions. Specify two ‘catch’ clauses for the two
3. exceptions. Each ‘catch’ block handles a different type of exception. For example the
exception could be ‘ArithmeticException’ and ‘ArrayIndexOutOfBoundsException’.
Display a message in the ‘finally’ block.

package practical;
Code
public class p4p3 {
public static void main(String args[]){
try{
int arr[]=new int[7];
arr[4]=30/0;
System.out.println("Last Statement of try block");
}
catch(ArithmeticException e){
System.out.println("You should not divide a number by
zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Accessing array elements outside of
the limit");

}
try{
int arr[]=new int[7];
arr[10]=10/5;
System.out.println("Last Statement of try block");
}
catch(ArithmeticException e){
System.out.println("You should not divide a number by
zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Accessing array elements outside of
the limit");
}
finally
{
System.out.println("ProgrammeSuccesful:-");

3
CE257 Java Programming
Kautik patel id=20CE087

System.out.println("Created By :Kautik Patel(20CE087)


");

}
}

Outp
ut

Part-V
File Handling & Streams
WAP to show how to create a file with different mode and methods of File class to
1. find path, directory etc.

package practical;
Code
import java.io.File;

// Displaying file property

public class p5p1 {


public static void main(String[] args) {
//accept file name or directory name through command
line args
//String fname =args[0];

//pass the filename or directory name to File object


File f = new File("final.txt");

//apply File class methods on File object


System.out.println("File name :"+f.getName());

4
CE257 Java Programming
Kautik patel id=20CE087

System.out.println("Path: "+f.getPath());
System.out.println("Absolute path:"
+f.getAbsolutePath());
System.out.println("Parent:"+f.getParent());
System.out.println("Exists :"+f.exists());
if(f.exists())
{
System.out.println("Is writeable:"+f.canWrite());
System.out.println("Is readable"+f.canRead());
System.out.println("Is a
directory:"+f.isDirectory());
System.out.println("File Size in bytes
"+f.length());
}
System.out.println("\nPrepared by:- Kautik PATEL (20CE087) ");
}

Outp
ut

When to use Character Stream over Byte Stream? When to use Byte Stream over
2. Character Stream? Give example
Ans In Java, characters are stored using Unicode conventions. Character stream is
useful when we want to process text files.
These text files can be processed character by character. A character size is
typically 16 bits.
Byte oriented reads byte by byte. A byte stream is suitable for processing
raw data like binary files.

Outpu
t

Write a program to transfer data from one file to another file so that if the
3. destination file does not exist, it is created.

package practical;
Code //part5pr3

5
CE257 Java Programming
Kautik patel id=20CE087

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 instream = null;
FileOutputStream outstream = null;

try{
File infile =new File("C:\\Users\\admin\\eclipse-
workspace\\practical\\src\\MyInputFile.txt");
File outfile =new File("C:\\Users\\admin\\eclipse-
workspace\\practical\\src\\MyOutputFile.txt");

instream = new FileInputStream(infile);


outstream = new FileOutputStream(outfile);

byte[] buffer = new byte[1024];

int length;
/*copying the contents from input stream to
* Output stream using read and write methods
*/
while ((length = instream.read(buffer)) > 0){
outstream.write(buffer, 0, length);
}

//Closing the input/Output file streams


instream.close();
outstream.close();

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

}catch(IOException ioe){
ioe.printStackTrace();
}
System.out.println("\nPrepared by Kautik PATEL
(20CE087)");
}

Outpo
ut

6
CE257 Java Programming
Kautik patel id=20CE087

WAP to show use of character and byte stream.


4.
package practical;
Code import java.io.*;
public class P5p4 {
public static void main(String[] args) throws IOException
{
FileReader sourceStream = null;
try
{
sourceStream = new FileReader("C:\\Users\\admin\\
eclipse-workspace\\practical\\src\\MyInputFile.txt");

int temp;
while ((temp = sourceStream.read()) != -1)
System.out.println((char)temp);
}
finally
{
// Closing stream as no longer in use
if (sourceStream != null)
sourceStream.close();
}
System.out.println("\nBy 20CE087-Kautik Patel ");
}

Outp
ut

Write a program to enter any 15 numbers from the user and store only even
5. numbers in a file named “Even.txt”. And display the contents of this file on the
console. (BufferedReader /BufferedWriter).
package practical;
Code import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

public class P5p5 {


public static void main(String[] args) throws IOException
{
BufferedReader bufr = null;
BufferedWriter bufw = null;
FileReader in = null;
FileWriter out = null;
String filelocation = "C:\\Users\\\\tisha\\\\eclipse-
workspace\\\\Practicals\\Even.txt";

7
CE257 Java Programming
Kautik patel id=20CE087

File file = new File(filelocation);


try
{
out= new FileWriter("Even.txt");
bufw= new BufferedWriter(out);
ArrayList<Integer> num = new
ArrayList<Integer>(15);
System.out.println("Please Enter 15 Numbers one by
one ...");
for(int i=0;i<15;i++)
{
Scanner sc= new Scanner(System.in);
num.add(sc.nextInt());
}
for(int i=0;i<15;i++)
{
if(((num.get(i))%2==0))
{
bufw.write(num.get(i));

}
}
bufw.close();
int abc;
in= new FileReader("Even.txt");
bufr= new BufferedReader(in);
System.out.println("");
System.out.println("Now Printing Even Numbers from
Even.txt ...");
while ((abc=bufr.read())!=-1)
{
System.out.println((abc));
}
}
catch(Exception e)
{
System.out.println(" Some exception occured !!
Please Write integer ");
}
finally
{
if (bufr != null)
{
bufr.close();
}
System.out.println("\nprepare By 20CE087-
kautik Patel " );
}
}

8
CE257 Java Programming
Kautik patel id=20CE087

Outp
ut

9
CE257 Java Programming
Kautik patel id=20CE087

PART-VI
Multithreading
Write a program to create thread which display “Hello World” message.
1. A. by extending Thread class
B. by using Runnable interface
package practical;
Cod
e
public class Example1a {
public static void main(String[] args)
{
NewThread nt = new NewThread();
nt.start();
try{
Thread.sleep(1000);
}

catch(InterruptedException e)
{

System.out.println("Interrupted");
}
System.out.println("Created by : Kautik Patel(20CE087)");
}

}
class NewThread extends Thread
{
//Thread t = new Thread(this,"demothread");

public void run()


{
System.out.println("Hello World.");
}
}
Outpu
t

B. by using Runnable interface.

Code package practical;

public class Example1a {


public static void main(String[] args)
{

10
CE257 Java Programming
Kautik patel id=20CE087

NewThread nt = new NewThread();


nt.t.start();
try{
//System.out.println("In main thread");
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("Created by : Kautik Patel(20CE087) ");
}

}
class NewThread implements Runnable
{
Thread t = new Thread(this,"demothread");

public void run()


{
System.out.println("Hello World.");
}
}

Outp
ut

2. Generate 15 random numbers from 1 to 100 and store it in an int array. Write a
program to display the numbers stored at odd indexes by thread1 and display
numbers stored at even indexes by thread2
Code package com.company;

class EvenDisplayThread implements Runnable


{

String Name;
int Array[];
Thread RefThread;

EvenDisplayThread()
{
this.Name = null;
this.Array = null;
this.RefThread = null;
}

EvenDisplayThread(String Name,int Array[])


{
this.Name = Name;
this.RefThread = new Thread(this,this.Name);

11
CE257 Java Programming
Kautik patel id=20CE087

this.Array = Array;
}

@Override
public void run()
{
System.out.println("--> Starting "+this.Name);
for(int i=0;i<this.Array.length;i++)
{
if(i%2==0)
{
System.out.println("Array["+i+"] = "+this.Array[i]);
}
}
System.out.println("--> Exiting "+this.Name);
}
}

class OddDisplayThread implements Runnable


{

String Name;
int Array[];
Thread RefThread;

OddDisplayThread()
{
this.Name = null;
this.Array = null;
this.RefThread = null;
}

OddDisplayThread(String Name,int Array[])


{
this.Name = Name;
this.RefThread = new Thread(this,this.Name);
this.Array = Array;
}

@Override
public void run()
{
System.out.println("--> Starting "+this.Name);
for(int i=0;i<this.Array.length;i++)
{
if(i%2!=0)
{
System.out.println("Array["+i+"] = "+this.Array[i]);
}
}
System.out.println("--> Exiting "+this.Name);
}
}

12
CE257 Java Programming
Kautik patel id=20CE087

public class Part6Practical2 {

static int GenerateRandom(int Min,int Max)


{
//Math.random() will return "0-1" any random double value
return (int)(Math.random()*(Max-Min+1)+Min);
}

public static void main(String[] args) {

int Array[] = new int[15];

for(int i=0;i<Array.length;i++)
{
Array[i] = GenerateRandom(0,100);
}

EvenDisplayThread t1 = new EvenDisplayThread("Even Display",Array);


t1.RefThread.start();
OddDisplayThread t2 = new OddDisplayThread("Odd Display",Array);
t2.RefThread.start();

Outp
ut

3. Write a program to increment the value of one variable by one and display it after one
second using thread using sleep() method.

Code package practical;


import java.util.*;
class Increment extends Thread{
int n;

13
CE257 Java Programming
Kautik patel id=20CE087

Increment(int n)
{

this.n=n;

}
public void run()
{

try{
Thread.sleep(1000);
System.out.println("incremented by : "+ (n+1) );
System.out.println("Created by : Kautik Patel(20ce087) ");
}
catch(InterruptedException e)
{
System.out.println("Interrupted THREAD");
}
}
}

public class P6p3 {


public static void main(String args[]){
int n1;
System.out.println("enter number to be incremented by
1 :");

Scanner sc=new Scanner(System.in);

n1=sc.nextInt();
Increment t1=new Increment(n1);
t1.start();
}

}
Outp
ut

4. Write a program to create three threads ‘FIRST’, ‘SECOND’, ‘THIRD’. Set the priority of
the ‘FIRST’ thread to 3, the ‘SECOND’ thread to 5(default) and the ‘THIRD’ thread to 7.

Code package com.company;

class Priority implements Runnable {

String name;
String temp;
Thread t;

// Creating thread, set name and set priority using constructor


Priority(String name, String temp, int priority) {
this.name = name;

14
CE257 Java Programming
Kautik patel id=20CE087

this.temp =temp;
t = new Thread(this, name);
t.setPriority(priority);
System.out.println(t);
}

// Overriding the run method


@Override
public void run() {
System.out.println(temp);
}
}

public class Part6Practical4 {


public static void main(String[] args) {

// pass name of thread and priority


Priority first = new Priority("FIRST", "This is first thread", 3);
Priority second = new Priority("SECOND", "This is second thread", 5);
Priority third = new Priority("THIRD", "This is third thread", 7);

System.out.println();

first.t.start();
second.t.start();
third.t.start();

}
}

Outp
ut

5. Write a program to solve producer-consumer problem using thread


Code package com.company;

class Shop
{
private int materials;
private boolean available = false;

15
CE257 Java Programming
Kautik patel id=20CE087

public synchronized int get()


{
while (available == false)
{
try
{
wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
available = false;
notifyAll();
return materials;
}
public synchronized void put(int value)
{
while (available == true)
{
try
{
wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
materials = value;
available = true;
notifyAll();
}
}
class Consumer extends Thread
{
private Shop Shop;
private int number;
public Consumer(Shop c, int number)
{
Shop = c;
this.number = number;
}
public void run()
{
int value = 0;
for (int i = 0; i < 10; i++)
{
value = Shop.get();
System.out.println("Consumed value " + this.number+ " got: " + value);
}
}
}

16
CE257 Java Programming
Kautik patel id=20CE087

class Producer extends Thread


{
private Shop Shop;
private int number;

public Producer(Shop c, int number)


{
Shop = c;
this.number = number;
}
public void run()
{
for (int i = 0; i < 10; i++)
{
Shop.put(i);
System.out.println("Produced value " + this.number+ " put: " + i);
try
{
sleep((int)(Math.random() * 100));
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
}

public class Part6Practical5


{
public static void main(String[] args)
{
Shop c = new Shop();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}

17
CE257 Java Programming
Kautik patel id=20CE087

Outp
ut

PART-VII
Collection Framework and Generic
Create a generic method for sorting an array of Comparable
1. objects.

package practical;
Code
public class P7p1 {
public static void main(String[] args) {

// Create an Integer array

Integer[] intArray = {2, new Integer(4), new Integer(3), new


Integer(7)}; // Autoboxing is done

//int k=intArray[1]; unboxing

Double[] doubleArray = {new Double(3.4),

new Double(1.3),

new Double(-22.1),

new Double(99.78), 6.7};

18
CE257 Java Programming
Kautik patel id=20CE087

Character[] charArray = {new Character('a'), new


Character('A'), new Character('b'), new Character('B'), 'd'};

Float[] floatArray = {new Float(1.2f), new Float(3.4f), new


Float(5.7f), new Float(-3.6f)};

String[] stringArray = {"have a ", "good ", "Day!!", "Nehal",


"Tanisha"};
// Sort the arrays

sort(intArray);

sort(doubleArray);

sort(charArray);

sort(stringArray);

sort(floatArray);

// Display the sorted arrays

System.out.print("Sorted Integer objects: ");

printList(intArray);

System.out.print("Sorted Double objects: ");


printList(doubleArray);

System.out.print("Sorted Character objects: ");

printList(charArray);

System.out.print("Sorted String objects: ");

printList(stringArray);

System.out.print("Sorted Float objects: ");

printList(floatArray);

System.out.println( "\nPrepared by Kautik Patel(20CE087)");

}
public static <M extends Comparable<M>> void sort(M[] list) {

M currentMin;

int currentMinIndex;

for (int i = 0; i < list.length - 1; i++) {

// Find the minimum in the list[i+1..list.length-2]

currentMin = list[i];

19
CE257 Java Programming
Kautik patel id=20CE087

currentMinIndex = i;

for (int j = i + 1; j < list.length; j++) {

if (currentMin.compareTo(list[j]) > 0) {

currentMin = list[j];

currentMinIndex = j;
}
}

// Swap list[i] with list[currentMinIndex] if necessary;


if (currentMinIndex != i) {

list[currentMinIndex] = list[i];

list[i] = currentMin;
}
}
}
public static void printList(Object[] list) {

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

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

System.out.println();

Outp
ut

Write a program that counts the occurrences of words in a text and displays the words
2. and their occurrences in alphabetical order of the words. Using Map and Set Classes.
package practical;
Cod
e import
import
java.util.Map;
java.util.Set;
import java.util.TreeMap;
public class CountOccurencesOfWords {

public static void main(String[] args){

20
CE257 Java Programming
Kautik patel id=20CE087

String text = "Good morning. Have a good night. " + "Have a


good Day. Have fun!";

Map<String, Integer> map = new TreeMap<>();

String[] words = text.split("[ \n\t\r.,;:!?()]");

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

String key = words[i].toLowerCase();

if (key.length() > 0) {

if (!map.containsKey(key)) {

map.put(key, 1);

} else {

int value = map.get(key);

value++;

map.put(key, value);

Set<Map.Entry<String, Integer>> entrySet = map.entrySet();

for (Map.Entry<String, Integer> entry : entrySet) {

System.out.println(entry.getValue() + "\t" +
entry.getKey());

}
System.out.println(map);

System.out.println( "\nPrepared by Kautik Patel(20CE087)");


}
}

21
CE257 Java Programming
Kautik patel id=20CE087

Personal Loan Eligibility Criteria for Salaried Applicant is as follows: Eligible Age Group -21
3. years to 60 yearsMinimum Net Monthly Income -Rs. 15,000 Minimum Total Work Experience -1
year Citizenship –IndianCreate a class AccountHolder to store above given information entered
by a user. Create 5 objects of AccountHolder class and store them in an ArrayList. Display
names of account holders , who are eligible to get a loan based on given criteria.
package com.company;
Code import java.util.*;
class AccountHolder{
int age, monthlyIncome, workExperience;
String name, citizenship;
AccountHolder(int age, int monthlyIncome, int workExperience, String name,
String citizenship){
this.age=age;
this.monthlyIncome=monthlyIncome;
this.workExperience=workExperience;
this.name=name;
this.citizenship=citizenship;
}
boolean checkEligibility(){
if((age >= 21 && age <=60) && (monthlyIncome >= 15000) &&
(workExperience >= 1) && (citizenship == "Indian")){
return true;
}
else{
return false;
}
}
}
public class Part7Practical3 {
public static void main(String[] args){
AccountHolder a1 = new AccountHolder(17,16000, 1, "AccountHolder0",
"Indian");
AccountHolder a2 = new AccountHolder(22,16000, 2, "AccountHolder1",
"Indian");
AccountHolder a3 = new AccountHolder(21,20000, 1, "AccountHolder2",
"Canadian");
AccountHolder a4 = new AccountHolder(25,25000, 0, "AccountHolder3",
"Indian");
AccountHolder a5 = new AccountHolder(65,20000, 1, "AccountHolder4",
"Indian");

22
CE257 Java Programming
Kautik patel id=20CE087

ArrayList<AccountHolder> arrayList = new ArrayList<>();


arrayList.add(a1);
arrayList.add(a2);
arrayList.add(a3);
arrayList.add(a4);
arrayList.add(a5);
for(int i=0; i<5; i++){
if(arrayList.get(i).checkEligibility()){
System.out.println("AccountHolder"+i+" is eligible for personal loan");
}
else{
System.out.println("AccountHolder"+i+" is not eligible for personal loan");
}
}
System.out.println("prepare by kautik patel(20CE087)”);
}
}

Outp
ut

23
CE257 Java Programming

You might also like