CORE JAVA /OOPS

Q1: What are the advantages of OOPL?

Ans: Object oriented programming languages directly represent the real life objects. The features of OOPL as inhreitance, polymorphism, encapsulation makes it powerful.

Q2: What do mean by polymorphisum, inheritance, encapsulation?

Ans: Polymorhisum: is a feature of OOPl that at run time depending upon the type of object the appropriate method is called.
Inheritance: is a feature of OOPL that represents the “is a” relationship between different objects(classes). Say in real life a manager is a employee. So in OOPL manger class is inherited from the employee class.
Encapsulation: is a feature of OOPL that is used to hide the information.

Q3: What do you mean by static methods?

Ans: By using the static method there is no need creating an object of that class to use that method. We can directly call that method on that class. For example, say class A has static function f(), then we can call f() function as A.f(). There is no need of creating an object of class A.

Q4: What do you mean by virtual methods?

Ans: virtual methods are used to use the polymorhism feature in C++. Say class A is inherited from class B. If we declare say fuction f() as virtual in class B and override the same function in class A then at runtime appropriate method of the class will be called depending upon the type of the object.

Q5: Given two tables Student(SID, Name, Course) and Level(SID, level) write the SQL statement to get the name and SID of the student who are taking course = 3 and at freshman level.

Ans: SELECT Student.name, Student.SID
FROM Student, Level
WHERE Student.SID = Level.SID
AND Level.Level = “freshman”
AND Student.Course = 3;

Q6: What are the disadvantages of using threads?

Ans: DeadLock.

Q1: Write the Java code to declare any constant (say gravitational constant) and to get its value

Ans: Class ABC
{
static final float GRAVITATIONAL_CONSTANT = 9.8;
public void getConstant()
{
system.out.println(“Gravitational_Constant: ” + GRAVITATIONAL_CONSTANT);
}
}
Q2: What do you mean by multiple inheritance in C++ ?

Ans: Multiple inheritance is a feature in C++ by which one class can be of different types. Say class teachingAssistant is inherited from two classes say teacher and Student.

Q3: Can you write Java code for declaration of multiple inheritance in Java ?

Ans: Class C extends A implements B
{
}

  1. What are the Object and Class classes used for?

The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.


  1. What is Serialization and deserialization?

Serialization is the process of writing the state of an object to a byte stream.
Deserialization is the process of restoring these objects.

  1. What interface must an object implement before it can be written to a stream as an object?

An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.


  1. What is the ResourceBundle class?

The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program’s appearance to the particular locale in which it is being run.

  1. What class allows you to read objects directly from a stream?

The ObjectInputStream class supports the reading of objects from input streams.


  1. How are this() and super() used with constructors?

this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.


  1. How is it possible for two String objects with identical values not to be equal under the == operator?

The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory.

  1. How does multithreading take place on a computer with a single CPU?

The operating system’s task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.


  1. What restrictions are placed on method overloading?

Two methods may not have the same name and argument list but different return types.


  1. What restrictions are placed on method overriding?

Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method.



  1. What happens when a thread cannot acquire a lock on an object?

If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object’s lock, it enters the waiting state until the lock becomes available.


  1. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?

The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.


  1. What classes of exceptions may be caught by a catch clause?

A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.

  1. What is the purpose of finalization?

The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

  1. What is synchronization and why is it important?

With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often causes dirty data and leads to significant errors.


  1. What are synchronized methods and synchronized statements?

Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method’s object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

  1. What is the serialization?

The serialization is a kind of mechanism that makes a class or a bean persistence by having its properties or fields and state information saved and restored to and from storage.


  1. How to make a class or a bean serializable?

By implementing either the java.io.Serializable interface, or the java.io.Externalizable interface. As long as one class in a class’s inheritance hierarchy implements Serializable or Externalizable, that class is serializable.


  1. How many methods in the Serializable interface?

There is no method in the Serializable interface. The Serializable interface acts as a marker, telling the object serialization tools that your class is serializable.


  1. How many methods in the Externalizable interface?

There are two methods in the Externalizable interface. You have to implement these two methods in order to make your class externalizable. These two methods are readExternal() and writeExternal().


  1. What is the difference between Serializalble and Externalizable interface?

When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class’s serialization process.


  1. What is a transient variable?

A transient variable is a variable that may not be serialized. If you don’t want some field not to be serialized, you can mark that field transient or static.

 

 

PROGRAMMING INTERVIEW QUESTIONS

 

Connecting to a Database

 

JDBC Questions


  1. What is JDBC?

JDBC is a layer of abstraction that allows users to choose between databases. It allows you to change to a different database engine and to write to a single API. JDBC allows you to write database applications in Java without having to concern yourself with the underlying details of a particular database.


  1. What are the two major components of JDBC?

One implementation interface for database manufacturers, the other implementation interface for application and applet writers.


  1. What is JDBC Driver interface?

The JDBC Driver interface provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each vendors driver must provide implementations of the java.sql.Connection,Statement,PreparedStatement, CallableStatement, ResultSet and Driver.


  1. What are the common tasks of JDBC?
    • Create an instance of a JDBC driver or load JDBC drivers through jdbc.drivers
    • Register a driver
    • Specify a database
    • Open a database connection
    • Submit a query
    • Receive results


  1. What packages are used by JDBC?

There are 8 packages: java.sql.Driver, Connection,Statement, PreparedStatement, CallableStatement, ResultSet, ResultSetMetaData, DatabaseMetaData.


  1. What are the flow statements of JDBC?

A URL string –>getConnection–>DriverManager–>Driver–>Connection–>Statement–>executeQuery–>ResultSet.


  1. What are the steps involved in establishing a connection?

This involves two steps: (1) loading the driver and (2) making the connection.


  1. How can you load the drivers?

Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following code will load it:

Eg.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Your driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverXYZ , you would load the driver with the following line of code:

E.g.
Class.forName("jdbc.DriverXYZ");


  1. What Class.forName will do while loading drivers?

It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.


  1. How can you make the connection?

In establishing a connection is to have the appropriate driver connect to the DBMS. The following line of code illustrates the general idea:

E.g.
String url = "jdbc:odbc:Fred";
Connection con = DriverManager.getConnection(url, "Fernanda", "J8");


  1. How can you create JDBC statements?

A Statement object is what sends your SQL statement to the DBMS. You simply create a Statement object and then execute it, supplying the appropriate execute method with the SQL statement you want to send. For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate. E.g. It takes an instance of an active connection to create a Statement object. In the following example, we use our Connection object con to create the Statement object stmt :

Statement stmt = con.createStatement();


  1. How can you retrieve data from the ResultSet?

First JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs.

E.g.
ResultSet rs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
 
Second:
String s = rs.getString("COF_NAME");

The method getString is invoked on the ResultSet object rs , so getString will retrieve (get) the value stored in the column COF_NAME in the current row of rs


  1. What are the different types of Statements?

1.Statement (use createStatement method) 2. Prepared Statement (Use prepareStatement method) and 3. Callable Statement (Use prepareCall)


  1. How can you use PreparedStatement?

This special type of statement is derived from the more general class, Statement. If you want to execute a Statement object many times, it will normally reduce execution time to use a PreparedStatement object instead. The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement ‘s SQL statement without having to compile it first.

E.g.
PreparedStatement updateSales = con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");


  1. How to call a Stored Procedure from JDBC?

The first step is to create a CallableStatement object. As with Statement an and PreparedStatement objects, this is done with an open Connection object. A CallableStatement object contains a call to a stored procedure;

E.g.
CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();


  1. How to Retrieve Warnings?

SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object

E.g.
SQLWarning warning = stmt.getWarnings();
    if (warning != null) {
 
        while (warning != null) {
          System.out.println("Message: " + warning.getMessage());
          System.out.println("SQLState: " + warning.getSQLState());
          System.out.print("Vendor error code: ");
          System.out.println(warning.getErrorCode());
          warning = warning.getNextWarning();
        }
    }


  1. How to Make Updates to Updatable Result Sets?

Another new feature in the JDBC 2.0 API is the ability to update rows in a result set using methods in the Java programming language rather than having to send an SQL command. But before you can take advantage of this capability, you need to create a ResultSet object that is updatable. In order to do this, you supply the ResultSet constant CONCUR_UPDATABLE to the createStatement method.

E.g.
Connection con = DriverManager.getConnection("jdbc:mySubprotocol:mySubName");
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, 
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = ("SELECT COF_NAME, PRICE FROM COFFEES");

 

Strings HANDLING

Constructing a String

If you are constructing a string with several appends, it may be more efficient to construct it using a StringBuffer and then convert it to an immutable String object.

StringBuffer buf = new StringBuffer(“Initial Text”);

   

// Modify

int index = 1;

buf.insert(index, “abc”);

buf.append(“def”);

          

 // Convert to string

 String s = buf.toString();

Getting a Substring from a String

int start = 1;

int end = 4;

 String substr = “aString”.substring(start, end);   // Str

 

Searching a String

 

 String string = “aString”;

   

 // First occurrence.

 int index = string.indexOf(‘S’);  // 1

 

 // Last occurrence.

 index = string.lastIndexOf(‘i’);  // 4

   

 // Not found.

 index = string.lastIndexOf(‘z’);  // -1

 

Replacing Characters in a String

 

// Replace all occurrences of ‘a’ with ‘o’

String newString = string.replace(‘a’, ‘o’);

 

Replacing Substrings in a String

 

 static String replace(String str,

         String pattern, String replace) {

   int s = 0;

   int e = 0;

 StringBuffer result = new StringBuffer();

   

  while ((e = str.indexOf(pattern, s)) >= 0) {

    result.append(str.substring(s, e));

    result.append(replace);

    s = e+pattern.length();

      }

    result.append(str.substring(s));

    return result.toString();

    }

 

Converting a String to Upper or Lower Case

 

 // Convert to upper case

 String upper = string.toUpperCase(); 

   

 // Convert to lower case

 String lower = string.toLowerCase(); 

 

Converting a String to a Number

int i = Integer.parseInt(“123”);

long l = Long.parseLong(“123”);

float f = Float.parseFloat(“123.4”);

double d = Double.parseDouble(“123.4e10”);

 

Breaking a String into Words

String aString = “word1 word2 word3”;

StringTokenizer parser =

          new StringTokenizer(aString);

while (parser.hasMoreTokens()) {

        processWord(parser.nextToken());

 

 

JSP /Servlets

 

  1. What is the servlet?

Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet may be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database.

  1. What’s the difference between servlets and applets?

Servlets are to servers; applets are to browsers. Unlike applets, however, servlets have no graphical user interface.

  1. What’s the advantages using servlets than using CGI?

Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. It is efficient, convenient, powerful, portable, secure and inexpensive. Servlets also address the problem of doing server-side programming with platform-specific APIs: they are developed with Java Servlet API, a standard Java extension.

  1. What are the uses of Servlets?

A servlet can handle multiple requests concurrently, and can synchronize requests. This allows servlets to support systems such as on-line conferencing. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries.

  1. What’s the Servlet Interface?

The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet.

Servlets-->Generic Servlet-->HttpServlet-->MyServlet.

The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet.

  1. When a servlet accepts a call from a client, it receives two objects. What are they?

ServeltRequest: which encapsulates the communication from the client to the server.

ServletResponse: which encapsulates the communication from the servlet back to the client.

ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.

  1. What information that the ServletRequest interface allows the servlet access to?

Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names of the remote host that made the request and the server that received it. The input stream, ServletInputStream.Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and PUT methods.

  1. What information that the ServletResponse interface gives the servlet methods for replying to the client?

It Allows the servlet to set the content length and MIME type of the reply. Provides an output stream, ServletOutputStream and a Writer through which the servlet can send the reply data.

  1. If you want a servlet to take the same action for both GET and POST request, what should you do?

Simply have doGet call doPost, or vice versa.

  1. What is the servlet life cycle?
    Each servlet has the same life cycle:
    A server loads and initializes the servlet (init())
    The servlet handles zero or more client requests (service())
    The server removes the servlet (destroy()) (some servers do this step only when they shut down)
  2. Which code line must be set before any of the lines that use the PrintWriter?

setContentType() method must be set before transmitting the actual document.

  1. How HTTP Servlet handles client requests?

An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request.

13. Difference between single thread and multi thread model servlet

 

 

 

Advertisements