- Information
- AI Chat
Was this document helpful?
What are exceptions? Why is it important to handle exceptions? Discuss different keywords that are used to handle exception.
Course: Computer Engineering (CSE123)
134 Documents
Students shared 134 documents in this course
University: Tribhuvan Vishwavidalaya
Was this document helpful?
What are exceptions? Why is it important to handle exceptions? Discuss
different keywords that are used to handle exception.
An exception is a problem that arises during the execution of a program. An
exception can occur for many different reasons, including the following: A user
has entered an invalid data A file that needs to be opened cannot be found A
network connection has been lost in the middle of communications or the JVM has
run out of memory Some of these exceptions are caused by user error, others by
programmer error, and others by physical resources that have failed in some
manner. There are three categories of exceptions in Java: a) Checked exceptions:
A checked exception is an exception that is typically a user error or a problem that
cannot be foreseen by the programmer. For example, if a file is to be opened, but
the file cannot be found, an exception occurs. These exceptions cannot be simply
ignored at the time of compilation. b) Runtime exceptions: A runtime exception is
an exception that occurs where that probably could have been avoided by the
programmer. As opposed to checked exceptions, runtime exceptions are ignored at
the time of compilation. c) Errors: These are not exceptions at all, but problems
that arise beyond the control of the user or the programmer. Errors are typically
ignored in our code because we can rarely do anything about an error. For
example, if JVM is out of memory, an error will arise. They are also ignored at the
time of compilation. It is important to handle exceptions because otherwise the
program would terminate abnormally whenever an exceptional condition occurs.
Exception handling enables a program to deal with exceptional situations and
continue its normal execution. There are five keywords in Java that are used to
handle exceptions. They are a) try b) catch c) finally d) throws e) throw
The code example to show usage of the keywords for exception handling is given
below: import java.util.Scanner; public class ExceptionHandlingTest { public
static int quotient(int number1, int number2) throws ArithmeticException { if
(number2 == 0) {throw new ArithmeticException("Divisor cannot be
zero"); }return number1 / number2;} public static void main(String[] args)
{ Scanner input = new Scanner(System.in);System.out.print("Enter two integers
for division: "); int number1 = input.nextInt(); int number2 = input.nextInt();
int result; try { result = quotient(number1, number2);
System.out.println(number1 + " / " + number2 + " is " +
result);}catch(ArithmeticException ex)
{ System.out.println(ex.getMessage());}finally{if(number2==0)
{ while(number2 == 0) { System.out.println("Execution continues ...");
System.out.println("Enter non-zero divisor:");number2 = input.nextInt();
} result = quotient(number1, number2);System.out.println(number1 + " / " +
number2 + " is " + result); }}}}
What is JDBC? How do you execute SQL statements in JDBC? JDBC is a Java
database connectivity technology from Oracle Corporation. This technology is an
API for the Java programming language that defines how a client may access a
database. It provides methods for querying and updating data in a database. JDBC
is oriented towards relational databases such as MySQL. The JDBC classes are
contained in the java.sql package. To work with database from Java programs, we
need to first load the appropriate driver and then get a connection to the database
via JDBC APIs. The JDBC connection supports creating and executing SQL
statements. These may be update statements such as INSERT, UPDATE and
DELETE, or they may be query statements such as SELECT. When SQL queries
are executed in JDBC, they return a JDBC result set and we manipulate this result
set to present a tabular view to the user. The following code example demonstrates
the mechanism of executing SQL statements in JDBC: import java.sql.*; public
class ExecuteSQLStamentsInJDBC { public static void main(String[] args) throws
SQLException, ClassNotFoundException { Class.forName
("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("
jdbc:mysql://localhost/library", "root", "vertrigo"),Statement stat =
conn.createStatement();String sql1 = "INSERT INTO BOOK VALUES (5, 'JAVA',
360)";stat.executeUpdate(sql1);String sql2 = "UPDATE BOOK SET
BOOKNAME='ADVANCED JAVA' WHERE BOOKID=5";
stat.executeUpdate(sql2);String sql3 = "DELETE FROM BOOK WHERE
BOOKID=3";stat.executeUpdate(sql3); String sql4 = "SELECT * FROM BOOK";
ResultSet rs = stat.executeQuery(sql4);ResultSetMetaData rsmd =
rs.getMetaData(); int no_of_columns = rsmd.getColumnCount(); for (int i =
1; i <= no_of_columns; i++) { System.out.print(rsmd.getColumnName(i) + "\t\t");
} while (rs.next()) { System.out.println(); for (int i = 1; i <=
no_of_columns; i++) { System.out.print(rs.getObject(i) +
"\t\t"); } } } }
The Grid Layout class: is a layout manager that lays out a container's
components in a rectangular grid. The container is divided into equal-sized
rectangles, and one component is placed in each rectangle. Thus we can say that
the components will be arranged in the form of rows and columns like a table with
equal sized cells. The constructors for the GridLayout class are: a) GridLayout() b)
GridLayout(int rows, int cols) c) GridLayout(int rows, int cols, int hgap, int vgap)
A suitable example of using GridLayout class is given below: import
java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JFrame;
public class GridLayoutTest extends JFrame { public GridLayoutTest() {
setLayout(new GridLayout(2,3,10,20)); JButton one = new JButton("1");
JButton two = new JButton("2"); JButton three = new JButton("3");
JButton four = new JButton("4"); JButton five = new JButton("5");
JButton six = new JButton("6"); add(one); add(two); add(three);
add(four); add(five); add(six); setSize(300, 300);
setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
public static void main(String []args) { new GridLayoutTest(); } }
Some classes to handle files in Java are discussed below:
(i) FileInputStream: The FileInputStream class creates an InputStream that we can use to read
bytes from a file. Its two most common constructors are shown here: FileInputStream(String
filepath) throws FileNotFoundException FileInputStream(File fileObj) throws
FileNotFoundException Here, filepath is the full path name of a file, and fileObj is a File object
that describes the file.
Code example: import java.io.*; public class FileInputStreamTest { public static void
main(String args[]) throws IOException { FileInputStream fin = new
FileInputStream("welcome.txt"); int i = 0; while ((i = fin.read()) != -1) {
System.out.print((char)i); } } }
(ii) FileOutputStream: FileOutputStream creates an OutputStream that we can use to write
bytes to a file. Its most commonly used constructors are: public FileOutputStream(String name)
throws FileNotFoundException public FileOutputStream(String name, boolean append) throws
FileNotFoundException public FileOutputStream(File file) throws FileNotFoundException
public FileOutputStream(File file, boolean append) throws FileNotFoundException
Here, filePath is the full path name of a file, and fileObj is a File object that describes the file. If
append is true, the file is opened in append mode.
Code example: import java.io.*; class FileOutputStreamDemo
Java { public static void main(String args[]) { try
{ FileOutputStream fout = new FileOutputStream("hello.txt"); String s =
"Hello World!!!"; byte b[]=s.getBytes(); fout.write(b); }
catch(IOException e) { System.out.println(e); } } }
(iii) FileReader: The FileReader class creates a Reader that you can use to read the contents of a
file. Its two most commonly used constructors are: public FileReader(String fileName) throws
FileNotFoundException public FileReader(File file) throws FileNotFoundException Here,
filePath is the full path name of a file, and fileObj is a File object that describes the file.
Code example: import java.io.FileReader; import java.io.IOException; public class
FileReaderDemo { public static void main(String[] args) { try { FileReader fr = new
FileReader("test.txt"); int c; while ((c = fr.read()) != -1)
{ System.out.print((char) c); } } catch (IOException ex)
{ ex.printStackTrace(); } } } (iv) FileWriter: FileWriter creates a Writer that you
can use to write to a file. Its most commonly used constructors are: public FileWriter(String
fileName) throws IOException public FileWriter(String fileName, boolean append) throws
IOException public FileWriter(File file) throws IOException public FileWriter(File file, boolean
append) throws IOException Here, filePath is the full path name of a file, and fileObj is a File
object that describes the file. If append is true, then output is appended to the end of the file.
Code example: import java.io.FileWriter; import java.io.IOException; public class
FileWriterDemo { public static void main(String args[]) { String src = "Welcome to Java
World!!!"; char buffer[] = src.toCharArray(); try { FileWriter f0 = new
FileWriter("file0.txt"); FileWriter f1 = new FileWriter("file1.txt"); for (int i = 0; i <
buffer.length; i = i + 2) { f0.write(buffer[i]); } f1.write(buffer);
f0.close(); f1.close(); } catch (IOException e) { System.out.println(e); }
} } This program creates two files named file0.txt and file1.txt. The first file contains every
alternate characters of the buffer array and the second file contains the whole buffer. (v)
RandomAccessFile: RandomAccessFile encapsulates a random-access file. It is not derived
from InputStream or OutputStream. Instead, it implements the interfaces DataInput and
DataOutput, which defines the basic I/O methods. It also supports positioning requests i.e., we
can position the file pointer within the file. It has these two constructors:
RandomAccessFile(File fileObj, String access) throws FileNotFoundException Code example:
import java.io.IOException; import java.io.RandomAccessFile; public class
TestRandomAccessFile { public static void main(String []args) { try
{ RandomAccessFile r = new RandomAccessFile("abc.dat", "rw");
r.writeChar('a'); //2 bytes r.writeInt(555); //4 bytes r.writeDouble(3.14); // 8 bytes
String s = "Random"; r.writeBytes(s); //6 bytes r.seek(0);
System.out.println(r.readChar()); System.out.println(r.readInt());
System.out.println(r.readDouble()); r.seek(2); System.out.println(r.readInt());
r.close(); } catch(IOException e) { System.out.println(e); } } }
How can you handle events using adapter classes? Discuss. Adapter classes
such as KeyAdapter, MouseAdapter, MouseMotionAdapter, WindowAdapter, etc
provides the default (generally empty) implementation of all methods for many of
the event listener interfaces such as KeyListener, MouseListener,
MouseMotionListener, WindowListener, etc. Adapter classes are very useful when
you want to process only few of the events that are handled by a particular event
listener interface. For example, the KeyListener interface contains three methods
KeyPressed(), KeyReleased() and KeyTyped(). If we implement this interface, we
have to give implementation of all these three methods. However, by using the
KeyAdapter class, we can override only the method that is needed. This can be
shown in the code example given below. Here we are writing a GUI program that
accepts user input in a text field and displays the key typed in another text field
when the pressed key is released. The first program uses KeyListener interface and
the second program uses KeyAdapter class.
First program //KeyListenerTest.java import java.awt.*; import java.awt.event.*;
import javax.swing.*; public class KeyListenerTest extends JFrame { JTextField t1
= new JTextField(10); JTextField t2 = new JTextField(10); public
KeyListenerTest() { setLayout(new FlowLayout()); setSize(200, 200);
setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(t1); add(t2); t2.setEditable(false); t1.addKeyListener(new KeyListener() {
@Override public void keyTyped(KeyEvent e) { } @Override public void
keyPressed(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) {
String copy = t1.getText(); t2.setText(copy); } }); } public static void main(String[]
args) { new KeyListenerTest(); } } Second program //KeyAdapterTest.java
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class
KeyAdapterTest extends JFrame { JTextField t1 = new JTextField(10);
JTextField t2 = new JTextField(10); public KeyAdapterTest()
{ setLayout(new FlowLayout()); setSize(200, 200); setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add(t1); add(t2);
t2.setEditable(false); t1.addKeyListener(new KeyAdapter() { @Override
public void keyReleased(KeyEvent e) { String copy = t1.getText();
t2.setText(copy); }}); } public static void main(String[] args) { new
KeyAdapterTest(); } }
What is interface? How can you use the concepts of interface to achieve
multiple inheritances? Discuss with suitable example. An interface in the Java
programming is an abstract type that is used to specify a boundary that classes
must implement. It contains only method signatures and static final variable
declarations. It is declared using the keyword “interface”. A class that implements
the interface must define all of the interface’s methods. An example of interface
declaration is: interface MyInterface { static final int var = 5; public void
myMethod(); } Now, we give a suitable example of multiple inheritance in Java
utilizing the second method. Here, we have an interface AcademicActivities and a
class ExtraCurricularActivities. The interface is implemented and the class is
extended by another class named Result to find out the student’s total performance.
import java.util.Scanner; interface AcademicActivities { float
getAcademicMarks(); void setAcademicMarks(float a); } class
ExtraCurricularActivities { float extra_curricular_marks; float
getExtraCurricularMarks(){ return extra_curricular_marks; } void
setExtraCurricularMarks(float e) { extra_curricular_marks = e; } } public
class Result extends ExtraCurricularActivities implements AcademicActivities {
float academic_marks; float total; @Override public float
getAcademicMarks() { return academic_marks; } @Override public void
setAcademicMarks(float a) { academic_marks = a; } void
displayResult() { total = (academic_marks + extra_curricular_marks)/2;
System.out.println("Student total:"+total); } public static void main(String[]
args) { float a,e; Result r = new Result(); System.out.println("Enter
marks in academic activities:"); Scanner sc = new Scanner(System.in); a
= sc.nextFloat(); r.setAcademicMarks(a); System.out.println("Enter
marks in extra curricular activities:"); e = sc.nextFloat();
r.setExtraCurricularMarks(e); r.displayResult(); } }