Professional Documents
Culture Documents
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
}
}
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;
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;
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");
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);
}
}catch(IOException ioe){
ioe.printStackTrace();
}
System.out.println("\nPrepared by Kautik PATEL
(20CE087)");
}
Outpo
ut
6
CE257 Java Programming
Kautik patel id=20CE087
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.*;
7
CE257 Java Programming
Kautik patel id=20CE087
}
}
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");
10
CE257 Java Programming
Kautik patel id=20CE087
}
class NewThread implements Runnable
{
Thread t = new Thread(this,"demothread");
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;
String Name;
int Array[];
Thread RefThread;
EvenDisplayThread()
{
this.Name = null;
this.Array = null;
this.RefThread = null;
}
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);
}
}
String Name;
int Array[];
Thread RefThread;
OddDisplayThread()
{
this.Name = null;
this.Array = null;
this.RefThread = null;
}
@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
for(int i=0;i<Array.length;i++)
{
Array[i] = GenerateRandom(0,100);
}
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.
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");
}
}
}
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.
String name;
String temp;
Thread t;
14
CE257 Java Programming
Kautik patel id=20CE087
this.temp =temp;
t = new Thread(this, name);
t.setPriority(priority);
System.out.println(t);
}
System.out.println();
first.t.start();
second.t.start();
third.t.start();
}
}
Outp
ut
class Shop
{
private int materials;
private boolean available = false;
15
CE257 Java Programming
Kautik patel id=20CE087
16
CE257 Java Programming
Kautik patel id=20CE087
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) {
new Double(1.3),
new Double(-22.1),
18
CE257 Java Programming
Kautik patel id=20CE087
sort(intArray);
sort(doubleArray);
sort(charArray);
sort(stringArray);
sort(floatArray);
printList(intArray);
printList(charArray);
printList(stringArray);
printList(floatArray);
}
public static <M extends Comparable<M>> void sort(M[] list) {
M currentMin;
int currentMinIndex;
currentMin = list[i];
19
CE257 Java Programming
Kautik patel id=20CE087
currentMinIndex = i;
if (currentMin.compareTo(list[j]) > 0) {
currentMin = list[j];
currentMinIndex = j;
}
}
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
}
}
public static void printList(Object[] list) {
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 {
20
CE257 Java Programming
Kautik patel id=20CE087
if (key.length() > 0) {
if (!map.containsKey(key)) {
map.put(key, 1);
} else {
value++;
map.put(key, value);
System.out.println(entry.getValue() + "\t" +
entry.getKey());
}
System.out.println(map);
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
Outp
ut
23
CE257 Java Programming