Advanced Java Programming 2074

Tribhuwan University
Institute of Science and Technology
2074
Bachelor Level / Seventh Semester / Science
Computer Science and Information Technology ( CSC409 )
( 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.

                                                Group A

                             Attempt any two questions (2x10=20)

1. Define inheritance. Discuss the benefits of using inheritance. Discuss multiple inheritance with suitable example.(1+2+7)

10 marks view

Inheritance is a concept that acquires the properties from one class to other classes. A class can inherit attributes and methods from another class. The class that inherits the properties is known as the sub-class or the child class. The class from which the properties are inherited is known as the superclass or the parent class.

Benefits of Inheritance

  • Inheritance helps in code reuse. The child class may use the code defined in the parent class without re-writing it.
  • Inheritance can save time and effort as the main code need not be written again.
  • Inheritance provides a clear model structure which is easy to understand.
  • An inheritance leads to less development and maintenance costs.
  • With inheritance, we will be able to override the methods of the base class so that the meaningful implementation of the base class method can be designed in the derived class. An inheritance leads to less development and maintenance costs.
  • In inheritance base class can decide to keep some data private so that it cannot be altered by the derived class.

Multiple Inheritance

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 Interfaces. 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. why do we need event handling? Discuss the process of handling events with example. Differentiate event listener interface with adapter class. (3+4+3)

10 marks view

Change in the state of an object is known as event. Events are generated as result of user interaction with the graphical user interface components.  For example, click on button, dragging mouse, entering a character through keyboard, selecting an item from list etc. 

Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism have the code which is known as event handler that is executed when an event occurs. Event handling has three main components,

  • Events : An event is a change of state of an object.
  • Events Source : Event source is an object that generates an event.
  • Listeners : A listener is an object that listens to the event. A listener gets notified when an event occurs.

A source generates an Event and send it to one or more listeners. Listener waits until it receives an event. Once the event is received, the listener process the event and then returns. Listener needs to be registered with the source object so that the listener can receive the event notification. There are three things that are done in event handling:

1. Create a class that represents the event handler.

2. Implement an appropriate interface called “event listener interface” in the above class.

3. Register the event handler

The event listeners listen for a particular event and whenever the event occurs they fire the action that is registered for them.


Example

import java.awt.event.*;

import javax.swing.*;

public class EventListener extends JFrame implements ActionListener {

   public EventListener(){

     JButton btn = new JButton("Click Me");

     add(btn);

     btn.addActionListener(this);         //registering the event handler

     setSize(100, 100);

     setVisible(true);

     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

@Override

public void actionPerformed(ActionEvent e) {

    JOptionPane.showMessageDialog(null, "Hello");

}

public static void main(String []a) {

   new EventListener();

  }

}

Here, whenever the “Click Me” button is clicked, an event is generated and a particular action of opening a dialog box and displaying message “Hello” happens.


Event Listener Interface vs Adapter Class


Many of the listener interfaces have more than one method. When we implement a listener interface in any class then we must have to implement all the methods declared in that interface because all the methods in an interface are final and must be override in class which implement it. 

Adapter class makes it easy to deal with this situation. An adapter class provides empty implementations of all methods defined by that interface. Adapter classes are very useful if we want to override only some of the methods defined by that interface. 

3. Write a program using swing components to find simple interest. Use text fields for inputs and output. Your program should display output if the user clicks a button. (10)

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

 }

}

                                                 Group B

                     Attempt any eight questions. (8x5=40)

4.Write an object oriented program to find area and perimeter of rectangle. (5)

5 marks view
class Rectangle{
    double length;
    double width;
    
    Rectangle(double l, double w){
        length = l;
        width = w;
    }
    
    double area(){
        return length*width;
    }
    
    double perimeter(){
        return 2*(length+width);
    }
}

public class RectangleTest {
    public static void main(String[] args){
        Rectangle r = new Rectangle(10,20);
        double area = r.area();
        double perimeter = r.perimeter();
        System.out.println("Area of rectangle r is: " + area);
        System.out.println("Perimeter of rectangle r is: " + perimeter);
    }
}

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

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.Discuss grid layout with example. 

10 marks view

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

      }

}

7. What is action event? Discuss (5)

5 marks view

The ActionEvent is generated when button is clicked or the item of a list is double-clicked. The listener related to this class is ActionListenerTo have any component listen for an ActionEvent, we must register the component with an ActionListener as: component.addActionListener(new MyActionListener()); and then write the  public void actionPerformed(ActionEvent e); method for the component to react to the event.

Example

import java.awt.event.*;

import javax.swing.*;

public class EventListener extends JFrame implements ActionListener {

   public EventListener(){

     JButton btn = new JButton("Click Me");

     add(btn);

     btn.addActionListener(this);         //registering the event handler

     setSize(100, 100);

     setVisible(true);

     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

@Override

public void actionPerformed(ActionEvent e) {

    JOptionPane.showMessageDialog(null, "Hello");

}

public static void main(String []a) {

   new EventListener();

  }

}

Here, whenever the “Click Me” button is clicked, an event is generated and a particular action of opening a dialog box and displaying message “Hello” happens.

8. How do you execute SQL statement in JDBC? (5)

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

               }

      }

}

9 What is socket? How can you write java programs that communicate with each other using TCP sockets? (1+4)

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

}

10. Write a Java program using servlet to display "Tribhuvan University". (5)

5 marks view
import java.io.*;
import javax.servlet.*;
public class TU extends GenericServlet{
   public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException{
       res.setContentType(“text/html”);
       PrintWriter pw = res.getWriter();
       pw.println("<html>"); 
       pw.println("<head>");
       pw.println(“<title>TU</title>”);
       pw.println("</head>"); 
       pw.println("<body>"); 
       pw.println("<h2>Tribhuvan University</h2>");
       pw.println("</body>"); 
       pw.println("</html>");
       pw.close();
   }
}

11. Discuss property design patterns for Java Beans. (5)

5 marks view

12. What is CORBA? How is it different from RMI? (2+3)

5 marks view

The Common Object Request Broker Architecture (CORBA) is a standard developed by the Object Management Group (OMG) to provide interoperability among distributed objects. The CORBA enables the exchange of information, independent of hardware platforms, programming languages, and operating systems. E.g. A client object written in C++ and running under windows can communicate with an object on a remote machine written in java running under UNIX.



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 notes on: (2.5+2.5)

     a) Multithreading

     b) JSP

5 marks view