Sunday 4 September 2016

How to Create the Custom Exception in Java ?

        In this post, we will learn how to create the custom exception in Java.  To achieve this we can create a Java custom exception class that can  extends Exception class.
        Below code is a sample example of custom or user defined exception class. In this example, if entered age value is less than or equal to 0 or greater than 100 then it will throw the exception with user defined message at the client side.


   public class InvalidAgeException extends Exception { 
              
            public InvalidAgeException(String message) { 
                      super(message);  
            } 
   }

        In the below class, the ageValidate(int age) method will throw the Runtime exception i.e InvalidAgeException when the entered age is less than or equal to 0 or greater than 100. We can provide user understandable message at the client side so user can easily understand the exception.
 
public class CustomExceptionDemo {    

         public int validateAge(int age) { 
                if (age <=0 || age > 100) { 
                      try { 
                           throw new InvalidAgeException("Entered age is not a valid age"); 
                      } catch (InvalidAgeException ex) { 
                         ex.printStackTrace();
                      }        
                } 
                return age; 
        } 

       public static void main (String[] args){ 
               CustomExceptionDemo demo = new ExceptionDemo(); 
               //int age = demo.validateAge(36); 
               int age1 = demo.validateAge(120);  // here it will throw exception.
       } 
}

Output of the above code: -

com.practice.InvalidAgeException: Entered age is not a valid age    at com.practice.CustomExceptionDemo.validateAge(CustomExceptionDemo.java:12)
    at com.practice.
CustomExceptionDemo.main(CustomExceptionDemo.java:23)


      The base Exception class has the following constructors,  we used one constructor in the above example.
 

1) Exception()
 

2) Exception (String message)
 

3) Exception (String message, Throwable cause)
 

4) Exception (Throwable cause)


Related Post: --    
Exception Handling Interview questions and answers  
How to Create Custom Immutable Class with mutable object references in Java?
Factory Design Pattern in Java
Difference between final,finalize and finally in Java

Monday 11 July 2016

Java Object sorting example (Comparable and Comparable)

     In this post, you can learn how to sort Java object specially ArrayList with custom class as generics using Comparable and Comparator interface. In ArrayList sorting with datatype as generics then no need to use comparable and comparator interface, you can use directly Collections.sort(list) methods.

1) Sort an Array
       
         Use Arrays.sort() method to sort an array. See the below example,

               String[] departments = new String[] {"IT", "Engineering", "Support", "Sales"};
               Arrays.sort(departments);
               for (String dept : departments) {
                     System.out.println(dept);
               }

    output : Engineering
                IT
                Sales
                Support


2) Sort an ArrayList without using Comparable or Comparator

         If you want to sort an ArrayList using datatype as Generics then directly you can pass the arraylist parameter in Collections sort method.
    Example,

            List<String> list = Arrays.asList("IT", "Engineering", "Support", "Sales");
            Collections.sort(list);
            //after sorting
            for (String dept : list) {
                  System.out.println("depts : "+ dept);
            }

output : Engineering
            IT
            Sales
            Support



3) Sort an ArrayList of custom objects by Property (Using Comparable interface)

          If you are sorting the custom objects of ArrayList without using Comparable interface, you will get exception, see below code.
     
               public class Employee {
                      private int id;
                      private String name;
                      public int getId () {
                             return id;
                      }
                      public String getName () {
                             return name;
                      }
                      public Employee (int id, String name) {
                              this.id = id;
                              this.name = name;
                      } 

Sorting Employee class objects,

                 Employee[] emp = new Employee[3];
                 emp[0] = new Employee (1, "Mahesh");
                 emp[1] = new Employee (2, "Kiran");
                 emp[2] = new Employee (3, "Rajesh");
                 
                 List<Employee> list = new ArrayList<Employee>();
                 list.add(emp[0]);
                 list.add(emp[1]);
                 list.add(emp[2]);

                 Collections.sort(list);
            
                 for (Employee e : list) {
                          System.out.println(e);
                 }

 when you try to run this code , it throws Run time exception :--
       Exception in thread "main" java.lang.ClassCastException.

      To sort the custom object based on property then you can use any one Comparable or Comparator interface. In the above Employee class, you can implement with Comparable interface and implement compareTo() method. Keep sorting logic in compareTo() method. See the Employee class.

              public class Employee implements Comparable<Employee> {
                      
                      private int id;
                      private String name;

                      public int getId () {
                             return id;
                      }

                      public String getName () {
                             return name;
                      }
    
                      public Employee (int id, String name) {
                              this.id = id;
                              this.name = name;
                      } 

                      @Override
                      public int compareTo (Employee emp) {
                              return this.id - (Integer)emp.getId();
                      }

          The compareTo(Object arg) method returns the negative integer or zero or positive integer, If it returns the negative integer then this object is less than passed argument, returns zero then this object is equal to passed argument, returns positive integer then this object is greater than passed argument.

     Sorting the above Employee class based on id property using ArrayList is as follows,
  
                    Employee[] emp = new Employee[3];
                    emp[0] = new Employee (3, "Mahesh");
                    emp[1] = new Employee (1, "Kiran");
                    emp[2] = new Employee (5, "Rajesh");
                 
                    List<Employee> list = new ArrayList<Employee>();
                    list.add(emp[0]);
                    list.add(emp[1]);
                    list.add(emp[2]);

                    Collections.sort(list);
            
                    for (Employee e : list) {
                          System.out.println(e.getName());
                    }
  
output :- Kiran
             Mahesh
             Rajesh 


4) Sort an ArrayList of custom objects by Property (Using Comparator interface)

               Using Comparable interface, we can sort single property and that should be an integer type. If you can sort the ArrayList based on multiple properties then use Comparator interface. In order to implement the Comparator interface, to implement the compare(Object obj1, Object obj2) methdod of Comparator interface.
               See the below Employee class,

                   public class Employee implements Comparable<Employee> {
                      
                           private int id;
                           private String name;

                           public int getId () {
                                  return id;
                           }

                           public String getName () {
                                  return name;
                           }
    
                           public Employee (int id, String name) {
                                   this.id = id;
                                   this.name = name;
                           } 

                           @Override
                           public int compare(Employee emp1, Employee emp2) {
                                   return emp1.getName().compareTo(emp2.getName());
                           }

 Sorting the above Employee class based on multiple property using ArrayList is as follows,
  
                    Employee[] emp = new Employee[3];
                    emp[0] = new Employee (3, "Mahesh");
                    emp[1] = new Employee (1, "Kiran");
                    emp[2] = new Employee (5, "Rajesh");
                 
                    List<Employee> list = new ArrayList<Employee>();
                    list.add(emp[0]);
                    list.add(emp[1]);
                    list.add(emp[2]);

                    Collections.sort(list, new Emplyee());
            
                    for (Employee e : list) {
                          System.out.println(e.getName());
                    }
         
         
output :- Kiran
             Mahesh
             Rajesh 


Related Post : --
Difference between Comparable & Comparator Interface in Java 

Monday 6 June 2016

JDBC Interview Questions and Answers in Java

A list of jdbc interview questions recently asked in interview are as follows(with answers),

1) What is JDBC ?  
       JDBC itself stands for Java Database Connectivity, and is used to connect and execute sql query to the database using jdbc drivers.


2) What are different types of JDBC Drivers?
      JDBC Drivers can help to interact with java application and the database. There are 4 types of JDBC drivers.
   1) JDBC - ODBC bridge driver
         JDBC - ODBC driver uses ODBC driver to connect to the database. We should install ODBC driver in the client machine so thats'y this driver is not using at all.

   2) Native - API driver(partially java driver)
          This driver converts JDBC calls to the client API for the database servers. We should have database client API installed. This driver also not preferred driver because extra dependency on client API.

    3) Pure Java driver (Network protocol driver)
           This driver sends the JDBC calls to a middle-ware server that can connect to different type of databases. We should have a middle-ware server installed in the client machine. This adds to a extra network calls and slow performance and thatsy this driver also not using widely.

    4) Thin driver or type 4 driver
            This driver converts JDBC calls directly into the vendor specific database protocol . So, it is known as thin driver. It is fully written in Java language.


3) What are the steps in java to make JDBC connectivity ?

         The following are the basic steps to connecting the java application with database using JDBC.
    1)  Register the driver

          The forName() method of  class is used to register the driver class. This method is used to dynamically load the driver class.
         
          Syntax : - 
          public static void forName(String className) throws ClassNotFoundException
   Example of forName() method of MySQL Driver :--
          Class.forName("com.mysql.jdbc.Driver");

     2) Create the Connection object

           The getConnection() method of DriverManager class is used to create the Connection object.
               
           Syntax :-
        1) public static Connection getConnection(String url) throws SQLException
         2) public static Connection getConnection(String url, String name, String password) throws SQLException

   Example of getConnection() method of MySQL driver:--
          Connection con = DriverManager.getConnection("jdbc:mysql://localhost/dbName", "username", "password"); 

      3) Create the Statement object

             The Statement is an interface to execute the query with database. There are three types of statement in Java 1) Statement 2) PreparedStatement 3) CallableStatement

             Example :
            Statement st = con.createStatement();     //Statement 
            PreparedStatement pst = con.prepareStatement(String sqlQuery);  //PreparedStatement
            CallableStatement cst = con.prepareCall(String sqlQuery);    // CallableStatement

       4) Executing the Query

             The execute(), executeQuery() and executeUpdate() method of Statement interface is used to execute the queries to the database.

             Example:--
             ResultSet rs = st.executeQuery();
             int i = st.executeUpdate();
             boolean success = st.execute();  
           
      5) Closing the Connection

            The close() method of the Connection interface is used to close the connection object.

                     con.close();


4 ) What does setAutoCommit(false) do?
      
           A JDBC Connection is created in auto-commit mode by default. This means that each individual SQL statement is treated as a transaction and will be automatically committed as soon as it is executed. If you require two or more statements to be grouped into a transaction then you need to disable auto-commit using below command,

               con.setAutoCommit(false); 
 
         Once auto-commit mode is disabled , no SQL statements will be committed until you explicitly call the commit method.
          Example:--

                   Connection con = null;
                   PreparedStatement insertStmt = null;
                   PreparedStatement updateStmt = null;
                   try {
                         Class.forName("com.mysql.jdbc.Driver");
                         con = DriverManager.getConnection("jdbc:mysql://localhost:3306//dBName","username","password");
                          con.setAutoCommit(false);
                          insertStmt = con.prepareStatement(String insertQuery);
                          insertStmt.executeQuery();
                          updateStmt = con.prepareStatement(String updateQuery);
                          updateStmt.executeUpdate();
                          con.commit();
                   } catch(Exception)  {
                          con.rollback();
                   } finally {
                          if(insertStmt != null) {
                                insertStmt.close();
                           }
                           if (updateStmt != null) {
                                updateStmt.close();
                          }
                            if (con != null) {
                                 con.close();
                            }
                      }


5) How to get the Database server details in Java?

            We can use DatabaseMetaData interface to get the database server details. When database connection is created then you call meta data object by calling getMetaData() method. There are so many methods available in DatabaseMetaData to get the product name, major version, minor version and product version etc.

                     DatabaseMetaData dbmd = con.getMetaData();
                     System.out.println("Database Product Name "+dbmd.getDatabaseProductName);
                     System.out.println("Database Product Version"+dbmd.getDatabaseProductVersion);
                     System.out.println("Database Major Version "+dbmd.getDatabaseMajorVersion);
                     System.out.println("Database Minor Version "+dbmd.getDatabaseMinorVersion);
                   
                           // Driver information
                     System.out.println("Driver Name "+dbmd.getDriverName); 
                     System.out.println("Driver Version "+dbmd.getDriverVersion); 
                     System.out.println("Driver Major Version "+dbmd.getDriverMajorVersion);
                     System.out.println("Driver Minor Version "+dbmd.getDriverMinorVersion);


6) Difference between Statement and PrepareStatement in Java?

      Statement : - This statement is used for executing a static SQL statements and it can not accept parameters at run time.  Statement is slower as compared to preparedStatement. Statement enforces SQL injection . This statement can't be used for storing/retrieving images and files in database

      PreparedStatement:-  This PreparedStatement is used for executing precompiled SQL statement and it can accept parameters at run time. Execution process is fast compared to Statement. PreapredStatement prevents the SQL injection. This statement can be used for storing/retrieving images and files in database.


7) Why PreparedStatement is faster than Statement ?

            If you have to run the same Statement with multiple times, with different data then you can use PreparedStatement because it can validate query only once and run multiple times.  i.e In PreparedStatement pre compilation is done only once so it can take less execution time. But in simple Statement every time it can validate and runs the query so it is slow compared to PreparedStatement.   

8) How can we execute stored procedures and functions?
           We can execute stored procedures and functions by using Callable statement interface. This statement can extends Prepared Statement interface.
            For example,
             
            CallableStatement callStmt = con.prepareCall("{call calculateTotalAmount(?,?)}") ;

  In the above query, calculateTotalAmount is the stored procedure or function.
 

9) How the ResultSet Object works in JDBC ?
           Refer this Working with JDBC ResultSet object


10) What are different types of ResultSet ?

            ResultSet contains the result of the SQL query. There are different types of ResultSet object that we can get based on the user input while creating the Statement. In createStatement() and preparedStatement() methods of Statement and PreparedStatement, we are passing Resultset type and concurrency as an argument.
          There are three types of ResultSet types are as follows,

        1) ResultSet.TYPE_FORWARD_ONLY
                 This is the default type and cursor can only move forward direction

        2) ResultSet.TYPE_SCROLL_INSENSITIVE
                 The cursor can move both forward and backward direction and resulset is not sensitive to changes made by others to the database after the resultset was created. 
     
        3) ResultSet.TYPE_SCROLL_SENSITIVE
                  The cursor can move both forward and backward direction and resultset is sensitive to changes made by others to the database after the resultset was created.

       Based on the concurrency,

       1) ResultSet.CONCUR_READ_ONLY
                The resultset is read only and this is the default concurrency type.

      2) ResultSet.CONCUR_UPDATABLE 
                This resultset method is used to update the rows data.

Syntax of connection methods to create statements with desired Resultset types,

           Statement st = con.createStatement(int RSType, int RSConcurrency);
           PreparedStatement pst = con.prepareStatement(String Sql, int RSType, int RSConcurrency);
           CallableStatement cst = con.prepareCall(String sql, int RSType, int RSConcurrency);


                 
11) What is ResultSetMetaData in Java?
          
         The ResultSetMetaData is an interface and it can used to get information about the name of columns, number of columns and data types of the columns in ResultSet object.
     
        Example : --
                     Connection con = null;
                     PreparedStatement pst = null;
                     ResultSet rs = null;
                     try {
                           Class.forName("com.mysql.jdbc.Driver");
                           con =DriverManager.getConnection("mysql:jdbc//localhost:3306
                                    //dbName,","username","password");
                           pst = con.prepareStatement("SELECT * FROM employee");
                           rs = pst.executeQuery();
                           while (rs.next()) {
                                  ResultSetMetaData rsmd = rs.getMetaData();
                                  System.out.println(rsmd.getColumnCount()); //column count
                                  System.out.println(rsmd.getColumnName());//column name
                                  System.out.println(rsmd.getColumnTypeName());
                           }
                     } catch (Exception e) {
                           e.printStackTrace();
                     } finally {
                            if (rs != null) {
                                  rs.close();
                            }
                            if (pst != null) {
                                  pst.close();
                            }
                            if (con != null) {
                                  con.close();
                            }
                     }
output : - 3
               emp_useraname
               VARCHAR


12)  How do you handle transaction in JDBC using connection interface ?

        By default auto-commit is turned ON which commits to database for every SQL statement is sent/issued to database.
        Turned OFF auto-commit, commit to the database at the end using manually commit() method.

           connection.setAutoCommit(false);
             // do some operations like insert, update, delete so on
             // in finally block do commit
          connection.commit();

If any error in between transaction, then rollback the connection using rollback() method.
   
         connection.rollback();
  


13) Difference between java.sql.Time, java.sql.Timestamp and java.sql.Date. 
        
          java.sql.Time represents only time information e.g hours,minutes and seconds without any date information. java.sql.Date represents only date information like day, month and year, no time information. java.sql.Timestamp represents both time and Date including nanoseconds also.
          java.sql.Time and java.sql.Timestamp extends java.util.Date but java.sql.Date is independent.
          

14) What is the design pattern followed by JDBC ?

           JDBC follows a bridge design patten.


15) How to insert images into database using BLOB datatype? Write a sample code.  

          BLOB is a datatype, stands for Binary Large Object. and it can be used for storing large amount of data into the database like images, voice and graphical data.
         CLOB is also a datatype and stands for Character Large Object and it can be used for storing single byte character data like text files, pdf, doc and docx.

         Below code is a sample example of insert a image into database using BLOB datatype(using mysql database).
         Table Structure:--
           CREATE TABLE candidate_photo
                  (reg_id INT, user_photo BLOB);


            Connection con = null;
            PreparedStatement pst = null;
            InputStream is = null;
            try {
                   Class.forName("com.mysql.jdbc.Driver");
                   con = DriverMabnager.getConnection("jdbc:mysql://localhost:3306//dbName", "username", "password");
                   pst = con.prepareStatement("insert into candidate_photo values(?,?)");
                   pst.setInt(1, 1);
                   is = new FileInputStream(new File("D://Documents//Image.jpg"));
                   int fileLength = (int) new File("D://Documents//Image.jpg").length();
                   pst.setBinaryStream(2, is, fileLength);
                   pst.execute();
            } 
            catch(Exception e ) {
                   e.printStackTrace();
            } 
            finally {
                   if (pst != null ) {
                        pst.close();
                   }
                   if (is != null) {
                        is.close();
                   }
                   if (con != null) {
                         con.close();
                   }
            }

16) How to read the image from the database? write a sample code.

            Connection con = null;
            PreparedStatement pst = null;
            ResultSet rs = null;
            InputStream is = null;
            FileOutputStream os = null;
            try {
                   Class.forName("com.mysql.jdbc.Driver");
                   con = DriverMabnager.getConnection("jdbc:mysql://localhost:3306//dbName", "username", "password");
                   pst = con.prepareStatement("select user_photo from candidate_photo where reg_id=1");
                   rs = pst.executeQuery();
                   if (rs.next()) {
                         is = rs.getBinaryStream(1);
                    }
                    FileOutputStream os = new FileOutputStream("D://Documents//Image1.jpg");
                    byte[] content = new byte[1024];
                    int size = 0;
                    while((size = is.read(content)) != -1){
                                os.write(content, 0, size);
                     } 
            } 
            catch(Exception e ) {
                   e.printStackTrace();
            } 
            finally {
                   if (pst != null ) {
                        pst.close();
                   }
                   if (is != null) {
                        is.close();
                   }
                   if (os != null) {
                        is.close();
                   }
                   if (con != null) {
                         con.close();
                   }
            }
 

Sunday 6 March 2016

Static Keyword and Its usage in Java

                   In this post, we will discuss the use use of static keyword in Java. The static keyword is mainly used for memory management. This keyword is used to create static method, static class, static block and static variable. The static keyword belongs to the class than instance of the class.

1) Static variable :--

         
          Static variable value is same for all object or instances of the class, in other words we can say that all objects of the same class share a single copy of static variables. Static variable gets memory only once in class area at the time of class loading.

Example:-- Without using static,
 
       public class StaticVar {

             int a = 0;

             public StaticVar() {
                   a++;
                   System.out.println(a);
             }

             public static void main(String[] args) {

                    StaticVar o1 =  new StaticVar();
                    StaticVar o2 =  new StaticVar();

             }

        } 
 
 Output: 1
         1 
                 

Using static keyword- i.e static variable,

 
      public class StaticVar {

            static int a = 0;

            public StaticVar() {
                   a++;
                   System.out.println(a);

            }

            public static void main(String[] args) {

                   StaticVar o1 =  new StaticVar();      
                   StaticVar o2 =  new StaticVar();

            }

     }

Output:--  1
            2

                 

2) Static block:--

         
              Static blocks are nothing but a normal block of code, enclosed in braces {},preceded with static keyword. These static block will be called when JVM loads the class into memory. Incase a class has multiple static blocks across the class, then JVM combines all these blocks as a single block of code and executes it. Static blocks will be called only once, when it is loaded into memory. These are also called initialization blocks.
                Static block is mainly used for changing the default values of the static variables.

Example 1:--


    public class StaticBlk {

          static int a;

          static {

                a = 10;

                System.out.println(a);

         }

         public static void main(String[] args){

         }

   }

Output:-- 10

Example 2:-- Multiple static blocks


 public class StaticBlk {

        static int a;

        static {

              System.out.println("Static block1");

              a = 10;

        }

        static {

              System.out.println("Static block2");

              a = 20;

        }

        public static void main(String[] args){

              System.out.println("Value of a is "+a)

        }

  }

 Output:-- Static block1
                  Static block2
                  Value of a is 20

Example 3:-- Static blocks are executed before constructors.

                     public class StaticBlk {
                            static int a;
                            static {
                                    System.out.println("Static block"); 
                            }
                            public StaticBlk{
                                   System.out.println("This is constructor");
                            }
                            public static void main(String[] args){
                                     StaticBlk sb = new StaticBlk();
                            }
                     }
Output:-- Static block
               This is constructor

3) Static methods :--


             It is a method which belongs to the class not to the object. It can access only the static data.
Static method can call only other static methods not a non static methods. and it can not refer to "this" and "super" keywords anywhere.

Example:--
                        public class StaticMethod {
                                  public static void display () {
                                           System.out.println("static method");
                                  }
                                  public void disp () {
                                           System.out.println("non static method");
                                  }
                                  public static void main (String[] args) {
                                           display();    //calling without object
                                           StaticMethod obj = new StaticMethod();
                                           obj.disp(); //calling using object
                                  }
                        }
Output:-- static method
               non static method

4) Static Nested Class:--

               Nested static class is another class which is declared inside a class as a member and made static. Nested static class is also declared as member of outer class and can be  make private, public or protected like any other member. One of the main benefit of the nested static class over inner class is that instance of the static class is not attached to any enclosing instance of Outer class.

Example:
                    public class NestedClassEx {
                             private static class NestedClass {
                                       public void print () {
                                               System.out.println("Static nested class example");
                                       }
                            }
                            public static void main (String[] args) {
                                      NestedClass nc = new NestedClass();
                                      nc.print();
                            }
                    }
 Output:-- Static nested class example


Note:-- Constant variable name should be in Caps. you can use (_) in between.

Questions and answers:

1) Can we overload the static methods in Java?

         
         Yes, we can overload static methods in Java.

Example:--
                       public class StOverload {
                                 public static void display (String name) {
                                           System.out.println("Name "+name);
                                 } 
                                 public static void display (String name, int Id) {
                                           System.out.println("Name "+name+" Id "+Id);
                                 }
                                 public static void main (String[] args) {
                                            display("Anil");
                                            display("Anil" , 20);
                                 }
                       }
Output:--   Name Anil
                 Name Anil Id 20


2) Can we write main method as  static public void main(String[] args) ?

 
Yes, we can write main method like static public void main(String[] args){}.


3) What will happen if we remove the static keyword from the main method ?


No compilation error but will get run time error as "NoSuchMethodError".


 4) Can we override static methods in Java?
 

No, we can not override static methods in Java.

5) Why main method is static in Java?  

 
     Object is not required to call the static method, If it is non-static method then jvm create object first then call main() method that will lead the problem of extra memory allocation.



6) Which memory areas does instance and static variables use ?  

 
Instance variables stored in heap and static variables are stored in method area.

7) Can we serialize static variables ?

 
 No, Only object and it's members are serialized. Static variables are shared variables and doesn't correspond to a specific object.


8) What is a static import ?
    
     
         Static imports allow us to import all static fields and methods of the class, you can access them without class name reference.


9) Can we execute a program without  main() method?


     Yes, its possible in previous versions of java not in 1.7 using static block.

                      public class StaticBlockEx {
                             static {
                                    System.out.println("Static block invoked");
                                    System.exit(0);
                             }
                      }

Output :-- Static block invoked


Related Post:--
1) String Interview Questions and Answers
2) Factory Design Pattern in Java
3) Singleton Design Pattern in java with example
4) Difference between Loose Coupling and Tight Coupling in Java With Examples.
5) Internal implementation of ArrayList in Java
6) Java Vertual Machine(JVM) Architecture in Java