Tuesday, February 23, 2016

Java Thread - simple program by extending the Thread class


Concept of Thread refer to running many processes(subprograms) concurrently
within a Main program.

As simple illustration.
If COOKING a dish is the Main program.
Within it, Heating Oil and Cutting Vegetables are independent tasks.
There is no need to wait to cut vegetables till Oil is heated.
Theses two tasks can be performed concurrently by assigning them two people.

Same thing can be done in java by assigning the tasks to two threads.

We will use the above example and write a Java program with
COOKING as a the Main program and
HEATING OIL and CUTTING VEGETABLE as two threads running concurrently
within the Main program.

In Java, Thread can be created in two ways.

1. Using the RUNNABLE interface
2. By extending THREAD class.

This programs uses extended THREAD class.
The classes overrides run() method.
run() method contains content of the thread.
Threads end when run() method is completed.


/* HeaingOil thread class*/

class HeatingOil extends Thread{
   int HOcount;
      public void run() {
   
        while(HOcount <= 5){
            try{
                System.out.println("Mts "+(++HOcount) +"- Heating  Oil");
         
                Thread.sleep(1000);
         
            } catch (InterruptedException ie) {
                System.out.println("Exception in thread: "+ie.getMessage());
           }
        }
   
      }
}

/* CuttingVegetable Thread class */

class CuttingVegetable extends Thread{
   int VCcount;
      public void run() {
   
        while(VCcount <= 5){
            try{
                System.out.println("Mts "+(++VCcount) +"- Cutting Veg.");
         
                Thread.sleep(1000);
         
            } catch (InterruptedException ie) {
                System.out.println("Exception in thread: "+ie.getMessage());
           }
        }
   
      }
}

/* Main Program */

public class Cooking {

    public static void main(String[] args) {
         HeatingOil hot=new HeatingOil();   // Object instances of thread classes
         CuttingVegetable cvt = new CuttingVegetable();
     hot.start();                                           // Starting the threads
     cvt.start();
      while (cvt.isAlive() && hot.isAlive()){ //Loops till threads ends
       
                try{
                     Thread.sleep(1000);
   
            } catch (InterruptedException ie){
                System.out.println("Exception in main thread: "+ie.getMessage());
            }
       
    }
 
       System.out.println("CUTTING VEG. IS OVER");
           System.out.println("HEATING OIL IS OVER");
          System.out.println("Main Program COOKING proceeds...");
    }
}

Output -
run:
Mts 1- Heating  Oil
Mts 1- Cutting Veg.
Mts 2- Heating  Oil
Mts 2- Cutting Veg.
Mts 3- Heating  Oil
Mts 3- Cutting Veg.
Mts 4- Heating  Oil
Mts 4- Cutting Veg.
Mts 5- Cutting Veg.
Mts 5- Heating  Oil
Mts 6- Cutting Veg.
Mts 6- Heating  Oil
CUTTING VEG. IS OVER
HEATING OIL IS OVER
Main Program COOKING proceeds...

Click to Thread Creation using RUNNABLE interface

Java Thread - simple program using Runnable Interface



Concept of Thread refer to running many processes(subprograms) concurrently
within a Main program.

If we consider the Main program as a JOB,
the job can be divided into different tasks and
the tasks which are independent can be processed concurrently
using threads within that Main program.

As simple illustration.
If COOKING a dish is the Main program.
Within it, Heating Oil and Cutting Vegetables are independent tasks.
There is no need to wait to cut vegetables till Oil is heated.
Theses two tasks can be performed concurrently by assigning them two people.

Same thing can be done in java by assigning the tasks to two threads.

We will use the above example and write a Java program with
COOKING as a the Main program and
HEATING OIL and CUTTING VEGETABLE as two threads running concurrently
within the Main program.

In Java, Thread can be created in two ways.

1. Using the RUNNABLE interface
2. By extending THREAD class.

This programs uses RUNNABLE interface.
Runnable interface consists of one method run(), which is executed when
the thread is activated by start() method.
run() method contain the program content of the thread.
Thread automatically ends when run() is completed.

Now,
We create two Runnables, one for the task of Heating Oil and another
for Cutting Vegetables.
The content for each thread (runnables) must be coded in the run() method of
respective runnable class.
After creating the Runnable classes.
In the Main program, Objects are created from the classes.
And, threads are constructed using the objects.
Exception for the threads are caught using InterruptedException, which is
extension of Exception class.


/* HeatingOil Runnable */

class HeatingOil implements Runnable{
 public static int HOcount; // counter for iteration
 
    public HeatingOil(){
     
       
    }
    public void run() {
   
        while(HOcount <= 5){
            try{
                System.out.println("Mts "+(++HOcount) +"- Heating  Oil");
         
                Thread.sleep(1000);
         
            } catch (InterruptedException ie) {
                System.out.println("Exception in thread: "+ie.getMessage());
           }
        }
    }
}

/* CuttingVegetable Runnable */

class CuttingVegetable implements Runnable{

    public static int CVcount;
    public CuttingVegetable(){
       
    }
    public void run() {

        while(CuttingVegetable.CVcount <= 5){
            try{
         
                System.out.println("Mts "+ (++CVcount) + "- Cutting Vegetables " );
     
                Thread.sleep(1000); // suspending thread
            } catch (InterruptedException ie) {
                System.out.println("Exception in thread: "+ie.getMessage());
            }
           
        }
    }
}

/* In the Main program. 
Using the above Runnables corresponding objects are created (HeatingOil,CuttingVegetable).
And for each runnable objects, a thread is constructed ( hot, cvt).
Threads have many methods, methods used in this program are
start() - to start the Thread and it also implicitly executes the run() method.
sleep(n) - to suspend thread for said time
isAlive(t)- to check whether the thread is completed the run() method.
A thread end automatically after completing the run() method.

*/
public class Cooking {

 
    public static void main(String[] args) {

        System.out.println("Main Thread...");
        HeatingOil ho = new HeatingOil(); // object creation
        CuttingVegetable cv = new CuttingVegetable();
        Thread hot = new Thread(ho); //thread construction
        Thread cvt = new Thread(cv);
        hot.start(); // Starting the threads and it will execute the run()
        cvt.start(); // implicitely
       
        // loops till both the threads end 
     while (cvt.isAlive() && hot.isAlive()){
       
                try{
                     Thread.sleep(1000);
   
            } catch (InterruptedException ie){
                System.out.println("Exception in main thread: "+ie.getMessage());
            }
         
         
         }
           
          System.out.println("CUTTING VEG. IS OVER");
           System.out.println("HEATING OIL IS OVER");
          System.out.println("Main Program COOKING proceeds...");
     
    }
 
}

Output :

run:
Main Thread...
Mts 1- Heating  Oil
Mts 1- Cutting Vegetables
Mts 2- Heating  Oil
Mts 2- Cutting Vegetables
Mts 3- Heating  Oil
Mts 3- Cutting Vegetables
Mts 4- Cutting Vegetables
Mts 4- Heating  Oil
Mts 5- Heating  Oil
Mts 5- Cutting Vegetables
Mts 6- Heating  Oil
Mts 6- Cutting Vegetables
CUTTING VEG. IS OVER
HEATING OIL IS OVER
Main Program COOKING proceeds...

Click to see Thread creation by extendeding Thread class
                                 

Thursday, February 18, 2016

Java - Date Formatting (USA,UK and ISO 8601 format) and simple Array handling


Dates are classified as Big-endian, Little-endian and Middle-endian.
Big-Endian meaning Most significant to Least significant, ie Year->Month->Day
Little-Endian meaning Least significant to Most significant, ie  Day->Month->Year
Middle-Endian means it is neither of the above, ie it is Month->Day->Year.

We can see
International Standard ISO 8601 notation follows Big-Endian format (YYYY/MM/DD)
British date notation follows Little-Endian format.(DD/MM/YY)
American date notation follows Middle-Endian format.(MM/DD/YY).

Among the above formats (using only numbers).
USA and UK notations can cause confusion, but not ISO 8601 format.
For instance
The date 02/03/16 can indicate two different dates.
UK notation (Little-Endian) means, it is 2nd of March in the year 2016.
USA notation (Middle-Endian) means, it is 3rd of February in the Year 2016.

But using numbers has advantages.
It is language independent, easy to read, enter and manipulate.
International Standard ISO 8601 notation is most suitable for this purpose.
Its noattion being YYYY-MM-DD.
It can't be misread even if we remove the separators(YYYYMMDD).

Having said that,
there are other factors which would decide the final format.

This simple program uses an array to store the above date formats and
displays the system date in each format through a 'for' loop with description.



/* RESOURCES required

import java.util.Date; // For date object with current date and time
import java.text.SimpleDateFormat; // to apply user format

public class GetDateTime {

    public static void main(String[] args) {
     
        /* Arrays to store date formats and their description
       Note: Formats are case sensitive- (Eg)'M' for month, 'm' for minutes */
     
        String[] DateFts   = { "YYYY/MM/dd",
                                           "MM.dd.yy",
                                           "dd/MM/yy"};   
        String[] DateFtsDes = { "ISO 8601 notation (Big",
                             " USA notation (Middle",
                             " UK notation (Little"};
   
        // date object 'dateobj' with current date 

       Date dateobj = new Date();

       //'df' as SimpleDateformat object

       SimpleDateFormat df;
       int i;

       // Displaying date  without formatting

       System.out.println( "Unformatted Current date with time: " + dateobj);
       System.out.println( "Formated date with SimpleDateFormat(): ");
   
       // loop to display date in the formats stored in the Array

         for (i=0;i<DateFts.length;++i){  
       df = new SimpleDateFormat(DateFts[i]); //Initializing 'df' through iteration 
       System.out.println( (i+1) + ") "                 // Array Index starts with 0,so i+1 
                                 +" Format      : "  + "SimpleDateFormat("
                                 + DateFts[i] + ")"           // To display Format text
                                 + "\n" + "    Output      : "
                                 + df.format(dateobj) + "      " //Formating the Date
                                 +"\n" +"    Description :"
                                 + DateFtsDes[i]                   // To display description 
                                 + "-Endian)");
         
       }
    }
}

Output of the Program:

Unformatted Current date with time: Thu Feb 18 16:08:22 IST 2016
Formated date with SimpleDateFormat():
1)  Format      : SimpleDateFormat(YYYY/MM/dd)
    Output      : 2016/02/18    
    Description :ISO 8601 notation (Big-Endian)
2)  Format      : SimpleDateFormat(MM.dd.yy)
    Output      : 02.18.16    
    Description : USA notation (Middle-Endian)
3)  Format      : SimpleDateFormat(dd/MM/yy)
    Output      : 18/02/16    
    Description : UK notation (Little-Endian)
     
 
 

Saturday, February 13, 2016

Java - DBMS - Row/Record locking through a table column


In a multiuser environment same row/record may be accessed/updated concurrently
This could cause data inconsistency and anomaly.
Locking as such is a wide concept and can be implemented in many ways.
It differs according to the DBMS, language and complexity of the project.
by more than one user.

To avoid such situations and maintain data integrity, locking concept is applied.
In this example program,
record locking is done by having a separate column for LOCK status in the table. 
This is done through program logic.
A row is retrieved for UPDATE, only if the LOCK column is marked as FALSE.
If LOCK status is FALSE, the program marks the LOCK status TRUE, writes it to 
the database and allows the user to make changes.
After the user update, it writes the UPDATED row and changes LOCK 
status to FALSE again.
So that it can be accessed by other users.

Software used is  NetBeans IDE 8.0.2. 
Note : ClientId is unique and do not allow duplicates.
Database is created in JavaDB which is part of JDK package.Database ClientDB and table Mailist and records are created through the wizard.Programs also created using Netbeans IDE 8.0.2.Same code holds good for other DBMS with the corresponding driver program.



Database Name : ClientDB
Table Name        :       Maillist
Table Attributes  :         ClientId             N   
                                        ClientName  A/N  
                                        ClientEmail  A/N  
                                        Lock             Boolean
EXAMPLE -

package lockbycolumn;
import java.sql.Connection;
import java.sql.DriverManager; 
import java.sql.Statement; 
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; 
import java.util.Scanner; 

public class LockByColumn {
String host = "jdbc:derby://localhost:1527/clientDB";
String UserName = "parthiban";
String UserPassword = "password";
String sql; 
Connection con;
ResultSet rs;
PreparedStatement ps;
Statement ss;
Scanner AcceptInput = new Scanner(System.in);
int WClientId; // Work Variables
String WClientName, WClientEmail,Wlock; 

  
    public static void main(String[] args) {
        // Cmo is created to enable non static method calling from static Main
       LockByColumn Cmo = new LockByColumn();
        Scanner AcceptInput = new Scanner(System.in);
        String OptionInput;
        Cmo.ConnectMethod();
         do { 
        System.out.println( " ** Select an Operation **");
        System.out.println( " Retrieval of Record - 1");
        System.out.println( " Update of Record    - 2");
        System.out.println( " Exit                - 0");
        System.out.println( " ENTER OPTION - ");
        OptionInput = AcceptInput.next();
    
        switch (OptionInput) {
          
            case "1":
                Cmo.RetrieveRecord();
                break;
            case "2":                
                Cmo.UpdateRecord();
                break;
            case "0":
         // For input 0, program is terminated
                 System.out.println("Ending Session");
                System.exit(0);
                break;
            default:
                System.out.println("Invalid selection - Reenter");
                break; 
         } // end switch
        // Note, how string value is checked for not = "0"
        }  while (!OptionInput.equals("0"));    
    }// end main
    
       /* CONNECTION METHOD */
     public void ConnectMethod(){
         try{
         con = DriverManager.getConnection(host,UserName,UserPassword);                     
            System.out.println(" Connected..");
            }
        catch (SQLException err){
            System.out.println("ERROR:"+err.getMessage());
        }
    }

        /* RECORD RETIEVAL METHOD */

/* this method lists rows with UNDER UPDATE message if that row is under
process by another user */

        public void RetrieveRecord(){
        System.out.println("RECORD RETRIEVAL");
        WClientId =1;
             try {
                        
             sql ="SELECT * from MAILLIST "; 
              ps = con.prepareStatement(sql);
              rs=ps.executeQuery();
              while(rs.next()){
               WClientId = rs.getInt(1);
               WClientName = rs.getString(2);
               WClientEmail = rs.getString(3);
               Wlock="     ";
               /* If LOCK column is TRUE,then Uner Update message is displayed */
               if (rs.getBoolean(4)){
                   Wlock = " -- Under UPDATE --";
               }
            
               System.out.println("Client Id : " + WClientId + ", Name : "
                       + WClientName + ",  EMail : " + WClientEmail 
                        + Wlock);
            
               }
           
        }
        catch (SQLException err){
            System.out.println("ERROR:"+err.getMessage());
        }
    }
      
      /* RECORD UPDATE METHOD */
    
    public void UpdateRecord(){
       System.out.println("RECORD UPDATE");
        WClientId = 1;
       try {
             while (WClientId != 0) {
           System.out.println("Enter Client Id (0 to EXIT): ");
              WClientId = AcceptInput.nextInt();
               AcceptInput.nextLine();// to avoid skipping next input
               
               if (WClientId !=0){
             sql ="SELECT Clientname,clientemail,lock from  MAILLIST where CLIENTID = ? "; 
              ps = con.prepareStatement(sql);
              ps.setInt(1, WClientId);
              rs=ps.executeQuery();
              rs.next(); 
               WClientName = rs.getString(1);
               WClientEmail = rs.getString(2);
               Wlock ="";
               /* if LOCK column is TRUE display RECORD is locked message */
               if (rs.getBoolean(3)){
                    System.out.println( "Record is Locked");
                                             
             }
               /* If RECORD is not locked, update LOCK column as TRUE
                  and proceed with update */ 
               else {
                    sql ="UPDATE MAILLIST set lock = ?  where ClientId = ? ";
            ps = con.prepareStatement(sql);
            ps.setInt(2, WClientId);
            ps.setBoolean(1,true);
            ps.executeUpdate();
            System.out.println("Client Id : " + WClientId + ", Name : "
                       + WClientName + ", Current EMail : " + WClientEmail);
               System.out.println("Enter New Email or press ENTER for no chnage):");
               WClientEmail = AcceptInput.nextLine();// New Email
               sql ="UPDATE MAILLIST SET ClientEmail = ? ,lock = ? where ClientId = ? ";
            ps = con.prepareStatement(sql);
             ps.setString(1,WClientEmail);
             /* Reset LOCK column as FALSE as part of update */
             ps.setBoolean(2,false );
            ps.setInt(3, WClientId);
            ps.executeUpdate();
         
               } 
                   } 
                }
        } 
        catch (SQLException err){
            System.out.println("ERROR:"+err.getMessage());
        } 

    }
}

Saturday, February 6, 2016

Java - DBMS - Row locking through Sql DML statements


In a multiuser environment same row/record may be accessed/updated concurrently
by more than one user.
This could cause data inconsistency and anomaly.

For instance,
If someone is accessing a record to see balance amount and it is under update
by another user. Instead of current balance, old balance would be retrieved,
called as dirty read.
There can be more serious situations which would adversely affect the
integrity of data.

To avoid such situations and maintain data integrity, locking concept is applied.
Locking as such is a wide concept and can be implemented in many ways.
It differs according to the DBMS, language and complexity of the project.

What is shown in this example program is simple method of locking.
It has its limitations but stable one to begin with.
One has to look into that particular DBMS to ascertain effectiveness
and limitations of such locks.

Here,
locking is done through the DML (Select,Update,Delete) statement.
DML statements with FOR UPDATE clause locks the record.

The row/record remain locked till the transaction is completed
(committed /rollback),then the lock is released and the row
is made available for the next transactions and so on.

Software used is  NetBeans IDE 8.0.2. 
Note : ClientId is unique and do not allow duplicates.
Database is created in JavaDB which is part of JDK package.
Database ClientDB and table ClientEmailList are created through the wizard.
Programs also created using Netbeans IDE 8.0.2.
Same code holds good for other DBMS with the corresponding driver program.

Database Name : ClientDB
Table Name        :       ClientContact
Table Attributes  :         ClientId             N   
                                        ClientName  A/N  
                                        ClientEmail  A/N  

No other checks were made.


Now the example.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class CRUDandLOCK {
String host = "jdbc:derby://localhost:1527/ClientDB";
String UserName = "parthiban";
String UserPassword = "password";
String sql;
Connection con;
ResultSet rs;
PreparedStatement ps;
Statement ss;
Scanner AcceptInput = new Scanner(System.in);
int WClientId; // Work Variables
String WClientName, WClientEmail;

    public static void main(String[] args) {
 // Cmo is created to enable non static method calling from static Main
       CRUDandLOCK Cmo = new CRUDandLOCK();
        Scanner AcceptInput = new Scanner(System.in);
        String OptionInput;
        // ConnectMethod is called using Cmo instance
        Cmo.ConnectMethod();
         do {
        System.out.println( " ** Select an Operation **");
        System.out.println( " Creation of Record  - 1");
        System.out.println( " Retrieval of Record - 2");
        System.out.println( " Update of Record    - 3");
        System.out.println( " Deletion of Record  - 4");
        System.out.println( " Exit                - 0");
        System.out.println( " ENTER OPTION - ");
        OptionInput = AcceptInput.next();
        // Based on user input switch control is used to call relevant method
        switch (OptionInput) {
            case "1":
                Cmo.CreateRecord();
                break;
            case "2":
                Cmo.RetrieveRecord();
                break;
            case "3":              
                Cmo.UpdateRecord();
                break;
            case "4":            
               Cmo.DeleteRecord();
                break;
            case "0":
         // For input 0, program is terminated
                 System.out.println("Ending Session");
                System.exit(0);
                break;
            default:
                System.out.println("Invalid selection - Reenter");
                break;
         } // end switch
        // Note, how string value is checked for not = "0"
        }  while (!OptionInput.equals("0"));  
    }// end main
 
        /* CONNECTION METHOD */

     public void ConnectMethod(){
         try{
         con = DriverManager.getConnection(host,UserName,UserPassword);                  
            System.out.println(" Connected..");
            }
        catch (SQLException err){
            System.out.println("ERROR:"+err.getMessage());
        }
    }
 /* RECORD CREATION METHOD */
       public void CreateRecord(){
        System.out.println("RECORD CREATION");
        Scanner Accept = new Scanner(System.in);
        int WclientId  = 1;    
       try {
            /* INSERT sql statement with place holders ?,?,? */
            sql ="INSERT INTO  CLIENTEMAILLIST (ClientId,ClientName,ClientEmail)"
                  + "values(?,?,?)";
             ps = con.prepareStatement(sql);
            /* Following code accepts user input for Client Id, Name and Email */ 
           while (WclientId != 0) {
             System.out.println("Enter Client Code (0-QUIT): ");
             WclientId = Accept.nextInt();
             Accept.nextLine(); // Dummy to avoid skipping NAME input
         
             if (WclientId != 0){
              System.out.println("Enter Client Name : ");
              String WclientName = Accept.nextLine();
              System.out.println("Enter Client EMail : ");
              String WclientEmail = Accept.nextLine();
              // Settler method  to assign actual values 
              ps.setInt(1,WclientId);  
              ps.setString(2,WclientName);
              ps.setString(3,WclientEmail);
           
            ps.executeUpdate();
             System.out.println("Record Created in the database");
             }// if end
             } // while end
               }
            catch (SQLException err){
            System.out.println("ERROR:"+err.getMessage());
        }// try end
   
     }
        /* RECORD RETRIEVAL METHOD */
        public void RetrieveRecord(){
        System.out.println("RECORD RETRIEVAL");
        WClientId =1;
             try {
               
         while (WClientId != 0) {
           System.out.println("Enter Client Id (0 to EXIT): ");
              WClientId = AcceptInput.nextInt();
               AcceptInput.nextLine();// to avoid skipping next input
        con.setAutoCommit(false);
               if (WClientId !=0){
             sql ="SELECT Clientname,clientemail from  CLIENTEMAILLIST where CLIENTID = ? for update";
                 
              ps = con.prepareStatement(sql);
              ps.setInt(1, WClientId);
              rs=ps.executeQuery();
              rs.next();
               WClientName = rs.getString(1);
               WClientEmail = rs.getString(2);
               System.out.println("Client Id : " + WClientId + ", Name : "
                       + WClientName + ", Current EMail : " + WClientEmail);
               con.setAutoCommit(true);
               } //if end
                } // while end
           
        }
        catch (SQLException err){
            System.out.println("ERROR:"+err.getMessage());
        }
    }

      /* RECORD UPDATE METHOD */
 
    public void UpdateRecord(){
       System.out.println("RECORD UPDATE");
        WClientId = 1;
       try {      
             while (WClientId != 0) {
                 con.setAutoCommit(false); // Set auto-commit off
           System.out.println("Enter Client Id (0 to EXIT): ");
              WClientId = AcceptInput.nextInt(); // nextInt() method for integer input
               AcceptInput.nextLine();// to avoid skipping next input
               if (WClientId !=0){
      sql ="SELECT Clientname,clientemail from  CLIENTEMAILLIST where CLIENTID = ? for update of clientemail";
              ps = con.prepareStatement(sql);
              ps.setInt(1, WClientId);
              rs=ps.executeQuery();
              rs.next();
               WClientName = rs.getString(1);
               WClientEmail = rs.getString(2);
               System.out.println("Client Id : " + WClientId + ", Name : "
                       + WClientName + ", Current EMail : " + WClientEmail);
               System.out.println("Enter New Email or press ENTER for no chnage):");
               WClientEmail = AcceptInput.nextLine();// New Email
            sql ="UPDATE CLIENTEMAILLIST SET ClientEmail = ?  where ClientId = ? ";
            ps = con.prepareStatement(sql);
            ps.setInt(2, WClientId);
            ps.setString(1,WClientEmail);
            ps.executeUpdate();
            con.commit();
            con.setAutoCommit(true);// Set auto-commit on
                      } // if end
                } // while end
        }
        catch (SQLException err){
            System.out.println("ERROR:"+err.getMessage());
        }
     
    }
     /* RECORD DELETION METHOD */
 public void DeleteRecord(){
        System.out.println("RECORD DELETION");
        Scanner Accept = new Scanner(System.in);
        WClientId= 1;
     
      try {
          while (WClientId!=0){
       
           con.setAutoCommit(false);  
           System.out.println("Enter Client Id of the record to be Deleted (Numeric): ");
              WClientId = Accept.nextInt();
          /*SQL select statement with placeholder for ClientId to display detail*/
              sql ="SELECT Clientname,clientemail from  CLIENTEMAILLIST where CLIENTID = ? for update of clientemail";
              ps = con.prepareStatement(sql);
              ps.setInt(1, WClientId); // settler method assigns actual value 
              rs=ps.executeQuery(); //  to get result set 
               rs.next();   // move cursor to first record in the result set
               WClientName = rs.getString(1);
               WClientEmail = rs.getString(2);
               System.out.println("Client Id : " + WClientId + ", Name : "
                       + WClientName + ", Old EMail : " + WClientEmail);
                                     System.out.println("Confirm DELETION (y/n)");
            String confirm = Accept.next();
           /* to confirm DELETION */
             if (confirm.equals("y")){
             sql ="DELETE FROM CLIENTEMAILLIST where ClientId = ?";
             ps = con.prepareStatement(sql);
             ps.setInt(1,WClientId);
             ps.executeUpdate();
            System.out.println("Above record is deleted from the database");
             } //if end
         System.out.println(" Record not deleted");
         con.setAutoCommit(true);  
      } // if end
      } //while end
 
        catch (SQLException err){
            System.out.println("ERROR:"+err.getMessage());
        } //try end
 
    } // menu
}// class


One can test the program by running two instances in NetBeans by
NetBeans -> Projects -> Application ->Right Click -> Run