Advanced Java Programming 2070

Tribhuwan University
Institute of Science and Technology
2070
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 interface? How can you use the concept of interface to achieve multiple inheritance? Discuss with suitable example.

10 marks view

An interface in Java is a blueprint of a class. It has static constants and abstract methods. An interface is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in java.

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

2. Write a program using swing components to multiply two numbers. Use text fields for inputs and output. Your program should display the result when the user press a button.

10 marks view

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

class Multiplication extends JFrame implements ActionListener     //implement listener interface

{

 JLabel l1, l2;

 JTextField t1, t2, t3;

 JButton b1; 

 public Multiplication() 

{

  l1 = new JLabel("First Number:");

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

  t1 = new JTextField(10);

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

  l2 = new JLabel("Second Number:");

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

  t2 = new JTextField(10);

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

  b1 = new JButton("Product");

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

  t3 = new JTextField(10);

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

  add(l1);

  add(t1);

  add(l2);

  add(t2);

  add(b1);

  add(t3);

  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){

        int num1 = Integer.parseInt(t1.getText()); 

        int num2 = Integer.parseInt(t2.getText()); 

        int product = num1 * num2;

        t3.setText(String.valueOf(product));

   }

 public static void main(String args[])

 {

    new Multiplication();

 }

}

3. What is RMI? How can you use RMI to develop a program that runs in different machine? Discuss with suitable example.

10 marks view

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.

To create an application that uses RMI, one needs to use the classes and interfaces defined by the java.rmi package.
To create an RMI application, the following steps need to be followed:

1. Define a remote interface

2. Implement the remote interface

3. Develop the server application program

4. Develop a client application program

5. Generate Stubs and Skeletons

6. Start the RMI registry on server machine

7. Start the server

8. Start the client

Example:

Define a remote interface

import java.rmi.*;

public interface Adder extends Remote

{

      public int add(int a,int b)throws RemoteException;

}

Implementation of remote interface

import java.rmi.*;

import java.rmi.server.*;

public class AdderRemote extends UnicastRemoteObject implements Adder

{

      AdderRemote()throws RemoteException{

      super();

}

public int add(int a,int b)

{

      return a+b;

}

}


Writing the Server Program

import java.rmi.*;

import java.rmi.registry.*;

public class AddServer {

  public static void main(String args[]) {

      try {

            AdderRemote s1=new AdderRemote();

            LocateRegistry.createRegistry(1099);

            Naming.rebind("AddService",s1);

           }

      catch(Exception e) {

            System.out.println(e);

      }

  }

}


Writing the Client Program

import java.rmi.*;

public class Client {

   public static void main(String args[]) {

      try{

            String ip="rmi://127.0.0.1/Addservice";

            Adder st = (Adder)Naming.lookup(ip);

            System.out.println(st.sum(25,8));

      }

      catch(Exception e) {

            System.out.println(e);

      }

   }

}

                                                              Section B

                                    Attempt any Eight questions. (8x5=40)

4. What is JDBC? How do you execute SQL queries in 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.

The following steps are involved in executing SQL statements in JDBC:

1.      Load the JDBC driver.

2.      Specify the name and location (given as a URL) of the database being used.

3.      Connect to the database with a Connection object.

4.      Execute a SQL query using a Statement object.

5.      Get the results in a ResultSet object.

6.      Finish by closing the ResultSetStatement and Connection objects.


Example:

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class Simplejdbc{

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";

            Connection conn = DriverManager.getConnection(url);

           //Create a statement

            Statement st = conn.createStatement();

           //Execute a statement

            ResultSet rs = st.executeQuery("SELECT * FROM Employee");

            while(rs.next()){

                               int id = rs.getInt("E_ID");

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

                               String address = rs.getString("E_Address");

                               Date d = rs.getDate("DOB");

                               System.out.println(id+"\\t"+name+"\\t"+address+"\\t"+d);

                               }

           st.close();

           conn.close();

    }catch (SQLException sqlExcep){

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

               }

      }

}

5. What is java beans? How is it different from java class?

5 marks view

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

  }

 }

}

7. Discuss different methods used in life cycle of servlet.

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.

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.

8. Discuss border layout with suitable example.

5 marks view

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

}  

}  

9. Why multithreading is important in programming? Discuss.

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

    }

}

10. Discuss any 5 exception classes in java.

5 marks view

Given below is a list of the exceptions classes:

  1. ArithmeticException: It is thrown when an exceptional condition has occurred in an arithmetic operation like divide by zero.
  2. ArrayIndexOutOfBoundsException: It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
  3. ClassNotFoundException: This Exception is raised when we try to access a class whose definition is not found.
  4. FileNotFoundException: This Exception is raised when a file is not accessible or does not open.
  5. IOException: It is thrown when an input-output operation failed or interrupted.

Example of Arithmetic Exception:

class ArithmeticException_Demo
{
    public static void main(String args[])
    {
        try {
            int a = 30, b = 0;
            int c = a/b;  // cannot divide by zero
            System.out.println ("Result = " + c);
        }
        catch(ArithmeticException e) {
            System.out.println ("Can't divide a number by 0");
        }
    }
}

11. Discuss the role of event listeners to handle events with suitable example.

5 marks view

12. What is socket? How can you communicate two programs in a network using TCP Socket?

5 marks view

A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.


Sockets provide the communication mechanism between two programs using TCP. We create client server programs using TCP as follows:


Creating a Socket Client:

The Socket class is used to implement a client program. We use this class to make connection to a server, send data to and read data from that server. The following steps are applied for a communication with the server:

1. The client initiates connection to a server specified by hostname/IP address and port number. (creation of socket object)

2. Send data to the server using an OutputStream.

3. Read data from the server using an InputStream.

4. Close the connection


Creating a Socket Server

The ServerSocket class is used to implement a server program. Here are the typical steps involve in developing a server program:

1. Create a server socket and bind it to a specific port number

 2. Listen for a connection from the client and accept it. This results in a client socket is created for the connection.

 3. Read data from the client via an InputStream obtained from the client socket.

4. Send data to the client via the client socket’s OutputStream.

5. Close the connection with the client.


Example:

Java program using TCP that enables chatting between client and server


//Server.java 

import java.io.*; 

import java.net.*; 

public class Server

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

 { 

  try 

 { 

  System.out.println("SERVER:......\\n"); 

  ServerSocket s = new ServerSocket(95); 

  System.out.println("Server Waiting For The Client"); 

  Socket cs=s.accept(); 

  System.out.println("Client connected”); 

  BufferedReader in=new BufferedReader(new InputStreamReader(cs.getInputStream())); 

  PrintWriter out=new PrintWriter(cs.getOutputStream(),true); 

  while(true)

  { 

    BufferedReader din=new BufferedReader(new InputStreamReader(System.in)); 

    System.out.print("To Client:"); 

    String tocl=din.readLine(); 

    out.println(tocl); 

    String st=in.readLine(); 

    if(st.equalsIgnoreCase("Bye")||st==null)break; 

    System.out.println("From Client:"+st); 

  }

 in.close(); 

 out.close(); 

 cs.close(); 

catch(IOException e) { } 

 } 

}


//Client.java 

import java.io.*; 

import java.net.*; 

public class Client 

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

  { 

   try

  { 

    System.out.println("CLIENT:......\\n"); 

    Socket con=new Socket("localhost", 95); 

    BufferedReader in=new BufferedReader(new InputStreamReader(con.getInputStream())); 

    PrintWriter out=new PrintWriter(con.getOutputStream(),true); 

    while(true) 

   { 

     String s1=in.readLine(); 

     System.out.println("From Server:"+s1); 

     System.out.print("Enter the messages to the server:"); 

     BufferedReader din=new BufferedReader(new InputStreamReader(System.in)); 

     String st=din.readLine(); 

     out.println(st); 

     if(st.equalsIgnoreCase("Bye")||st==null)break; 

   } 

  in.close(); 

  out.close(); 

  con.close(); 

 catch(UnknownHostException e){ } 

}

13. Write a simple JSP program to display “Lalitpur, Nepal” 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 “Lalitpur, Nepal” 10 times</title>

   </head>

   <body>

            <h1> Displaying “Lalitpur, Nepal” 10 times!!</h1>

            <table>

               <%

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

               %>

               <tr><td> Lalitpur, Nepal</td></tr>

               <% } %>

            </table>

   </body>

   </html>