SlideShare une entreprise Scribd logo
1  sur  4
Télécharger pour lire hors ligne
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
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
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
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);
}
}

Contenu connexe

Tendances

Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydney
julien.ponge
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 

Tendances (15)

Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydney
 
Introduzione al TDD
Introduzione al TDDIntroduzione al TDD
Introduzione al TDD
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
JavaExamples
JavaExamplesJavaExamples
JavaExamples
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
 
Smarter Testing With Spock
Smarter Testing With SpockSmarter Testing With Spock
Smarter Testing With Spock
 
Spock framework
Spock frameworkSpock framework
Spock framework
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Algoritmos sujei
Algoritmos sujeiAlgoritmos sujei
Algoritmos sujei
 
Java practical
Java practicalJava practical
Java practical
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка
 
Application-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta LanguageApplication-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta Language
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
 

Similaire à Lab4

Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
Shahjahan Samoon
 
The Java Program for the above given isimport java.io.File;impo.pdf
The Java Program for the above given isimport java.io.File;impo.pdfThe Java Program for the above given isimport java.io.File;impo.pdf
The Java Program for the above given isimport java.io.File;impo.pdf
anjanacottonmills
 
Create a text file named lnfo.txt. Enter the following informatio.pdf
Create a text file named lnfo.txt. Enter the following informatio.pdfCreate a text file named lnfo.txt. Enter the following informatio.pdf
Create a text file named lnfo.txt. Enter the following informatio.pdf
shahidqamar17
 
Write a java program that allows the user to input the name of a file.docx
Write a java program that allows the user to input  the name of a file.docxWrite a java program that allows the user to input  the name of a file.docx
Write a java program that allows the user to input the name of a file.docx
noreendchesterton753
 
import java.io.BufferedReader;import java.io.File;import java.io.pdf
import java.io.BufferedReader;import java.io.File;import java.io.pdfimport java.io.BufferedReader;import java.io.File;import java.io.pdf
import java.io.BufferedReader;import java.io.File;import java.io.pdf
manojmozy
 

Similaire à Lab4 (20)

Inheritance
InheritanceInheritance
Inheritance
 
Bhaloo
BhalooBhaloo
Bhaloo
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
CORE JAVA-1
CORE JAVA-1CORE JAVA-1
CORE JAVA-1
 
Java programs
Java programsJava programs
Java programs
 
54240326 (1)
54240326 (1)54240326 (1)
54240326 (1)
 
54240326 copy
54240326   copy54240326   copy
54240326 copy
 
The Java Program for the above given isimport java.io.File;impo.pdf
The Java Program for the above given isimport java.io.File;impo.pdfThe Java Program for the above given isimport java.io.File;impo.pdf
The Java Program for the above given isimport java.io.File;impo.pdf
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
 
Exceptions and errors in Java
Exceptions and errors in JavaExceptions and errors in Java
Exceptions and errors in Java
 
Create a text file named lnfo.txt. Enter the following informatio.pdf
Create a text file named lnfo.txt. Enter the following informatio.pdfCreate a text file named lnfo.txt. Enter the following informatio.pdf
Create a text file named lnfo.txt. Enter the following informatio.pdf
 
Java 104
Java 104Java 104
Java 104
 
ExtraFileIO.pptx
ExtraFileIO.pptxExtraFileIO.pptx
ExtraFileIO.pptx
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
 
5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе
 
source code which create file and write into it
source code which create file and write into itsource code which create file and write into it
source code which create file and write into it
 
Write a java program that allows the user to input the name of a fil.docx
 Write a java program that allows the user to input  the name of a fil.docx Write a java program that allows the user to input  the name of a fil.docx
Write a java program that allows the user to input the name of a fil.docx
 
Write a java program that allows the user to input the name of a file.docx
Write a java program that allows the user to input  the name of a file.docxWrite a java program that allows the user to input  the name of a file.docx
Write a java program that allows the user to input the name of a file.docx
 
2. Write a program which will open an input file and write to an out.pdf
2. Write a program which will open an input file and write to an out.pdf2. Write a program which will open an input file and write to an out.pdf
2. Write a program which will open an input file and write to an out.pdf
 
import java.io.BufferedReader;import java.io.File;import java.io.pdf
import java.io.BufferedReader;import java.io.File;import java.io.pdfimport java.io.BufferedReader;import java.io.File;import java.io.pdf
import java.io.BufferedReader;import java.io.File;import java.io.pdf
 

Plus de siragezeynu (12)

2 programming with c# i
2 programming with c# i2 programming with c# i
2 programming with c# i
 
6 database
6 database 6 database
6 database
 
Recovered file 1
Recovered file 1Recovered file 1
Recovered file 1
 
Chapter one
Chapter oneChapter one
Chapter one
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
Chapter 3i
Chapter 3iChapter 3i
Chapter 3i
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
Chapter 6
Chapter 6Chapter 6
Chapter 6
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
6 chapter 6 record storage and primary file organization
6 chapter 6  record storage and primary file organization6 chapter 6  record storage and primary file organization
6 chapter 6 record storage and primary file organization
 

Dernier

Dernier (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 

Lab4

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