Advanced Java Programming 2072

Tribhuwan University
Institute of Science and Technology
2072
Bachelor Level / Seventh Semester / Science
Computer Science and Information Technology ( CSC-403 )
( Advanced Java Programming )
Full Marks: 60
Pass Marks: 24
Time: 3 hours
Candidates are required to give their answers in their own words as far as practicable.
The figures in the margin indicate full marks.

                                                    Section A

                                  Attempt any Two questions. (2x10=20)

1. What is exception handling? Discuss exception handling in detail with suitable example.

10 marks view

An Exception is an unwanted event that interrupts the normal flow of the program. When an exception occurs program execution gets terminated. In such cases we get a system generated error message. 

Exception handling is a powerful mechanism or technique that allows us to handle runtime errors in a program so that the normal flow of the program can be maintained. Java exception handling is important because it helps maintain the normal, desired flow of the program even when unexpected events occur. If Java exceptions are not handled, programs may crash or requests may fail.  Suppose there are 10 statements in a program and an exception occurs at statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform exception handling, the rest of the statements will be executed. That is why we use exception handling

Java provides five keywords that are used to handle the exception. 

1. try:  The "try" keyword is used to specify a block where an exception can occur. It is always followed by a catch block, which handles the exception that occurs in the associated try block. A try block must be followed by catch blocks or finally block or both.

2. Catch: The "catch" block is used to handle the exception. This block must follow the try block and a single try block can have several catch blocks associated with it. When an exception occurs in a try block, the corresponding catch block that handles that particular exception executes. It can be followed by finally block later.

3. Finally: A finally block contains all the crucial statements that must be executed whether an exception occurs or not. The statements present in this block will always execute, regardless an exception occurs in the try block or not such as closing a connection, stream etc.

4. throw: The "throw" keyword is used to throw an exception.

5. throws: The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn't throw an exception. It is always used with method signature.

Example:

class TestExceptions {
   static void myMethod(int testnum) throws Exception {
      System.out.println ("start - myMethod");
      if (testnum == 12) 
         throw new Exception();
      System.out.println("end - myMethod");
      return;	
   }
   public static void main(String  args[]) {
      int testnum = 12;
      try {
         System.out.println("try - first statement");
         myMethod(testnum);
         System.out.println("try - last statement");
      }
      catch ( Exception ex) {
         System.out.println("An Exception");
      }
      finally {
         System. out. println( "finally") ;
      }
      System.out.println("Out of try/catch/finally - statement");
   }
}
Output:
try - first statement
start - myMethod
An Exception
finally
Out of try/catch/finally - statement

2. What is layout management? Discuss any three layout management classes with example of each.

10 marks view

The layout management is used to arrange components in a particular manner. The Java LayoutManagers facilitates us to control the positioning and size of the components in GUI forms. The layout management classes are given below:

1. Border Layout

The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. Each region (area) may contain one component only.

Components of the BorderLayout Manager

·         BorderLayout.NORTH

·         BorderLayout.SOUTH

·         BorderLayout..EAST

·         BorderLayout.WEST

·         BorderLayout.CENTER

BorderLayout Constructors:

BorderLayout()

creates a border layout but with no gaps between the components.

BorderLayout(int hgap, int vgap)

creates a border layout with the given horizontal and vertical gaps between the components.


Example:

import java.awt.BorderLayout;  

import javax.swing.JButton;

import javax.swing.JFrame;

  

public class BorderLayoutExample {  

BorderLayoutExample(){  

    JFrame f=new JFrame();  

      

    JButton b1=new JButton("NORTH");;  

    JButton b2=new JButton("SOUTH");;  

    JButton b3=new JButton("EAST");;  

    JButton b4=new JButton("WEST");;  

    JButton b5=new JButton("CENTER");;  

      

    f.add(b1,BorderLayout.NORTH);  

    f.add(b2,BorderLayout.SOUTH);  

    f.add(b3,BorderLayout.EAST);  

    f.add(b4,BorderLayout.WEST);  

    f.add(b5,BorderLayout.CENTER);  

      

    f.setSize(300,300);  

    f.setVisible(true);  

}  

public static void main(String[] args) {  

    new BorderLayoutExample();  

}  

}  


2. Flow Layout


The FlowLayout is used to arrange the components in a line, one after another (in a flow).  It arranges components in a line, if no space left remaining components goes to next line. Align property determines alignment of the components as left, right, center etc.

FlowLayout Constructors:

FlowLayout()

 

creates a flow layout with centered alignment and a default 5 unit horizontal and vertical gap.

FlowLayout(int align)

creates a flow layout with the given alignment and a default 5 unit horizontal and vertical gap.

FlowLayout(int align, inthgap, intvgap)

creates a flow layout with the given alignment and the given horizontal and vertical gap.

 

Example:     

import java.awt.FlowLayout;

import javax.swing.JButton;

import javax.swing.JFrame;

public class FlowLayoutExample {

 FlowLayoutExample(){

     JFrame f = new JFrame("Flow Layout");

        JButton b1 = new JButton("button 1");

        JButton b2 = new JButton("button 2");

        JButton b3 = new JButton("button 3");

        JButton b4 = new JButton("button 4");

        JButton b5 = new JButton("button 5");

        f.add(b1);

        f.add(b2);

        f.add(b3);

        f.add(b4);

        f.add(b5);

        f.setLayout(new FlowLayout());

        f.setSize(300,300);  

        f.setVisible(true);  

    }

    public static void main(String[] args) {

        new FlowLayoutExample();

    }

}


3. Grid Layout

The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle. Components are placed in columns and rows.

Every Component in a GridLayout has the same width and height. Components are added to a GridLayout starting at the top-left cell of the grid and proceeding left to right until the row is full. Then the process continues left to right on the next row of the grid, and so on.

GridLayout Constructors:

GridLayout()

creates a grid layout with one column per component in a row.

GridLayout(int rows, int cols)

creates a grid layout with the given rows and columns but no gaps between the components.

GridLayout(int rows, int cols, int int hgap, int vgap)

creates a grid layout with the given rows and columns alongwith given horizontal and vertical gaps.

 

Example:

import java.awt.*;

import javax.swing.*;

public class GridDemo

{

      JButton b1, b2, b3, b4, b5, b6;

      GridDemo()

      {

           JFrame f = new JFrame("GridLayoutDemo");

           b1 = new JButton("A");

           b2 = new JButton("B");

           b3 = new JButton("C");

           b4 = new JButton("D");

           b5 = new JButton("E");

           b6 = new JButton("F");

           f.add(b1);

           f.add(b2);

           f.add(b3);

           f.add(b4);

           f.add(b5);

           f.add(b6);

           f.setLayout(new GridLayout(2, 3));

           f.setSize(200, 200);

           f.setVisible(true);

      }

      public static void main(String args[])

      {

           new GridDemo();

      }

}

3. Write a Java program using JDBC to extract name of those students who live in Kathmandu district, assuming that the student table has four attributes (ID, name, district, and age).

10 marks view

Before Writing the code please run the Xampp server and create a database name test and add a table called student with (id, name, district and age) column name.

Program

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class Studentjdbc{

public static void main( String args[] ) {

try{

          //Load the JDBC driver

            Class.forName("com.mysql.jdbc.Driver");

           // Establish a connection

            String url = "jdbc:mysql//localhost/test";

            String username = "root";

            String password = "";

            Connection conn = DriverManager.getConnection(url, username, password);

           //Create a statement

            Statement st = conn.createStatement();

           //Execute a statement

            ResultSet rs = st.executeQuery("SELECT name FROM student WHERE district = 'Katmandu' ");

            while(rs.next()){

String name = rs.getString("name");

System.out.println("Name: "+ name);

}

            st.close();

            conn.close();

    }catch (SQLException sqlExcep){

System.out.println("Error: " + sqlExcep.getMessage());

}

      }

}

                                               Section B

                           Attempt any Eight questions. (8x5=40)

4. Write an object oriented program in Java to find the area of circle.

5 marks view
class Circle{
    double radius;
    
    Circle(double r){
        radius = r;
    }
    
    double area(){
        return Math.PI*Math.pow(radius, 2);
    }
}
public class CircleTest {
    public static void main(String[] args){
        Circle c = new Circle(5);
        double area = c.area();
        System.out.println("Area of circle c is: "+area);
    }
}

5. Write a simple java program that reads data from one file and writes data to another file.

5 marks view

Let us suppose we have a file named “test.txt” in D-drive. Now we first read from this file character-by-character and later we write the contents of this file to another file say “testwrite.txt” in E-drive. For these tasks, we use the character stream classes namely FileReader and FileWriter. The code is given below:

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;


public class FileReadWrite {

  public static void main(String []args) {

  try

  {

    FileReader fr = new FileReader("D:\\\\test.txt");

    FileWriter fw = new FileWriter("E:\\\\testwrite.txt");

    int c;

    while((c=fr.read())!=-1) {

      fw.write(c);

      System.out.print((char)c);

    }

    fr.close();

    fw.close();

  }

  catch (IOException ex)

  {

    ex.printStackTrace();

  }

 }

}

6. What are the benefits of using swing components? Explain.

5 marks view

Java Swing is a lightweight Graphical User Interface (GUI) toolkit that includes a rich set of widgets. The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu etc.

The benefits of using swing components are

  • Swing provides both additional components and added functionality to AWT-replacement components 
  •  Swing components can change their appearance based on the current "look and feel" library that's being used. 
  •  Swing components follow the Model-View-Controller (MVC) paradigm, and thus can provide a much more flexible UI. 
  • Swing provides "extras" for components, such as:  Icons on many components  Decorative borders for components 
  • Tool tips for components 
  •  Swing components are lightweight (less resource intensive than AWT) 
  •  Swing provides built-in double buffering 
  • Swing provides paint debugging support for when you build your own components 

7. Discuss any three event classes in Java.

5 marks view

8. Discuss different driver types on JDBC.

5 marks view

JDBC Driver is a software component that enables java application to interact with the database. There are 4 types of JDBC drivers:

Type 1: JDBC-ODBC Bridge

  • To use a Type 1 driver in a client machine, an ODBC driver should be installed and configured correctly.
  • This type of driver does not directly interact with the database. To interact with database, it needs ODBC driver.
  •  The JDBC-ODBC bridge driver converts JDBC method class into ODBC method calls.
  •  It can be used to connect to any type of the databases.

Type 2: Native –API driver

  • Type 2 drivers are written partially in Java and partially in native code.
  • The Native-API of each database should be installed in the client system before accessing a particular database. So in this way, a Native-API driver is database specific driver.
  • This driver converts JDBC method calls into native calls of the database API.

Type 3: Net Pure Java Driver

  • In a Type 3 driver, the JDBC driver on the client machine uses the socket to communicate with the middleware at the server. The middleware or server acts as a gateway to access the database.
  • The client database access requests are sent through the network to the middleware or server and then the middleware converts the request to the database specific API.
  •  Type-3 drivers are fully written in Java, hence they are portable drivers.

Type 4: Pure Java Driver

  • This driver interact directly with database. It does not require any native database library and middleware server, that is why it is also known as Thin Driver.
  • No client-side or server-side installation.
  • It is fully written in Java language, hence they are portable drivers.

9. What is socket? Differentiate TCP socket from UDP socket.

5 marks view

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.

Datagram sockets use UDP (User Datagram Protocol) for data transport, thus they are also called UDP socketsStream sockets use TCP (Transmission Control Protocol) for data transport, thus they are also called TCP 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.

TCP

UDP

TCP is a connection oriented protocol.

UDP is a connectionless oriented protocol.

TCP assure reliable delivery of data to the destination.

UDP does not assure reliable delivery of data to the destination.

TCP provides extensive error checking mechanisms such as flow control and acknowledgement of data.

UDP does not provides error checking mechanisms such as flow control and acknowledgement of data.

Delivery of data is guaranteed if you are using TCP.

Delivery of data is not guaranteed if you are using UDP.

TCP is comparatively slow because of these extensive error checking mechanism.

UDP makes fast and best effort service to transmit data.

Retransmission of lost packets is possible.

There is no retransmission of lost packets in UDP.


The Java code to perform client-server communication using UDP sockets is given below:


//UDPClient.java

import java.net.*;

import java.io.*;

public class UDPClient

{

    public static void main (String[] args)

    {

        try

        {

            DatagramSocket socket = new DatagramSocket ();

            byte[] buf = new byte[256];      //Byte array to store information

            String messg = "Hello UDP Server\\n";

            buf = messg.getBytes ();    //Getting the size of message

            InetAddress address = InetAddress.getByName ("127.0.0.1");

            DatagramPacket packet = new DatagramPacket (buf, buf.length, address, 1234);

            socket.send(packet);         // Sends datagram packet, packet

        }

        catch (IOException e)

        {

        }

    }

}


//UDPServer.java

import java.net.*;

import java.io.*;

public class UDPServer

{

    public static void main (String[] args)

    {

        try

        {

            DatagramSocket socket = new DatagramSocket (1234);

            byte[] buf = new byte[256];

            DatagramPacket packet = new DatagramPacket (buf, buf.length);

            socket.receive (packet);

            String received = new String (packet.getData());

            System.out.println ("Received packet: " + received);

        }

        catch (IOException e)

        {

        }     

    }

}

10. What is servlet? Discuss its life cycle.

5 marks view

A servlet is a small java program that executes on the server-side of web connection and dynamically extends the functionality of a web server. Servlet technology is used to create Dynamic web application.


Life Cycle of Servlets

In the life cycle of servlet there are three important methods. These methods are: init(), service() and destroy().



The client enters the URL in the web browser and makes a request. The browser then generates the HTTP request for this URL and sends it to the web server. This HTTP request is received by the web server. The web server maps this request to the corresponding servlet.

init():

-          The server invokes the init( ) method of the servletThis method is invoked only when the servlet is loaded in the memory for the first time. It is possible to pass initialization parameters to the servlet so it may configure itself.

service():

-          The service() method is the main method to perform the actual task.

-          The web server calls the service() method to handle requests coming from the client/browsers and to write the response back to the client (to process the HTTP rerquest). The service() method is called for each HTTP request.

destroy():

-          Finally server unloads the servlet from the memory using the destroy() method to clean any resources.

-          The destroy() method is called only once at the end of the life cycle of a servlet.

11. What is Java Bean? How is it different from other Java classes?

5 marks view

12. What is RMI? How is it different from CORBA?

5 marks view

Remote Method Invocation (RMI) is a mechanism that allows an object running in one java virtual machine (JVM) to invoke methods on an object running in another java virtual machine (JVM). RMI provides remote communication between java programs. Objects with methods that can be invoked across JVMs are called remote objects. The remote object is called the server object.

Difference between RMI and CORBA

RMI

CORBA

RMI is a Java-specific technology. 

CORBA is independent of programming languages. It Can access foreign language objects.

It uses Java interface for implementation.

It uses Interface Definition Language (IDL) to separate interface from implementation.

RMI programs can download new classes from remote JVMs.

CORBA doesn't have this code sharing mechanism.

RMI passes objects by remote reference or by value.

CORBA passes objects by reference.

RMI uses the Java Remote Method Protocol as its underlying remoting protocol.

CORBA use Internet Inter- ORB Protocol (IIOP) as its underlying remoting protocol.

The responsibility of locating an object implementation falls on JVM.

The responsibility of locating an object implementation falls on Object Adapter either Basic Object Adapter or Portable Object Adapter.

Distributed garbage collection is available integrated with local collectors.

No distributed garbage collection is available

Generally simpler to use.

More complicated.

It is free of cost.

Cost money according to the vendor.

 

CORBA has better scalability.

13. Write short note on:

            a. Multithreading

            b. RMI architecture

5 marks view