Advanced Java Programming 2075

Tribhuwan University
Institute of Science and Technology
2075
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.

Section A

Attempt any two questions. (2x10=20)

1. Design a GUI form using swing with a text field, a text label for displaying the input message “Input any String”, and three buttons with caption CheckPalindrome, Reverse, FindVowels. Write a complete program for above scenario and for checking palindrome in first button, reverse it after clicking second button and extract the vowels from it after clicking third button. (10)

10 marks view

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class Palindrome extends JFrame

{

    public static void main(String[] args)

    {

        Palindrome frame = new Palindrome();

        frame.setVisible(true);

    }

    public Palindrome()

    {

        setLayout(new GridLayout(4,1,10,20));

        JLabel inputLabel = new JLabel("Input any String: ");

        JTextField inputTextField = new JTextField(20);

        add(inputLabel);

        add(inputTextField);

        JLabel outputLabel = new JLabel("Output: ");

        JTextField outputTextField = new JTextField(20);

        add(outputLabel);

        add(outputTextField);

        outputTextField.setEditable(false);

        JButton checkPalindromeButton = new JButton("Check Palindrome");

        add(checkPalindromeButton);

        JButton reverseButton = new JButton("Reverse");

        add(reverseButton);

        JButton findVowelButton = new JButton("Find Vowel");

        add(findVowelButton);

        checkPalindromeButton.addActionListener(new ActionListener()

        {

            @Override

            public void actionPerformed(ActionEvent e)

            {

                String copyUserInput="";

                String userInput = inputTextField.getText();

                int length = userInput.length();

                for (int i = length-1; i>=0; i-- )

                {

                    copyUserInput = copyUserInput + userInput.charAt(i);

                }

                if (copyUserInput.equalsIgnoreCase(userInput))

                {

                    outputTextField.setText("String is palindrome.");

                }

                else

                {

                    outputTextField.setText("String isn't a palindrome.");

                }

            }

        });

        reverseButton.addActionListener(new ActionListener()

        {

            @Override

            public void actionPerformed(ActionEvent e)

            {

                String reverseUserInput="";

                String userInput = inputTextField.getText();

                int length = userInput.length();

                for (int i = length-1; i>=0; i-- )

                {

                    reverseUserInput = reverseUserInput + userInput.charAt(i);

                }

                    outputTextField.setText("Reverse String is: "+ reverseUserInput);

            }

        });


        findVowelButton.addActionListener(new ActionListener()

        {

            @Override

            public void actionPerformed(ActionEvent e)

            {

                char[] vowel={'a','e','i','o','u','A','E','I','O','U'};

                String userInput = inputTextField.getText();

                int length = userInput.length();

                char[] extractedVowel= new char[length];

                String showVowel="";

                for (int i =0; i<=length-1; i++ )

                {

                    for (int j = 0; j<=vowel.length-1; j++)

                    {

                        if(userInput.charAt(i)== vowel[j])

                        {

                            extractedVowel[i] = userInput.charAt(i);

                            showVowel = showVowel + String.valueOf(extractedVowel[i]); //append the extractedVowel to string variable so that it can be displayed at once in a textfield in the form of string.

                        }

                    }

                }

               outputTextField.setText("Vowels: "+showVowel);

            }

        });

        pack();

        setDefaultCloseOperation(EXIT_ON_CLOSE);

    }

}

2. Why do we need to handle the exception? Distinguish error and exception, Write a program to demonstrate your own exception class. [1+2+7]

10 marks view

An exception is an event that occurs during the execution of a program and that disrupts the normal flow of instructions. Java exceptions are specialized events that indicate something bad has happened in the application, and the application either needs to recover or exit.

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

Error vs Exception

ErrorException
An error is caused due to lack of system resources.
An exception is caused because of the code.
An error is irrecoverable.
An exception is recoverable.
There is no means to handle an error by the program code.
Exceptions are handled using three keywords "try", "catch", and "throw".
It belongs to java.lang.error 
It belongs to java.lang.Exception 
As the error is detected the program will terminated abnormally.
As an exception is detected, it is thrown and caught by the "throw" and "catch" keywords correspondingly.
Errors are classified as unchecked type.
Exceptions are classified as checked or unchecked type.
E.g. Java.lang.StackOverFlow,  java.lang.OutOfMemoryErrorE.g.  SQLException, IOException, ArrayIndexOutOfBoundException

In Java, we can create our own exceptions that are derived classes of the Exception class. Creating our own Exception is known as custom exception or user-defined exception. Using the custom exception, we can have your own exception and message. Here, we have passed a string to the constructor of superclass i.e. Exception class that can be obtained using getMessage() method on the object we have created.

Example:

class CustomException extends Exception {
   String message;
   CustomException(String str) {
      message = str;
   }
   public String toString() {
      return ("Custom Exception Occurred : " + message);
   }
}
public class MainException {
   public static void main(String args[]) {
      try {
         throw new CustomException("This is a custom message");
      } catch(CustomException e) {
         System.out.println(e);
      }
   }
}

3. Describe the process to deploy the servlet. Write a program to a JSP web form to take input of a student and submit it to second JSP file which may simply print the values of form submission. [4+6]

10 marks view
A servlet is normally deployed as part of a Web application, usually in the folder WEB-INF\\classes. Like any other java program we need to compile a servlet by using the java compiler javac and after compilation the servlet application , it would be deployed in a configuration environment and can be executed. This development environment setup involves following steps:
1. Download and install tomcat
2. Create a directory structure
3. Create a Servlet
4. Compile the Servlet
5. Create a deployment descriptor
6. Start the server and deploy the project
7. Access the servlet
Now, once you created servlet and the project is ready, There are several ways to deploy the project. They are as follows:
1. By copying the context(project) folder into the webapps directory
2 .By copying the war folder into the webapps directory
3. By selecting the folder path from the server
4. By selecting the war file from the server
Here, we are using the first approach. We need the servlet api to compile the servlet. We need to include JAR file in the CLASSPATH environment variable. Once the compilation succeeds, make a copy of web.xml file in "webapps\\hello\\WEB-INF" and make the following entries in the file.
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>TestServlet</servlet-class>
</servlet>
</servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/TestServlet</url-pattern>
</servlet-mapping>
Restart the Tomcat server to refresh the "web.xml" file and invoke the servlet by issuing the URL: http://localhost:8080/myproject/TestServlet
Thus, above are the process to deploy the servlet.

Second Part:

//StudentForm.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <title>Student Form.</title>

    </head>

    <body>

        <h1>Fill up the form!</h1>

        <form action="PrintDetail.jsp" method="POST">

            Name: <input type="text" name="name"><br><br>

            Roll No.: <input type="text" name="roll"><br><br>

            Address: <input type="text" name="address"><br><br>

            <input type="submit" value="Submit">   

        </form>

    </body>

</html>


// PrintDetail.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <title>Print Student Details.</title>

    </head>

    <body>

        <h1>Student Details!</h1>

        Name: <%= request.getParameter("name") %><br>

        Roll No.: <%= request.getParameter("roll") %><br>

        Address: <%= request.getParameter("address") %><br>

    </body>

</html>

                                          Group B

                     Attempt any eight questions. (8x5=40)

4. An array is called balanced if it's even numbered elements (a[0], a[2], etc.) are even and its odd numbered elements (a[1], a[3],etc.) are Odd. Write a function named is Balanced that accepts an array of integers and returns 1 if the array is balanced otherwise it returns 0. [5]

5 marks view
public static int Balanced(int[] array){
    for(int i=0; i<array.length; i++){
        if(i%2==0){
            if(array[i]%2 != 0){
                return -1;
            }
        }
        else if(i%2 != 0){
            if(array[i]%2 == 0){
                return -1;
            }
        }
    }
    return 1;
}

5. Explain the significance of cookies and sessions with suitable example? [5]

5 marks view

6. Define the chain of constructor. What is the purpose of private constructor? [5]

5 marks view

Chain of constructor is the process of calling one constructor from another constructor with respect to current object. Constructor chaining can be done in two ways: 

  • Within same class: It can be done using this() keyword for constructors in same class
  • From base class: by using super() keyword to call constructor from the base class

What is constructor chaining in Java

The main purpose of using a private constructor is to restrict object creation. We also use private constructors to implement the singleton design pattern. 

Example:

public class A  

{  

//craeting a private constructor   

private A()  

{  

}  

void display()  

{  

System.out.println("Private Constructor");  

}  

}  

private class Test  

{  

public static void main(String args[])  

{  

//compile time error  

A obj = new A();   

}  

}  

7. Describe the process to run the RMI application. [5]

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

      }

   }

}

8. How prepared statements are different with statement? List the types of JDBC driver.[2+3]

5 marks view

 Difference between Statement and Prepared Statement

Statement

PreparedStatement

It is used when SQL query is to be executed only once.

It is used when SQL query is to be executed multiple times.

We cannot pass parameters at runtime.

We can pass parameters at runtime.

Used for CREATE, ALTER, DROP statements.

Used for the queries which are to be executed multiple times.

Performance is very low.

Performance is better than Statement.

Used to execute normal SQL queries.

Used to execute dynamic SQL queries.


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. Write down the life cycle of thread. Write a program to execute multiple threads in priority base. [2+3]

5 marks view

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.

Program to execute multiple threads in priority base


class First extends Thread

{

    @Override

    public void run()

    {

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

        {

            System.out.println(i);

        }

    }

}

class Second extends Thread

{

    @Override

    public void run()

    {

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

        {

            System.out.println(i);

        }

    }

}

class Third extends Thread

{

    @Override

    public void run()

    {

        for (int i = 21; i <= 30; i++)

        {

            System.out.println(i);

        }

    }

}

public class ThreadPriority

{

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

    {

        Thread t1 = new First();

        Thread t2 = new Second();

        Thread t3 = new Third();

        t1.setPriority(Thread.MAX_PRIORITY);

        t2.setPriority(Thread.MIN_PRIORITY);

        t3.setPriority(Thread.NORM_PRIORITY);

        t1.start();

        t2.start();

        t3.start();

    }

}

10. When do we use final method and final class? Differentiate between function overloading and function overriding.[2+3]

5 marks view

11. Give any two differences between class and bean. Write the steps to create JAR files. [2+3]

5 marks view

12. What is a socket? Write client and server programs in which a server program accepts a radius of a circle from the client program. Computes area, sends the computed area to the client program, and displays it by client program.[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.


Program

// Server Program

import java.io.*;

import java.net.*;

class Server

{

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

   {

         ServerSocket ss=new ServerSocket(1064);

         System.out.println("Waiting for Client Request");

         Socket s=ss.accept();

         String str;

         BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));

         str=br.readLine();

         System.out.println("Received radius");

         double r=Double.valueOf(str);

         double area=3.14*r*r;

         PrintStream ps=new PrintStream(s.getOutputStream());

         ps.println(String.valueOf(area));

         br.close();

         ps.close();

         s.close();

         ss.close();

    }

}


//Client Program
import java.io.*;
import java.net.*;
class Client
{
   public static void main(String args[]) throws IOException
    {
       Socket s = new Socket(“localhost”,1064);
       String str;
       System.out.println("Enter Radius  :");
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       str = br.readLine();
       PrintStream ps=new PrintStream(s.getOutputStream());
       ps.println(str);
       BufferedReader fs=new BufferedReader(new InputStreamReader(s.getInputStream()));
       String result = fs.readLine();
       System.out.println("Area of the circle is : "+ result);
       br.close();
       fs.close();
       ps.close();
       s.close();
     }
}

13. Write short notes on:[2.5+2.5]

a. Grid Layout

b. Ragged Array

5 marks view

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

      }

}


b. Ragged Array

Ragged arrays are arrays of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D arrays but with variable number of columns in each row. These type of arrays are also known as Jagged arrays.

Syntax: int array_name = new int[row_size][column size];

Output: