Advanced Java Programming 2073

Tribhuwan University
Institute of Science and Technology
2073
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? How can you write multithreaded programs in java? Discuss with suitable example.

10 marks view

Multithreading is a process of executing two or more threads simultaneously to maximum utilization of CPU A thread is a lightweight sub-process, the smallest unit of processing.

Multithreaded program can be created by using two mechanisms:

1. By extending Thread class

Thread class provide constructors and methods to create and perform operations on a thread. This class overrides the run() method available in the Thread class. A thread begins its life inside run() method. We create an object of our new class and call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.

Example:

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

    }

}


2. By implementing Runnable interface

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run() which  is used to perform action for a thread. The start() method of Thread class is used to start a newly created thread.

Example:

public class ExampleClass implements Runnable {  

    @Override  

    public void run() {  

        System.out.println("Thread has ended");  

    }  

    public static void main(String[] args) {  

        ExampleClass ex = new ExampleClass();  

        Thread t1= new Thread(ex);  

        t1.start();  

        System.out.println("Hi");  

    }  

}  

2. What is Java Beans? How is it different from other Java classes? Discuss property design patterns with suitable example of each.

10 marks view

3. What is socket? How can you write java programs that communicate with each other using TCP sockets? Discuss with suitable example.

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

}

                                             Section B

                           Attempt any Eight questions. (8x5=40)

4. Write an object oriented program to find the area and perimeter of rectangle. 

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 the 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. Discuss border layout with 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();  

}  

}  

7. Why is it important to handle events? List any five event classes. 

5 marks view

8. What is JDBC? How do you execute SQL statements 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());

               }

      }

}

9. Discuss the process of sending email messages using Java.

5 marks view

import java.util.Properties;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

public class SendMail {

    public static void main(String[] args) {

        // Recipient's email ID needs to be mentioned.

        String to = "fromaddress@gmail.com";

        // Sender's email ID needs to be mentioned

        String from = "toaddress@gmail.com";

        // Assuming you are sending email from through gmails smtp

        String host = "smtp.gmail.com";

        // Get system properties

        Properties properties = System.getProperties();

        // Setup mail server

        properties.put("mail.smtp.host", host);

    properties.put("mail.smtp.port", "465");

    properties.put("mail.smtp.ssl.enable", "true");

    properties.put("mail.smtp.auth", "true");

        // Get the Session object.// and pass username and password

        Session session = Session.getInstance(properties, new javax.mail.Authenticator() {

            protected PasswordAuthentication getPasswordAuthentication() {

                return new PasswordAuthentication("fromaddress@gmail.com", "*******");

            }

        });

        // Used to debug SMTP issues

        session.setDebug(true);

        try {

            // Create a default MimeMessage object.

            MimeMessage message = new MimeMessage(session);

            // Set From: header field of the header.

            message.setFrom(new InternetAddress(from));

            // Set To: header field of the header.

            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

            // Set Subject: header field

            message.setSubject("This is the Subject Line!");

            // Now set the actual message

            message.setText("This is actual message");

       System.out.println("sending...");

            // Send message

            Transport.send(message); 

       System.out.println("Sent message successfully....");

        } catch (MessagingException mex) {

            mex.printStackTrace();

        }

    }

}

10. What is JSP? Discuss with suitable example.

5 marks view

Java Server Pages (JSP) is server side technology to create dynamic java web application. It allows java programming code to be embedded in the HTML pages.

  • Scripting elements are used to provide dynamic pages.
  • JSP simply puts Java inside HTML pages.

JSP provides the following scripting elements:

1. JSP Comments:

Syntax:

      <%-- comments --%>

2. JSP Scriplet: A scriptlet tag is used to execute java source code in JSP.

Syntax:

      <% java source code; %> 

3. JSP Expression:

JSP expression can be used to insert a single java expression directly into the response message. This expression will be place inside a out.print() method.

Syntax:

      <%= Java Expression %>

4. JSP Declaration: JSP declaration tag is used to declare variables and methods.

Syntax:

      <%! Variable or method declaration %>

Example


11. What is InetAddress class? Discuss.

5 marks view

The InetAddress class represents an IP address, both IPv4 and IPv6. The java.net.InetAddress class provides methods to get the IP of any host name for example www.google.com, www.facebook.com, etc. We can use the InetAddress class if we need to convert between host names and Internet addresses.

Commonly used methods of InetAddress class:

  • getByName(String host): creates an InetAddress object based on the provided hostname.
  •  getByAddress(byte[] addr): returns an InetAddress object from a byte array of the raw IP address.
  •  getAllByName(String host): returns an array of InetAddress objects from the specified hostname, as a hostname can be associated with several IP addresses.
  • getLocalHost(): returns the address of the localhost.

To get the IP address/hostname you can use a couple of methods below:

  •  getHostAddress(): it returns the IP address in string format.
  • getHostname(): it returns the host name of the IP address.

Example:

import java.io.*;  

import java.net.*;  

public class InetDemo{  

public static void main(String[] args){  

try{  

InetAddress ip=InetAddress.getByName("www.collegenote.net");

System.out.println("Host Name: "+ip.getHostName());  

System.out.println("IP Address: "+ip.getHostAddress());  

}catch(Exception e){

    System.out.println(e);}  

}  

}  

12. What is RMI? Discuss architecture of RMI.

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). It 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.

Architecture of RMI

In an RMI application, we write two programs, a server program (resides on the server) and a client program (resides on the client).

  • Inside the server program, a remote object is created and reference of that object is made available for the client (using the registry).
  • The client program requests the remote objects on the server and tries to invoke its methods.

The RMI architecture consists of four layers:

1. Application Layer: This layer is the actual systems i.e. client and server which are involved in communication. The java program on the client side communicates with the java program on the server-side.

2. Proxy Layer: This layer contains the client stub and server skeleton objects.

  • Stub is an object that resides on the client machine and it acts as a proxy for the remote object. It is like a gateway for the client program. When the client calls on the stub object, the stub forwards this request to a remote object (Skeleton) via RMI infrastructure which is then executed on the server.
  • The server object which resides in a server machine is known as Skeleton. Stub communicates with server application with the help of an intermediate Skeleton object. The responsibility of the skeleton object is to send parameters to method implementation and send the return values back to the client.

3. Remote Reference Layer: This layer is responsible to maintain the session during the method call. i.e. It manages the references made by the client to the remote server object. This layer is also responsible for handling duplicated objects. The invocation semantics of the RMI connection is defined and supported by this layer.

4. Transport Layer: The transport layer is responsible for setting up communication between the two machines. This layer uses standard TCP/IP protocol for connection. The actual transportation of data is performed through this layer.

13. Write short note on: 

      a. Interface

      b. Servlet

5 marks view