SlideShare a Scribd company logo
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);
}
}

More Related Content

What's hot

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 Sydneyjulien.ponge
 
Introduzione al TDD
Introduzione al TDDIntroduzione al TDD
Introduzione al TDD
Andrea Francia
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
JavaExamples
JavaExamplesJavaExamples
JavaExamples
Suman Astani
 
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
soft-shake.ch
 
Smarter Testing With Spock
Smarter Testing With SpockSmarter Testing With Spock
Smarter Testing With Spock
IT Weekend
 
Spock framework
Spock frameworkSpock framework
Spock framework
Djair Carvalho
 
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 TestsTomek Kaczanowski
 
Algoritmos sujei
Algoritmos sujeiAlgoritmos sujei
Algoritmos sujei
gersonjack
 
Java practical
Java practicalJava practical
Java practical
william otto
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
Sivadon Chaisiri
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
Erika Susan Villcas
 
4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка
DEVTYPE
 
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
ESUG
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
Rafael Winterhalter
 

What's hot (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
 

Similar to Lab4

Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streamsShahjahan Samoon
 
Java programs
Java programsJava programs
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
 
Exceptions and errors in Java
Exceptions and errors in JavaExceptions and errors in Java
Exceptions and errors in Java
Manuela Grindei
 
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
 
Java 104
Java 104Java 104
Java 104
Manuela Grindei
 
ExtraFileIO.pptx
ExtraFileIO.pptxExtraFileIO.pptx
ExtraFileIO.pptx
NguynThiThanhTho
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
Sunil OS
 
5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе
DEVTYPE
 
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
melakusisay507
 
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
ajoy21
 
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
 
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
rbjain2007
 
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
 

Similar to 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
 

More from siragezeynu

2 programming with c# i
2 programming with c# i2 programming with c# i
2 programming with c# i
siragezeynu
 
6 database
6 database 6 database
6 database
siragezeynu
 
Recovered file 1
Recovered file 1Recovered file 1
Recovered file 1
siragezeynu
 
Chapter one
Chapter oneChapter one
Chapter one
siragezeynu
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
siragezeynu
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
siragezeynu
 
Chapter 3i
Chapter 3iChapter 3i
Chapter 3i
siragezeynu
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
siragezeynu
 
Chapter 6
Chapter 6Chapter 6
Chapter 6
siragezeynu
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
siragezeynu
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
siragezeynu
 
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
siragezeynu
 

More from 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
 

Recently uploaded

Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 

Recently uploaded (20)

Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 

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