You are on page 1of 12

GIFT School of Engineering

and Applied Sciences

Fall 2019

CS-242: Data Structures and Algorithms

Lab-4 Manual
File I/O + Comparator + Exception Handling

v1.0
3/23/2019
Lab-4 Manual 2019

Exceptions in Java
Java defines several types of exceptions that relate to its various class libraries. Java also allows
users to define their own exceptions.

Built-in exceptions are the exceptions which are available in Java libraries. These exceptions are
suitable to explain certain error situations. Below is the list of important built-in exceptions in
Java.

Arithmetic Exception
It is thrown when an exceptional condition has occurred in an arithmetic operation.
class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number
by 0");
}
}
}

NOTE: Copy the ArithmeticException_Demo.java code from the Code folder then compile
and run the code.

Page 1
Lab-4 Manual 2019

ArrayIndexOutOfBoundException
It is thrown to indicate that an array has been accessed with an illegal index. The index is either
negative or greater than or equal to the size of the array.
public class IndexOutOfBoundException_Demo {
public static void main(String args[])
{
try {
int [] array = new int[10];
int c = array[15]; // accesing 15th element.
System.out.println ("Result = " + c);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println ("Index not Found !");
}
}
}

NOTE: Copy the IndexOutOfBoundException_Demo.java code from the Code folder then
compile and run the code.

StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative than the size of
the string
class StringIndexOutOfBound_Demo
{
public static void main(String args[])
{
try {
String a = "This is like chipping ";
// length is 22
char c = a.charAt(24);
// accessing 25th element
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e) {
System.out.println("Index not found in
String");
}
}
}
NOTE: Copy the StringIndexOutOfBound _Demo.java code from the Code folder then
compile and run the code.

Page 2
Lab-4 Manual 2019

ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found
FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
IOException
It is thrown when an input-output operation failed or interrupted
InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some processing , and it is interrupted.
NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
NoSuchMethodException
It is thrown when accessing a method which is not found.
NullPointerException
This exception is raised when referring to the members of a null object. Null represents nothing
NumberFormatException
This exception is raised when a method could not convert a string into a numeric format.
RuntimeException
This represents any exception which occurs during runtime.

Writing your own Exceptions


Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such
cases, user can also create exceptions which are called ‘user-defined Exceptions’.
Following steps are followed for the creation of user-defined Exception.

 The user should create an exception class as a subclass of Exception class. Since all the
exceptions are subclasses of Exception class, the user should also make his class a subclass
of it. This is done as:
class MyException extends Exception
 We can write a default constructor in his own exception class.
MyException(){}
 We can also create a parameterized constructor with a string as a parameter.
We can use this to store exception details. We can call super class(Exception) constructor
from this and send the string there.
MyException(String str)
{
super(str);
}
 To raise exception of user-defined type, we need to create an object to his exception class
and throw it using throw clause, as:
MyException me = new MyException(“Exception details”);
throw me;

Page 3
Lab-4 Manual 2019

 The following program illustrates how to create own exception class MyException.
 Details of account numbers, customer names, and balance amounts are taken in the form of
three arrays.
 In main() method, the details are displayed using a for-loop. At this time, check is done if
in any account the balance amount is less than the minimum balance amount to be kept in
the account.
 If it is so, then MyException is raised and a message is displayed “Balance amount is
less”.

Page 4
Lab-4 Manual 2019

class MyException extends Exception


{
//store account information
private static int accno[] = {1001, 1002, 1003, 1004};
private static String name[] = {"Nish", "Shubh", "Sush",
"Abhi", "Akash"};
private static double bal[] = {10000.00, 12000.00, 5600.0,
999.00, 1100.55};

// default constructor
MyException() { }

// write main()
public static void main(String[] args)
{
try {
// display the heading for the table
System.out.println("ACCNO" + "\t" + "CUSTOMER" +
"\t" + "BALANCE");

// display the actual account information


for (int i = 0; i < 5 ; i++)
{
System.out.println(accno[i] + "\t" + name[i]
+ "\t" + bal[i]);
// display own exception if balance < 1000
if (bal[i] < 1000)
{
MyException me =
new MyException();
throw me;
}
}
} //end of try
catch (MyException e) {
System.out.println("Balance is less than 1000");
}
}
}

Page 5
Lab-4 Manual 2019

NOTE: Copy the MyException.java code from the Code folder then compile and run the
code.

Task #1: Write your own Exception


In this task you are required to do these things

1. Implement the class given below.

2. Create another class MyException which extends Exceptions.


3. Add an default Constructor of MyException.
4. Add main method in MyException Class.
5. Create an array of Student class in main method of MyException with the name of
studentsList of size 3.
6. Add Students of the array.
7. Try to print all the students and throw exception when the Attendance of any student is
below 80.
8. Print the appropriate message when an exception has occurred.

Page 6
Lab-4 Manual 2019

File input/output in Java


 We will write content for reading data from file using the Scanner Object.
 We will write content for writing data to file using the Scanner Object.
You have used Scanner for Standard Input from the user like taking input using the keyboard, so
let’s see how scanner can work for taking input from the File with name input.txt.

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;

public class ScannerInput {


public static void main(String [] args) throws
FileNotFoundException{
System.out.println("Reading contents of file using
Scanner class:");

//FileReader object requires the location of file which


you will be using for input
//You have to give the location of Input file as an
argument to constructor of
//FileReader object.
//Location will be as follows
// "src/yourPackageNameHere/fileName.txt"

FileReader fileReader;
fileReader = new FileReader("src/testproject/input.txt");
Scanner input = new Scanner(fileReader);
while(input.hasNext()){
System.out.println(input.nextInt());
}//while
}//main
}//ScannerInput
NOTE: Copy the ScannerInput.java code from the Code folder. Crate an input.txt in your
package folder and add some data in that file and then compile and run the code.

Page 7
Lab-4 Manual 2019

Basic Methods for the Scanner Object for File Input.

No. Methods Description

1 boolean hasNext() Returns true if this scanner has another token in its input.

2 boolean Returns true if the next token in this scanner's input can be
hasNextDouble() interpreted as a double value using the nextDouble()
method.

3 boolean Returns true if the next token in this scanner's input can be
hasNextFloat() interpreted as a float value using the nextFloat() method.

4 boolean Returns true if the next token in this scanner's input can be
hasNextInt() interpreted as an int value in the default radix using the
nextInt() method.

5 String next() Finds and returns the next complete token from this
scanner..

6 String nextLine() Moves scanner position to the next line & returns the
value as a string.

7 byte nextByte() Scans the next token of the input as a byte.

8 short nextShort() Scans the next token of the input as a short.

9 int nextInt() Scans the next token of the input as a short.

10 long nextLong() Scans the next token of the input as a long.

11 float nextFloat() Scans the next token of the input as a float.

12 double Scans the next token of the input as a double.


nextDouble()

Page 8
Lab-4 Manual 2019

In the previous example you have seen how you can take input from file now we will write some
content in file.

import java.io.FileWriter;
import java.io.IOException;

public class FileOutput{


public static void main(String [] args) throws IOException {

System.out.println("Writing contents to file using


Scanner class:");

//FileWriter object requires the location of file which


you will be using for output
//You have to give the location of Output file as an
argument to constructor of
//FileWriter object.
//Location will be as follows
// "src/yourPackageNameHere/fileName.txt"

FileWriter fileWriter ;
fileWriter = new
FileWriter("src/testproject/output.txt");

fileWriter.write("Hello ");
fileWriter.write("To ");
fileWriter.write("DSA \n");
fileWriter.write("With ");
fileWriter.write("Course Code : CS- ");
fileWriter.write(String.valueOf(201));
fileWriter.close();

}//main
}//ScannerOutput
NOTE: Copy the FileOutput.java code from the Code folder. Crate an output.txt in your
package folder and then compile and run the code.

Page 9
Lab-4 Manual 2019

Task #2: Copy Data from one file to another


In this task you are required to copy data from input.txt file to output.txt file.

1. Create a class with the name CopyData.java with main method.


2. Copy the input.txt & output.txt file from Code folder.
3. Add your implementation in the main method of CopyData.java to read input.txt file and
write data into output.txt file.
4. Give appropriate message while reading and writing.

Comparator Interface in Java


Comparator interface is used to order the objects of user-defined classes. A comparator object is
capable of comparing two objects of two different classes. Following function compare obj1 with
obj2

Syntax:

public int compare(Object obj1, Object obj2)


How does Collections.Sort() work?
Internally the Sort method does call Compare method of the classes it is sorting. To compare
two elements, it asks “Which is greater?” Compare method returns -1, 0 or 1 to say if it is less
than, equal, or greater to the other. It uses this result to then determine if they should be
swapped for its sort.

NOTE: Copy the Student.java, SortByID.java, SortByName.java and SortingStudents.java


files from the Code folder then Compile and Run the SortingStudetns.java file.

Page 10
Lab-4 Manual 2019

Task #3: Comparator Interface to Compare Objects


In this task you are required to do these things

1. Implement the Class Given Below

2. Implement a class SortById which implements the Comparator<Book> with


implementation of Abstract method compare(Obejct o1, Object o2) in the
sense that if the Collection.sort(arrayList, SortById( )) is called , it
will sort the arrayList of Books in Descending order with respect to id.
3. Implement a class SortByPrice which implements the Comparator<Book> with
implementation of Abstract method compare(Object o1,Object o2) in the
sense that if the Collection.sort(arrayList, SortByPrice( ))is called ,
it will sort the arrayList of Book in Ascending order with respect to price.
4. Implement a class SortByNumberOfPages which implements the Comparator<Book>
with implementation of Abstract method compare(Object o1,Object o2) in the
sense that if the Collection.sort(arrayList, SortByNumberOfPages(
))is called , it will sort the arrayList of Book in Ascending order with respect to
numberOfPages.
5. Implement a class SortingBook with the main method.
a. Create an ArrayList of Book with the name arrayList
b. Add at least 3 books in the arrayList
c. Print the arrayList using the enhanced for loop and toString method.
d. Call the Collection.sort() using the SortById class and then print the
arrayList using the enhanced for loop and toString method.
e. Call the Collection.sort() using the SortByPrice class and then print
the arrayList using the enhanced for loop and toString method.
f. Call the Collection.sort() using the SortByNumberOfPages class
and then print the arrayList using the enhanced for loop and toString method.

Page 11

You might also like