1. 1
Chapter 5 Lab Manual
Program 35
//The program shown below terminates abnormally
if you enter a floating-point value instead of an
integer.
package ch5;
import java.util.Scanner;
public class ExceptionDemo {
public static void main(String args[]){
Scanner reader=new Scanner(System.in);
System.out.println("Enter a number :");
int num= reader.nextInt();
System.out.println("The number is :" +
num);
} }
Program 36
package ch4;
import java.util.Scanner;
import java.util.*;
public class ExceptionDemo {
public static void main(String args[]){
Scanner reader=new Scanner(System.in);
System.out.println("Enter a number :");
try {
int num= reader.nextInt();
System.out.println("The number is :" +
num);
}
catch (InputMismatchException e){
System.out.println("There is type mis
match :");
}
finally{
System.out.println("This part is always
done");
}} }
Program 37
package ch5;
class Example{
public static void main(String args[]) {
try{
int num=121/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("Number should not be
divided by zero");
}
/* Finally block will always execute even if there
is no exception in try block*/
finally{
System.out.println("This is finally
block");
}
System.out.println("Out of try-catch-finally");
}
}
Program 38
//multiple catch blocks
package ch5;
public class Example1 {
public static void main(String args[]) {
int num1, num2;
try {
/* We suspect that this block of statement can
throw exception so we handled it by placing these
statements inside try and handled the exception in
catch block */
num1 = 0;
num2 = 62 / num1;
System.out.println(num2);
System.out.println("Hey I'm at the end of try
block");
}
catch (ArithmeticException e) {
/* This block will only execute if any
Arithmetic exception occurs in try block */
System.out.println("You should not divide a
number by zero");
}
catch (Exception e) {
/* This is a generic Exception handler which
means it can handle all the exceptions. This will
execute if the exception is not handled by previous
catch blocks.*/
System.out.println("Exception occurred");
}
System.out.println("I'm out of try-catch block in
Java.");
}}
Program 39
// Multiple catch blocks that select the exact
exception
package ch5;
class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
System.out.println("First print statement in try
block");
}
catch(ArithmeticException e){
System.out.println("Warning:
ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning:
ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other
exception");
}
System.out.println("Out of try-catch block...");
}}
2. 2
Program 40
// The use of throw
package ch5;
public class Examplezero{
void checkAge(int age){
if(age<18)
throw new ArithmeticException("Not
Eligible for voting");
else
System.out.println("Eligible for voting");
}
public static void main(String args[]){
Examplezero obj = new Examplezero();
obj.checkAge(15);
System.out.println("End Of Program");
}
}
Program 41
// The use of throws for multiple exception selection
package ch5;
import java.io.*;
class ThrowExample {
void myMethod(int num)throws IOException,
ClassNotFoundException{
if(num==1)
thrownew IOException("IOException
Occurred");
else
thrownew
ClassNotFoundException("ClassNotFoundExcepti
on");
} }
class Examples{
public static void main(String args[]){
try{
ThrowExample obj=newThrowExample();
obj.myMethod(1);
}catch(Exception ex){
System.out.println(ex);
} }}
Program 42
package ch5;
public class throwsdividedbyzero{
int division(int a, int b) throws
ArithmeticException{
int t = a/b;
return t;}
public static void main(String args[]){
throwsdividedbyzero obj = new
throwsdividedbyzero();
try{
System.out.println(obj.division(15,0));
}
catch(ArithmeticException e){
System.out.println("You shouldn't divide
number by zero");
} } }
3. 3
Chapter 6 Lab Manual
Program 43
package ch6;
// Use a BufferedReader to read characters from the
console.
import java.io.*;
class BRRead {
public static void main(String args[])
throws IOException{
char c;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do {
c = (char)br.read();
System.out.println(c);
} while(c != 'q');
}}
Program 44
package ch6;
// Read a string from console using a
BufferedReader.
import java.io.*;
class BRReadLines {
public static void main(String args[])
throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
do {
str = br.readLine();
System.out.println(str);
}
while(!str.equals("stop"));
} }
Program 45
package ch6;
//copy byte
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyBytes {
public static void main(String[] args) throws
IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}} }}
Program 46
package ch6;
// Creating a text File using FileWriter
import java.io.FileWriter;
import java.io.IOException;
class CreateFile {
public static void main(String[] args) throws
IOException {
// Accept a string
String str = "File Handling in Java using "+
" FileWriter and FileReader";
// attach a file to FileWriter
FileWriter fw=new FileWriter("output.txt");
// read character wise from string and write
// into FileWriter
for (int i = 0; i < str.length(); i++)
fw.write(str.charAt(i));
System.out.println("Writing successful");
//close the file
fw.close();
} }
Program 47
package ch6;
// copy characters
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyCharacters {
public static void main(String[] args) throws
IOException {
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new
FileReader("xanadu.txt");
outputStream = new
FileWriter("characteroutput.txt");
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}}}}
Program 48
package ch6;
// read file from the disk
4. 4
import java.io.*;
public class FileStats{
public static void main(String[] args) throws
IOException {
// the file must be called 'temp.txt'
String s = "temp.txt";
// see if file exists
File f = new File(s);
if (!f.exists()){
System.out.println("'" + s + "' does not exit. Bye!");
return;
}
BufferedReader inputFile = new
BufferedReader(new FileReader(s));
// read lines from the disk file, compute stats
String line;
int nLines = 0;
int nCharacters = 0;
while ((line = inputFile.readLine()) != null){
nLines++;
nCharacters += line.length();
}
// output file statistics
System.out.println("File statistics for '” + s +
“'...");
System.out.println("Number of lines = " + nLines);
System.out.println("Number of characters = " +
nCharacters);
// close disk file
inputFile.close();
} }
Program 49
// writ file on the disk
package ch6;
import java.io.*;
class FileWrite {
public static void main(String[] args) throws
IOException {
// open keyboard for input (call it 'stdin')
BufferedReader stdin =new BufferedReader(new
InputStreamReader(System.in));
// Let's call the output file 'junk.txt'
String s = "junk.txt";
// check if output file exists
File f = new File(s);
if (f.exists())
{
System.out.print("Overwrite " + s + " (y/n)? ");
if(!stdin.readLine().toLowerCase().equals("y"))
return;
}
//open file for output
PrintWriter outFile =
new PrintWriter(new BufferedWriter(new
FileWriter(s)));
// inform the user what to do
System.out.println("Enter some text on the
keyboard...");
System.out.println("(^z to terminate)");
// read from keyboard, write to file output stream
String s2;
while ((s2 = stdin.readLine()) != null)
outFile.println(s2);
// close disk file
outFile.close();
} }
Program 50
package ch6;
//Java program to practice using String Buffer class
and its methods.
import java.lang.String;
class stringbufferdemo {
public static void main(String arg[]) {
StringBuffer sb=new StringBuffer("This is my
college");
System.out.println("This string sb is : " +sb);
System.out.println("The length of the string sb is : "
+sb.length());
System.out.println("The capacity of the string sb is :
" +sb.capacity());
System.out.println("The character at an index of 6 is
: " +sb.charAt(6));
sb.setCharAt(3,'x');
System.out.println("After setting char x at position
3 : " +sb);
System.out.println("After appending : "
+sb.append(" in gulbarga "));
System.out.println("After inserting : "
+sb.insert(19,"gpt "));
System.out.println("After deleting : "
+sb.delete(19,22));
} }
Program 51
package ch6;
// Java Program to illustrate reading from FileReader
// using BufferedReader
import java.io.*;
public class ReadFromFile2
{
public static void main(String[] args)throws
Exception
{
// We need to provide file path as the parameter:
// double backquote is to avoid compiler interpret
words
// like test as t (ie. as a escape sequence)
File file = new File("C:UsersDesktoptest.txt");
//use your own paths
BufferedReader br = new BufferedReader(new
FileReader(file));
String st;
while ((st = br.readLine()) != null)
System.out.println(st);
}
}