Advanced Java Programming 2071

Tribhuwan University
Institute of Science and Technology
2071
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 multithreading? Why is it important to develop in computer programs? Discuss life cycle of thread in detail.

10 marks view

The process of executing multiple threads simultaneously is known as multithreading. The main purpose of multithreading is to provide simultaneous execution of two or more parts of a program to maximum utilize the CPU time. A multithreaded program contains two or more parts that can run concurrently. Each such part of a program called thread.

Multithreading is important due to following reasons:

  • It doesn't block the user because threads are independent and we can perform multiple operations at the same time.
  • We can perform many operations together, so it saves time.
  • Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.

Example:

Program to create two threads. The first thread should print numbers from 1 to 10 at intervals of 0.5 second and the second thread should print numbers from 11 to 20 at the interval of 1 second.

class First extends Thread

{

    @Override

    public void run()

    {

        for (int i=1; i<=10; i++)

        {

            System.out.println(i);

            try

            {

                Thread.sleep(500);

            }

            catch (InterruptedException e)

            {

                System.out.println(e.getMessage());

            }

        }

 

    }

}

class Second extends Thread

{

    @Override

    public void run()

    {

        for (int i=11; i<=20; i++)

        {

            System.out.println(i);

            try{

                Thread.sleep(1000);

            }

            catch (InterruptedException e)

            {

                System.out.println(e.getMessage());

 

            }

        }

    }

}

public class ThreadInterval

{

    public static void main(String[] args)

    {

        Thread first = new First();

        Thread second= new Second();

        first.start();

        second.start();

    }

}


Life Cycle of Thread

thread in Java at any point of time exists in any one of the following states.

  • New:  A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread. In simple words, a thread has been created, but it has not yet been started. A thread is started by calling its start() method.
  • Runnable: The thread is in the runnable state after the invocation of start() method, but the thread scheduler has not selected it to be the running thread. A thread starts life in the Ready-to-run state by calling the start method and wait for its turn. The thread scheduler decides which thread runs and for how long.
  • Running:  When the thread starts executing, then the state is changed to a “running” state. The scheduler selects one thread from the thread pool, and it starts executing in the application.
  • Dead: This is the state when the thread is terminated. The thread is in running state and as soon as it completed processing it is in “dead state”. Once a thread is in this state, the thread cannot even run again.
  • Blocked (Non-runnable state):This is the state when the thread is still alive but is currently not eligible to run. A thread that is blocked waiting for a monitor lock is in this state. A running thread can transit to one of the non-runnable states depending on the situation. A thread remains in a non-runnable state until a special transition occurs. A thread doesn’t go directly to the running state from a non-runnable state but transits first to the Ready-to-run state.

2. Write a program using swing components to find simple interest. Use text fields for inputs and output. Your program should display the result when the user presses a button.

10 marks view

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

class SimpleInterest extends JFrame implements ActionListener    //implement listener interface

{

 JLabel l1, l2, l3;

 JTextField t1, t2, t3, t4;

 JButton b1; 

 public SimpleInterest() 

{

  l1 = new JLabel("Principal:");

  l1.setBounds(20, 10, 100, 20);    //x, y, width, height

  t1 = new JTextField(10);

  t1.setBounds(120, 10, 100, 20);

  l2 = new JLabel("Time:");

  l2.setBounds(20, 40, 100, 20);    

  t2 = new JTextField(10);

  t2.setBounds(120, 40, 100, 20);

  l3 = new JLabel("Rate:");

  l3.setBounds(20, 70, 100, 20);    

  t3 = new JTextField(10);

  t3.setBounds(120, 70, 100, 20);

  b1 = new JButton("Simple Interest");

  b1.setBounds(20, 100, 80, 20);

  t4 = new JTextField(10);

  t4.setBounds(120, 100, 100, 20);

  add(l1);

  add(t1);

  add(l2);

  add(t2);

  add(l1);

  add(t3);

  add(b1);

  add(t4);

  b1.addActionListener(this);    //Registering event

  setSize(400,300);

  setLayout(null);

  setVisible(true);

  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  

}

 @Override

 public void actionPerformed(ActionEvent e)    //Handle Event

 {

    if(e.getSource()==b1){

        double P = Double.parseDouble(t1.getText()); 

        double T = Double.parseDouble(t2.getText());

        double R = Double.parseDouble(t3.getText());

        double SI = (P*T*R)/100;

        t4.setText(String.valueOf(SI));

   }

 public static void main(String args[])

 {

    new SimpleInterest() ;

 }

}

3. What is servlet? Differentiate it with JSP. Discuss life cycle of servlet in detail.

10 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.


Difference between servlet and JSP


Servlets

JSP

Servlet is a pure java code.

JSP is a tag based approach.

We write HTML in servlet code.

We write JSP code in HTML.

Servlet is faster than JSP.

JSP is slower than servlet because it first translate into java code then compile.

Writing code for servlet is harder than JSP as it is html in java.

JSP is easy to code as it is java in html.

Servlet can accept all protocol requests.

JSP only accept http requests.

Modification in Servlet is a time consuming task because it includes reloading, recompiling and restarting the server.

JSP modification is fast, just need to click the refresh button. (reloading, recompilation and restart the server is not required)

Servlets do not have implicit objects.

JSP does have implicit objects.

In Servlet, we can override the service() method.

In JSP, we cannot override its service() method.

In MVC pattern, servlet act as a controller.

In MVC, JSP act as a view.

In Servlet, by default session management is not enabled we need to enable explicitly.

In JSP, session management is automatically enabled.

Packages are to be imported at the top of the servlet.

Packages can be imported anywhere in the JSP code.


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 servlet. This 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.

                                           Section B

                         Attempt any Eight questions. (8x5=40)

4. How do you achieve multiple inheritance in java? Discuss.

5 marks view

In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes. Java does not support multiple inheritances with classes. In java, we can achieve multiple inheritances only through InterfacesAn interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default. A class that implements an interface must implement all the methods declared in the interface.

Multiple inheritance can be achieved with interfaces, because the class can implement multiple interfaces. To implement multiple interfaces, separate them with a comma.

In the following example Class Animal is derived from interface AnimalEat and AnimalTravel.

interface AnimalEat {
   void eat();
}
interface AnimalTravel {
   void travel();
}
class Animal implements AnimalEat, AnimalTravel {
   public void eat() {
      System.out.println("Animal is eating");
   }
   public void travel() {
      System.out.println("Animal is travelling");
   }
}

5. What is JDBC? Discuss different driver types of JDBC.

5 marks view

Java Database Connectivity (JDBC) is an Application Programming Interface (API) used to connect Java application with Database. JDBC is used to interact with various type of Database such as Oracle, MS Access, My SQL and SQL Server. It allows java program to execute SQL statement and retrieve result from database.

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.

6. Explain the importance of exception handling with suitable example.

5 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. 

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.

Example:

class Example
{
   public static void main(String args[])
   {
      try{
         int num1=30, num2=0;
         int output=num1/num2;
         System.out.println ("Result: "+output);
      }
      catch(ArithmeticException e){
         System.out.println ("You Shouldn't divide a number by zero");
      }
   }
}

7. Discuss group layout with suitable example.

5 marks view

GroupLayout groups its components and places them in a Container hierarchically. The grouping is done by instances of the Group class. Group is an abstract class, and two concrete classes which implement this Group class are SequentialGroup and ParallelGroup. SequentialGroup positions its child sequentially one after another whereas ParallelGroup aligns its child on top of each other. The GroupLayout class provides methods such as createParallelGroup() and createSequentialGroup() to create groups.

GroupLayout treats each axis independently. That is, there is a group representing the horizontal axis, and a group representing the vertical axis. Each component must exist in both a horizontal and vertical group, otherwise an IllegalStateException is thrown during layout or when the minimum, preferred, or maximum size is requested.

Example:

import java.awt.*;    

import javax.swing.*;    

public class GroupExample {  

    public static void main(String[] args) {  

        JFrame frame = new JFrame("GroupLayoutExample");  

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  

        Container contentPanel = frame.getContentPane();  

        GroupLayout groupLayout = new GroupLayout(contentPanel);  

        contentPanel.setLayout(groupLayout);  

        JLabel clickMe = new JLabel("Click Here");  

        JButton button = new JButton("This Button");  

        groupLayout.setHorizontalGroup(  

                    groupLayout.createSequentialGroup()  

                                .addComponent(clickMe)  

                                .addGap(10, 20, 100)  

                                .addComponent(button));  

        groupLayout.setVerticalGroup(  

                     groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)  

                                .addComponent(clickMe)  

                                .addComponent(button));  

        frame.pack();  

        frame.setVisible(true);  

    }  

}  

8. Write a simple java program to read from and write to files.

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

  }

 }

}

9. What is TCP socket? Differentiate it with 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. 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.

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. Discuss any five event classes in java.

5 marks view

11. What is java beans? Differentiate it with java classes.

5 marks view

12. What is RMI? Differentiate it with 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 a simple JSP program to display “Tribhuvan University” 10 times.

5 marks view

<!DOCTYPE html>

<html>

   <head>

      <meta http-equiv=“Content-Type” content=“text/htm; charset=UTF-8”>

      <title> JSP program to display “Tribhuvan University” 10 times</title>

   </head>

   <body>

            <h1> Displaying “Tribhuvan University” 10 times!!</h1>

            <table>

               <%

               for(int i=1; i<=10; i++){

               %>

               <tr><td> Tribhuvan University</td></tr>

               <% } %>

            </table>

   </body>

   </html>