Method Overriding example

Method Overriding example
 package com.ram;

class Car{
 int CC;
 String name;
 
 public void display(){
  System.out.println("Will diaplsy car details ...");
 }
}

class BMW extends Car{
 public void display(){
  name="BMW X5";
  CC = 2979;
  System.out.println(name+" has "+CC+" CC");
 }
}

class Benz extends Car{
 public void display(){
  name = "Mercedes-Benz E class";
  CC = 3498;
  System.out.println(name+" has "+CC+" CC");
 }
}

public class OverrideExample {
 public static void main(String[] args) {
  Car bmw = new BMW();
  Car benz = new Benz();
  
  bmw.display();
  benz.display();
 }
}

 
Execute OverrideExample class and you get the below output:
BMW X5 has 2979 CC
Mercedes-Benz E class has 3498 CC

Method Overloading example

Method Overload example
 package com.ram;

class Sum{
 
 public int add(int x, int y){
  return (x + y);
 }
 
 public int add(int x, int y, int z){
  return (x + y + z);
 }
 
 public double add(int x, double y){
  return (x + y);
 }
}

public class OverloadExample {
 public static void main(String[] args) {
  Sum sum = new Sum();
  System.out.println(sum.add(10, 20));
  System.out.println(sum.add(10, 20, 30));
  System.out.println(sum.add(10, 10.50));
 }
}


 
Execute OverloadExample class and you get the below output:
30
60
20.5

Interface example

Interface example
 package com.ram;

interface Mother{
 int MOTHER_PROPERTY = 1000000;
}

interface Father{
 int FATHER_PROPERTY = 5000000;
}

class Child implements Mother,Father{
 int total_property = MOTHER_PROPERTY + FATHER_PROPERTY;
 
 public void display(){
  System.out.println("Totoal property of child is = "+total_property);
 }
}

public class InterfaceExample {
 public static void main(String[] args) {
  Child child = new Child();
  child.display();
 }
}


 
Execute InterfaceExample class and you get the below output:
Totoal property of child is = 6000000

Abstract class example

Abstract class example
 package com.ram;

abstract class Mobile{
 String name;
 String os;
 String model;
 
 public abstract void display();
}

class Samsung extends Mobile{

 @Override
 public void display() {
  name = "Samsung";
  os = "Android";
  model = "Galaxy SIII";
  System.out.println(name+" "+model+" uses "+os+" operating system");
 }
}

public class AbstractClassExample {
 public static void main(String[] args) {
  Mobile obj = new Samsung();
  obj.display();
 }
}

 
Execute AbstractClassExample class and you get the below output:
Samsung Galaxy SIII uses Android operating system

Java Programming

pass-by-value or pass-by-reference?

Question: Does java support pass-by-value or pass-by-reference?
Answer: Java is pass-by-value for all variables running with in a single virtual machine. So that means it takes a copy of the variable value and then that copied value will be passed. So java passes the copy of the bits representing the value. For example, we have declared two int variables a and b and we have assigned values 10 and 20 to them respectively. We now pass these variables as parameter to an add() method, which looks like add(a, b). Now what java does is, it takes a copy of these values and those copied values would be sent to the add method and not the original values or reference to those values. Whatever happens next in the add method will not effect the actual values in the variables.
The above explanation is regarding primitive data types. What if we have to pass objects as parameters? The answer is even the object references are passed by values only. That means java passes a copy of the bits representing the reference to an object. Here two references point to the same object. So, any change made by any of the reference will effect the other as well. For example, suppose we have ref1 as a reference to the object obj. And object obj has a variable a whose value is 15. Now we pass this reference ref1 as a parameter to a method. So java copies the bits of ref1 and then the copied value is sent. Let us name the copied reference as ref2. Now suppose ref2 changes the value of variable a in the object to 25. Then the value of variable a pointed by ref1 will also be 25. Because both ref1 and ref2 are pointing to the same object obj.

JDBC interview questions and answers

  1. What is JDBC?
    Answer: JDBC is an acronym for Java Data Base Connectivity. It is an API for communicating with relational data base (where data is stored in tables with rows and columns). A developer can make use of the API which has classes (java.sql.DriverManager, java.sql.Date etc) and interfaces (Connection, Driver, Statement, ResultSet), to persist the data.
  2. Explain the general procedure for establishing a connection with the data base.
    Answer:
    • Register the driver. Below piece of code is an example of registering oracle driver.
        Driver driver = new oracle.jdbc.driver.OracleDriver();
        DriverManager.registerDriver(driver);
        
    • Use DriverManager.getConnection method to establish the connection with the data base as shown in the below code.
       Connection conn = DriverManager.getConnection("dbc:oracle:thin:@localhost:1521:xe","hr","hr");
       
  3. Connection is an interface. How can you create an object to Connection interface?
    Answer: We cannot directly create an object to Connection interface. When we execute Connection c = DriverManager.getConnection(); it internally executes the code that is provided by JDBC driver vendor. This code creates an object based on the class provided by the vendor that implements connection interface.
  4. What are the different types of statements in JDBC?
    Answer: JDBC API provides us with 3 different statements (interfaces) using which we can persist data after establishing the connection.
    • Statement: It is used to implement simple SQL statements with no parameters.
       Statement stmt = null;
       stmt = con.createStatement();
       

    • PreparedStatement: This is used for precompiling SQL statements that may or may not contain input parameters. A sample code of how to use PreparedStatement is given below.
       PreparedStatement pstmt = conn.prepareStatement("insert into sample values(?)");
        for(int i=0; i<10; i++){
         pstmt.setInt(1, i);
         pstmt.executeUpdate();
       
      To see the complete example for PreparedStatement ... "Click here"
    • CallableStatement: This is used to execute stored procedures (a stored procedure is a group of SQL statements that form a logical unit and perform a particular task) that may contain both input and output parameters.
       callStmt = conn.prepareCall("{call procx(?,?,?)}");
        // set input parameters
        callStmt.setInt(1,10);
        callStmt.setInt(2, 20);
      
        //register output types
        callStmt.registerOutParameter(3, Types.INTEGER);
        callStmt.execute();
       
      To see the complete example for CallableStatement ... "Click here"
  5. Explain about the different JDBC drivers.
    Answer: There are four types of drivers. They are:
    • Type I driver or JDBC-ODBC Bridge Driver
    • Type II driver or JDBC-Native API Driver
    • Type IV driver or Pure java Driver
    • Type III driver or JDBC-Net pure Java
    To learn more about each driver ... "Click here"
  6. Can we execute non select statement using execute query?
    Answer: Yes we can execute non select statement using execute query but it is not recommended. But at the end data base will be updated. Some drivers give exceptions like inetGate.jar
  7. What is ResultSet?
    Answer: ResultSet object is returned as a result of executing the executeQuery. ResultSet represents a set of rows. ResultSet is an interface.
     String query = "select employee_id, first_name from employees";
      ResultSet rs = stmt.executeQuery(query);
      
      while(rs.next()){
       System.out.print("Employee_Id = "+rs.getString(1));
       System.out.println("  First_Name = "+rs.getString("first_name"));
      }
     
    Have a look at the complete program by ... Clicking here
  8. What is ResultSetMetaData?
    Answer: ResultSetMetaData is used to give more information about the ResultSet objects like data type of the columns, name of the columns etc. For example ResultSetMetaDate example
  9. How can you improve the performance of an application?
    Answer: We can improve the performance of the application by choosing appropriate value for fetch size. "statement.setFetchSize()" sets the fetch size used by the jdbc driver.
    The default fetch size of oracle driver is "10". In some drivers like JdbcOdbc by Sun Micro Systems the default fetch size id "1" and we cannot increase the fetch size.
  10. How do we know the fetch size of the driver we are using?
    Answer: To know the fetch size, we can use the below statement.
     System.out.println(statement.getFetchSize());
     
  11. How do you commit your transactions?
    Answer: By default all the jdbc drivers will be running in "autocommit" mode. To find out whether the driver is running in autocommit mode or not we can use the below statement.
      System.out.println(connection.getAutoCommit());
      
    If you want to explicitly commit a transaction then use:
    connection.commit();
  12. How do you control transactions in JDBC?
    Answer: We can control the transactions in JDBC by setting the autoCommit to "false".
  13. What is connection pooling?
    Answer: Opening a connection to a database is a time-consuming process. For short queries, it can take much longer to open the connection than to perform the actual database retrieval. Consequently, it makes sense to reuse Connection objects in applications that connect repeatedly to the same database. A connection pool is a cache of database connections maintained so that the connections can be reused when future requests to the database are required. It reduces the overhead for the application and increases performance.
  14. What is the use of Class.forName("SomeClass")?
    Answer: Class.forName("SomeClass") does the following things.
    • It loads the "SomeClass".
    • Returns an instance of SomeClass
    For example:
     Class.forName("oracle.jdbc.driver.OracleDriver");