-
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.
-
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");
- Register the driver. Below piece of code is an example of registering oracle driver.
-
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.
-
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"
- Statement: It is used to implement simple SQL statements with no parameters.
-
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
-
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
-
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 -
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
-
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. -
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());
-
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(); -
How do you control transactions in JDBC?Answer: We can control the transactions in JDBC by setting the autoCommit to "false".
-
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.
-
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
Class.forName("oracle.jdbc.driver.OracleDriver");
JDBC interview questions and answers
Pure object oriented programming
Question: Is java pure object oriented programming?
Answer: This has been the topic of debate for long. Java is not pure object oriented programming.
Examples of pure object oriented programming language are "Ruby", "SmallTalk" etc. Below are few reasons why java
is not a pure object oriented programming.
- Java has primitive data types like int, byte, float, double, char etc. Pure object oriented programming language should contain only classes and objects. It should not contain primitive data types. Now the question comes is why java has primitive data types? It is because primitive data types are faster than objects. Primitive data type "int" takes 4 bytes where as for Integer object just the reference to the Integer takes 32 bits.
- Java has a static keyword i.e., static fields, static methods. These are associated with the class itself, not with any particular object created from the class. You can run a program without making a single object.
- In pure object oriented language we should access everything by message passing in other words through objects. For example, write a simple addition of two numbers inside the main() method and display the output. You can run this program without creating object.
Immutable String
Question: Why is Sting class immutable?
Answer: String class is immutable. What this means is that String class
is final, its state cannot be changes and String class cannot be sub classed.
The reasons are listed below:
- In java strings are used every where. For example, user names, passwords, data base URL, network connections etc. Suppose strings are mutable and if the string goes into wrong hands (hackers) then they can change the strings and hack any system and get access to critical data. So for security reasons String classes are made immutable.
- As discussed in the previous question, immutable objects are thread safe and solves some synchronization issues.
- Java designers have come up with a separate memory for string known as "String Pool". String pool is a special storage space in heap. To support string pool facility, strings are immutable. To know more about string pool, please read the answer to question 23 of ... Core Java interview questions and answers
Operator overloading
Question: Why java does not support operator overloading?
Answer: Operator overloading means to use the same operator for different data types.
A programmer can provide his or her own operator to a class by overloading the built-in
operator to perform some specific computation when the operator is used on objects of that class.
Below are the reasons why java does not support operator overloading.
- Operator overloading can be exceedingly confusing. Keeping the human tendency in mind that some operators have specific meaning and if changed then programmers tend to make errors.
- By not supporting operator overloading, the code would be simple and clear which was one of the primary goals of java designers. And the same thing can be achieved by method overloading.
- Operator overloading also makes the task of JVM complex. What this means that JVM takes more time to execute programs.
The only overloaded operator in Java is the arithmetic "+" operator. When "+" is used with
integers it adds them. When the same "+" is used with strings it concatenates them. This can
be explained with a simple example as shown below.
package com.ram;
public class OperatorOverloading {
public static void main(String[] args) {
int a = 10;
int b = 20;
int c;
String firstName = "Ram";
String lastName = "Akunuru";
String name;
c = a + b; //Here "+" is used to add two integers.
System.out.println("c = "+c);
name = firstName + lastName; //Here "+" is used to concatenate the strings
System.out.println("Name = "+name);
}
}
Output:c = 30
Name = RamAkunuru
Immutable class
Question: How do you create an immutable class?
Answer: Immutable class or objects are those whose state(object's data) cannot be changed once
they are created. For example String class is an immutable class. Now the question is how
to create immutable objects. Below are the steps for creating immutable objects.
- Make all the fields i.e, all the member variables and methods as final.
- To further restrict the access we can use a private access modifier.
- Now mark the class as final. If class is declared as final then no other class can extend it.
Below is an example for immutable class.
package com.ram;
final class Immutable{
private final int empId;
private final String empName;
Immutable(int empId, String empName){
this.empId = empId;
this.empName = empName;
}
public int getEmpId() {
return empId;
}
public String getEmpName() {
return empName;
}
}
public class ImmutableClassExample {
public static void main(String[] args) {
Immutable imuObj = new Immutable(123456, "Ram");
System.out.println("Employye Id = "+imuObj.getEmpId());
System.out.println("Employee Name = "+imuObj.getEmpName());
}
}
Now the a question arises. What is the use of immutable class?
- Immutable classes are thread safe (it may be used from multiple threads at the same time without causing problems).
- They do not have any synchronization issues.
- Immutable objects do not copy constructors (A copy constructor is a Constructor that references to another object in the same class).
- Immutable objects can be reused by caching them.
Deadly Diamond of Death problem
Question: What is "Deadly Diamond of Death" problem in Java?
Answer: Before I explain about "Deadly Diamond of Death" problem in java, we need to know about
multiple inheritance. As we all know multiple inheritance refers to a feature in which a class
can inherit behaviors and features from more than one superclass. Java does not allow multiple
inheritance. Now the question arises why java does not support multiple inheritance? Let me
explain this with an example. Consider the following program.
package com.ram;
class A {
public void display(){
System.out.println("From class A ...");
}
}
class B extends A{
public void display(){
System.out.println("From class B ...");
}
}
class C extends A{
public void display(){
System.out.println("From class C ...");
}
}
public class D extends B,C{
//Which display() method would the class inherit, B or C?
}
In the above code, class A has a display() method. Now class A is extended by
both classes B and C. Now suppose there is a class D which extended classes B and C.
So which version of display() method would the class D inherit? In other words
class D will inherit two different implementations of the same method. This issue
is known as "Deadly Diamond of Death" because the shape of these four classes
looks like a diamond. Below diagram explains it better.
Java interesting concepts
There are a lot of interesting concepts in java and every Sunday a new interesting java concept would be published.
Enjoy reading :)
Enjoy reading :)
- What is "Deadly Diamond of Death" problem in Java?
- How do you create an immutable class?
- Why java does not support operator overloading?
- Why is Sting class immutable?
- Is java pure object oriented programming?
- Does java support pass-by-value or pass-by-reference?
- Class Loader Sub System
- How ArrayList works internally?
- Where do static methods and static variables gets stored in memory?
Subscribe to:
Posts (Atom)
