Skip to document

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 progra...
Course

Computer Engineering (CSE123)

134 Documents
Students shared 134 documents in this course
Academic year: 2017/2018
Uploaded by:
0followers
0Uploads
0upvotes

Comments

Please sign in or register to post comments.

Preview text

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; 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);System.out("Enter two integers for division: "); int number1 = input(); int number2 = input(); int result; try { result = quotient(number1, number2); System.out(number1 + " / " + number2 + " is " + result);}catch(ArithmeticException ex) { System.out(ex());}finally{if(number2==0) { while(number2 == 0) { System.out("Execution continues ..."); System.out("Enter non-zero divisor:");number2 = input(); } result = quotient(number1, number2);System.out(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 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.*; public class ExecuteSQLStamentsInJDBC { public static void main(String[] args) throws SQLException, ClassNotFoundException { Class ("com.mysql.jdbc"); Connection conn = DriverManager(" jdbc:mysql://localhost/library", "root", "vertrigo"),Statement stat = conn();String sql1 = "INSERT INTO BOOK VALUES (5, 'JAVA', 360)";stat(sql1);String sql2 = "UPDATE BOOK SET BOOKNAME='ADVANCED JAVA' WHERE BOOKID=5"; stat(sql2);String sql3 = "DELETE FROM BOOK WHERE BOOKID=3";stat(sql3); String sql4 = "SELECT * FROM BOOK"; ResultSet rs = stat(sql4);ResultSetMetaData rsmd = rs(); int no_of_columns = rsmd(); for (int i = 1; i <= no_of_columns; i++) { System.out(rsmd(i) + "\t\t"); } while (rs()) { System.out(); for (int i = 1; i <=

no_of_columns; i++) { System.out(rs(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; import javax.swing; import javax.swing; 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_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.; public class FileInputStreamTest { public static void main(String args[]) throws IOException { FileInputStream fin = new FileInputStream("welcome"); int i = 0; while ((i = fin()) != -1) { System.out((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.; class FileOutputStreamDemo Java { public static void main(String args[]) { try { FileOutputStream fout = new FileOutputStream("hello"); String s = "Hello World!!!"; byte b[]=s(); fout(b); } catch(IOException e) { System.out(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; import java.io; public class FileReaderDemo { public static void main(String[] args) { try { FileReader fr = new FileReader("test"); int c; while ((c = fr()) != -1) { System.out((char) c); } } catch (IOException ex) { ex(); } } } (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; import java.io; public class FileWriterDemo { public static void main(String args[]) { String src = "Welcome to Java World!!!"; char buffer[] = src(); try { FileWriter f0 = new FileWriter("file0"); FileWriter f1 = new FileWriter("file1"); for (int i = 0; i < buffer; i = i + 2) { f0(buffer[i]); } f1(buffer); f0(); f1(); } catch (IOException e) { System.out(e); } } } This program creates two files named file0 and file1. 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., 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; import java.io; public class TestRandomAccessFile { public static void main(String []args) { try { RandomAccessFile r = new RandomAccessFile("abc", "rw"); r('a'); //2 bytes r(555); //4 bytes r(3); // 8 bytes String s = "Random"; r(s); //6 bytes r(0); System.out(r()); System.out(r()); System.out(r()); r(2); System.out(r()); r(); } catch(IOException e) { System.out(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 import java.; import java.awt.; import javax.; public class KeyListenerTest extends JFrame { JTextField t = new JTextField(10); JTextField t2 = new JTextField(10); public KeyListenerTest() { setLayout(new FlowLayout()); setSize(200, 200); setVisible(true); setDefaultCloseOperation(JFrame_ON_CLOSE); add(t1); add(t2); t2(false); t1(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { String copy = t1(); t2(copy); } }); } public static void main(String[] args) { new KeyListenerTest(); } } Second program KeyAdapterTest import java.; import java.awt.; import javax.; 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_ON_CLOSE); add(t1); add(t2); t2(false); t1(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { String copy = t1(); t2(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; 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("Student total:"+total); } public static void main(String[] args) { float a,e; Result r = new Result(); System.out("Enter marks in academic activities:"); Scanner sc = new Scanner(System); a = sc(); r(a); System.out("Enter marks in extra curricular activities:"); e = sc(); r(e); r(); } }

Discuss border layout with suitable example. A border layout lays out a container, arranging and resizing its components to fit in five regions: north, south, east, west, and center. Each region contains no more than one component, and is identified by a corresponding constant: NORTH, SOUTH, EAST, WEST, and CENTER. When adding a component to a container with a border layout, we have to use one of these five constants. A suitable example utilizing border layout is given below: import java.awt; import javax.; public class BorderLayoutTest extends JFrame { JButton north, south, east, west, center; public BorderLayoutTest() { setLayout(new BorderLayout());north = new JButton("NORTH"); south = new JButton("SOUTH"); east = new JButton("EAST"); west = new JButton("WEST"); center = new JButton("CENTER"); add(north, BorderLayout); add(south, BorderLayout); add(east, BorderLayout); add(west, BorderLayout); add(center, BorderLayout); setSize(300, 300); setVisible(true); setDefaultCloseOperation(JFrame_ON_CLOSE); } public static void main(String []args) { new BorderLayoutTest(); } } Why multithreading is important in programming? Multithreading is the ability to run multiple threads concurrently. Thus multithreaded programs can do many things at once. A thread is a separate unit of execution performing a particular task in a multithreaded program. A thread is implemented by a particular method in programming language such as Java. With multithreading, we can achieve multitasking. If we have multiple CPUs, then each thread of a program can run on different CPUs allowing parallelism. If we have only one CPU, then the threads take turns in their run and this context switching of threads takes less time than multiprocessing systems. In the code example below, we have two threads Thread1 and Thread2. Thread1 prints odd numbers from 1 to 10 after 1 second and Thread2 prints even numbers in the same range after ½ second. class Thread extends Thread { @Override public void run() { try { for (int i = 1; i <= 10; i = i + 2) { Thread(1000); System.out(i); } } catch (InterruptedException e) { e(); } System.out("Exiting Thread1"); } } class Thread2 extends Thread { @Override public void run() { try { for (int i = 2; i <= 10; i = i + 2) { Thread(500); System.out(i); } } catch (InterruptedException e) { e(); } System.out("Exiting Thread2"); } } public class ThreadTest { public static void main(String[] a) { Thread1 t1 = new Thread1(); t1(); Thread2 t2 = new Thread2(); t2(); } } Layout management: A layout manager is an object that implements the LayoutManager interface and determines the size and position of the components within a container. Although components can provide size and alignment hints, a container's layout manager has the final say on the size and position of the components within the container. Flow Layout: The FlowLayout class puts components in a row, sized at their preferred size. If the horizontal space in the container is too small to put all the components in one row, the FlowLayout class uses multiple rows. If the container is wider than necessary for a row of components, the row is, by default, centered horizontally within the container. To specify that the row is to aligned either to the left or right, use a FlowLayout constructor that takes an alignment argument. FlowLayoutexperimentLayout = new FlowLayout(); compsToExperiment(experimentLayout); compsToExperiment(new JButton("Button 1")); compsToExperiment(new JButton("Button 2")); compsToExperiment(new JButton("Button 3")); compsToExperiment(new JButton("Long-Named Button 4")); compsToExperiment(new JButton("5")); A GridLayout object places components in a grid of cells. Each component takes all the available space within its cell, and each cell is exactly the same size. If the GridLayoutDemo window is resized, the GridLayout object changes the cell size so that the cells are as large as possible, given the space available to the container. setLayout(new GridLayout(3, 2)); add(new JButton("Button 1")); add(new JButton("Button 2")); add(new JButton("Button 3")); add(new JButton("Long-Named Button 4")); add(new JButton("5")); pack();The class BorderLayout arranges the components to fit in the five regions: east, west, north, south, and center. Each region can contain only one component and each component in each region is identified by the corresponding constant NORTH, SOUTH, EAST, WEST, and CENTER. classBorderLayoutFrame extends JFrame { publicBorderLayoutFrame() { Container pane = getContentPane(); pane(new BorderLayout()); JButton button = new JButton("Button 1 (PAGE_START)"); pane(button, BorderLayout_START); button = new JButton("Button 2 (CENTER)"); button(new Dimension(200, 100)); pane(button, BorderLayout); button = new JButton("Button 3 (LINE_START)"); pane(button, BorderLayout_START); button = new JButton("Long-Named Button 4 (PAGE_END)"); pane(button, BorderLayout_END); button = new JButton(" (LINE_END)"); pane(button, BorderLayout_END); pack(); setDefaultCloseOperation(EXIT_ON_CLOSE);}}

What is UDP socket? Differentiate it with TCP socket. Sockets are the endpoints of logical connections between two hosts and can be used to send and receive data. Java supports stream sockets and datagram sockets. Stream sockets use TCP (Transmission Control Protocol) for data transport, thus they are also called TCP sockets. Datagram sockets use UDP (User Datagram Protocol) for data transport, thus they are also called UDP sockets. Since TCP can detect lost transports and resubmit them, the transports are lossless and reliable. UDP, in contrast, cannot guarantee lossless transport and so is unreliable. The Java code to perform client-server communication using UDP sockets is given below: TheServer import java.net; import java.net; import java.net; public class TheServer { static int serverPort = 998; static int clientPort = 999; static final int buffer_size = 1024; static DatagramSocket ds; static byte buffer[] = new byte[buffer_size]; public static void Server() throws Exception { int length = 0; while (true) { int c = System.in(); if (c != '\n') { buffer[length++] = (byte) c; } else { ds(new DatagramPacket(buffer, length, InetAddress(), clientPort)); length = 0; } } } public static void main(String[] args) throws Exception { ds = new DatagramSocket(serverPort); Server(); } } TheClient import java.net; import java.net; public class TheClient { static int clientPort = 999; static final int buffer_size = 1024; static DatagramSocket ds; static byte buffer[] = new byte[buffer_size]; public static void Client() throws Exception { while (true) { DatagramPacket p = new DatagramPacket(buffer, buffer); ds(p); System.out(new String(p())); } } public static void main(String[] args) throws Exception { ds = new DatagramSocket(clientPort); Client(); } }

Discuss group layout with suitable example. GroupLayout is a layout manager that hierarchically groups components in order to position them in a Container. GroupLayout works with the horizontal and vertical layouts separately. The layout is defined for each dimension independently. The following program demonstrates using GroupLayout. import javax.*; public class GroupLayoutTest extends JFrame { public GroupLayoutTest() { JPanel panel = new JPanel(); GroupLayout layout = new GroupLayout(panel); JButton one = new JButton("Button 1"); JButton two = new JButton("Button 2"); JButton three = new JButton("Button 3"); JButton four = new JButton("Button 4"); JButton five = new JButton("Button 5"); JButton six = new JButton("Button 6"); layout(layout(GroupLayout.Alignment EADING) .addGroup(layout() .addComponent(one) .addComponent(two) .addComponent(three) .addGroup(layout() .addComponent(four) .addComponent(five)) .addComponent(six)); layout(layout() .addGroup(layout(GroupLayout.Alignment) .addComponent(one).addComponent(two).addComponent(three)) .addGroup(layout(GroupLayout.Alignment) .addComponent(four).addComponent(five)) .addComponent(six)); panel(layout); add(panel); setSize(400, 400); setVisible(true); setDefaultCloseOperation(JFrame_ON_CLOSE); } public static void main(String[] args) { new GroupLayoutTest(); } } What is RMI? Differentiate it with CORBA. Java’s Remote Method Invocation (commonly referred to as RMI) is used for client and server models. RMI is the object oriented equivalent of RPC (Remote procedure call). The Java Remote Method Invocation (RMI) system allows an object running in one Java Virtual Machine (JVM) to invoke methods on an object running in another JVM. RMI provides for remote communication between programs written in the Java programming language i. RMI is a Java-specific technology. However, CORBA (Common Object Request Broker Architecture) has implementations for many languages. We can use CORBA to share objects between programs written in different languages (e. C++ and Java). Further, CORBA uses IDL (Interface Definition Language) to separate interface from implementation whereas RMI just uses Java interfaces. Also, since CORBA is not tied to a particular language, the data types do not always map exactly to the types used by our programming language (e. a long in IDL is an int in Java), however with RMI the data types are exactly mapped. These are the differences between competing distributed systems technologies: RMI and CORBA.

What is a Java bean? How is it different from Java class? A Java bean is a Java class that should follow the following conventions: a. It should have a no argument constructor. b. It should be serializable i. it must implement the java.io interface. Serializability ensures that the object’s state can be written into streams such as files (called serialization) and can be restored later into object as well (called deserialization). c. It should provide methods to set and get the values of the properties, known as getter and setter methods. A Java bean is different from a Java class in the sense that a Java class definition does not have any restriction whereas a Java bean class definition has. Thus a Java bean class is just a Java class with the properties mentioned above. An example of a Java bean class is: package bsccsit; import java.io; public class JavaBeanClassEmployee implements Serializable { private int id; private String name; public int getId() { return id; } public void setId(int id) { this = id; } public String getName() { return name; } public void setName(String name) { this = name; } } Now, to access this Java bean class (from another package), we should use its getter and setter methods as: package seventhsemester; import bsccsit; public class Test { public static void main(String []args) { JavaBeanClassEmployee e = new JavaBeanClassEmployee(); e(1); e("Lok"); System.out(e() + " " + e()); } }

Discuss any five exception classes in Java. All exception classes are subtypes of the java. Exception class. The exception class is a subclass of the Throwable class. Other than the Exception class, there is another subclass called Error which is derived from the Throwable class. The Exception class has two main subclasses: IOException class and RuntimeException class. There are many subclasses of RuntimeException class such as ArithmeticException, NullPointerException, IndexOutOfBoundsException, IllegalArgumentException, ClassCastException, etc. The ArrayIndexOutOfBoundsException class extends IndexOutOfBoundsException class. Some of the exception classes in Java are discussed below: ArithmeticException class: This class deals with exceptional arithmetic conditions such as the divide-by-zero exception. The constructors for this class are: a. public ArithmeticException() b. public ArithmeticException(String s) ArrayIndexOutOfBoundsException class: This class is a subclass of IndexOutOfBoundsException class which is a subclass of RuntimeException class. This class is used to deal with the accessing of an illegal index of an array. The illegal index means either negative value or a value greater than or equal to the size of the array. The constructors for this class are: a. public ArrayIndexOutOfBoundsException() b. public ArrayIndexOutOfBoundsException(int index) c. public ArrayIndexOutOfBoundsException(String s) NullPointerException class: This class is used to deal with the cases where there should be an object instead of null. For example, when we try to find the length of string when the string contains null, then this exception occurs. The constructors for this class are: a. public NullPointerException() b. public NullPointerException(String s) ClassCastException class: This class deals with the code that attempts to cast an object to a subclass of which it is not an instance. For example, when we try an integer object to be casted to a string object, then this exception occurs. The constructors for this class are: a. public ClassCastException() b. public ClassCastException(String s) IllegalArgumentException class: This class deals with methods that are passed an illegal or inappropriate argument. The constructors for this class are: a. public IllegalArgumentException() b. public IllegalArgumentException(String s)

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