JAVA interview question and answer part 2

Back
What are the types of JDBC Driver Models and explain them
There are two types of JDBC Driver Models
1) Two tier model
2) Three tier model
Two tier model: In this model, Java applications interact directly with the database. A JDBC driver is required to communicate with the particular database management system that is being accessed. SQL statements are sent to the database and the results are given to user. This model is referred to as client/server configuration where user is the client and the machine that has the database is called as the server.
Three tier model: A middle tier is introduced in this model. The functions of this model are:
A) Collection of SQL statements from the client and handing it over to the database,
B) Receiving results from database to the client and
C) Maintaining control over accessing and updating of the above.

What are the steps involved for making a connection with a database or how do you connect to a database?
1) Loading the driver : To load the driver, Class. forName() method is used. Class. forName(”sun. jdbc. odbc. JdbcOdbcDriver”); When the driver is loaded, it registers itself with the java. sql. DriverManager class as an available database driver.
2) Making a connection with database: To open a connection to a given database, DriverManager. getConnection() method is used. Connection con = DriverManager. getConnection (”jdbc:odbc:somedb”, “user”, “password”);
3) Executing SQL statements : To execute a SQL query, java. sql. statements class is used. createStatement() method of Connection to obtain a new Statement object. Statement stmt = con. createStatement(); A query that returns data can be executed using the executeQuery() method of Statement. This method executes the statement and returns a java. sql. ResultSet that encapsulates the retrieved data:
ResultSet rs = stmt. executeQuery(”SELECT * FROM some table”);
4) Process the results : ResultSet returns one row at a time. Next() method of ResultSet object can be called to move to the next row. The getString() and getObject() methods are used for retrieving column values: while(rs. next()) { String event = rs. getString(”event”); Object count = (Integer) rs. getObject(”count”);

What type of driver did you use in project?
JDBC-ODBC Bridge driver (is a driver that uses native(C language) libraries and makes calls to an existing ODBC driver to access a database engine).

What are the types of statements in JDBC?
Statement: to be used createStatement() method for executing single SQL statement
PreparedStatement — To be used preparedStatement() method for executing same SQL statement over and over.
CallableStatement — To be used prepareCall() method for multiple SQL statements over and over.
What is stored procedure?
Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters.

How to create and call stored procedures?
To create stored procedures: Create procedure procedurename (specify in, out and in out parameters) BEGIN Any multiple SQL statement; END;
To call stored procedures: CallableStatement csmt = con. prepareCall(”{call procedure name(?,?)}”); csmt. registerOutParameter(column no. , data type); csmt. setInt(column no. , column name) csmt. execute();

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

What is the difference between an applet and a servlet?
1) Servlets are to servers what applets are to browsers.
2) Applets must have graphical user interfaces whereas servlets have no graphical user interfaces.

Who is loading the init() method of servlet?
Web server

What is the life cycle of a servlet?
Each Servlet has the same life cycle: a) A server loads and initializes the servlet by init () method. b) The servlet handles zero or more client’s requests through service() method. c) The server removes the servlet through destroy() method.
What is the difference between doPost and doGet methods?
1) doGet() method is used to get information, while doPost() method is used for posting information.
2) doGet() requests can’t send large amount of information and is limited to 240-255 characters. However, doPost()requests passes all of its data, of unlimited length.
3) A doGet() request is appended to the request URL in a query string and this allows the exchange is visible to the client, whereas a doPost() request passes directly over the socket connection as part of its HTTP request body and the exchange are invisible to the client.

How many ways can we track client and what are they?
The servlet API provides two ways to track client state and they are:
1) Using Session tracking
2) Using Cookies.

What is session tracking and how do you track a user session in servlets?
Session tracking is a mechanism that servlets use to maintain state about a series requests from the same user across some period of time. The methods used for session tracking are:
A) User Authentication - occurs when a web server restricts access to some of its resources to only those clients that log in using a recognized username and password.
B) Hidden form fields - fields are added to an HTML form that are not displayed in the client’s browser. When the form containing the fields is submitted, the fields are sent back to the server.
C) URL rewriting - every URL that the user clicks on is dynamically modified or rewritten to include extra information. The extra information can be in the form of extra path information, added parameters or some custom, server-specific URL change.
D) Cookies - a bit of information that is sent by a web server to a browser and which can later be read back from that browser.
E) HttpSession- places a limit on the number of sessions that can exist in memory. This limit is set in the session. maxresidents property.

What is Server-Side Includes (SSI)?
Server-Side Includes allows embedding servlets within HTML pages using a special servlet tag. In many servlets that support servlets, a page can be processed by the server to include output from servlets at certain points inside the HTML page. This is accomplished using a special internal SSINCLUDE, which processes the servlet tags. SSINCLUDE servlet will be invoked whenever a file with an. shtml extension is requested. So HTML files that include server-side includes must be stored with an . shtml extension.
What are cookies and how will you use them?
Cookies are a mechanism that a servlet uses to have a client hold a small amount of state-information associated with the user.
A) Create a cookie with the Cookie constructor: public Cookie(String name, String value)
B) A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of HttpServletResponse: public void HttpServletResponse. addCookie(Cookie cookie)
C) A servlet retrieves cookies by calling the getCookies() method of HttpServletRequest: public Cookie[ ] HttpServletRequest. getCookie().

Is it possible to communicate from an applet to servlet and how many ways and how?
Yes, there are three ways to communicate from an applet to servlet and they are:
A) HTTP Communication(Text-based and object-based)
B) Socket Communication
C) RMI Communication

What is connection pooling?
With servlets, opening a database connection is a major bottleneck because we are creating and tearing down a new connection for every page request and the time taken to create connection will be more. Creating a connection pool is an ideal approach for a complicated servlet. With a connection pool, we can duplicate only the resources we need to duplicate rather than the entire servlet.
A connection pool can also intelligently manage the size of the pool and make sure each connection remains valid.
A number of connection pool packages are currently available. Some like DbConnectionBroker are freely available from Java Exchange Works by creating an object that dispenses connections and connection Ids on request. The ConnectionPool class maintains a Hastable, using Connection objects as keys and Boolean values as stored values. The Boolean value indicates whether a connection is in use or not.
A program calls getConnection() method of the ConnectionPool for getting Connection object it can use; it calls returnConnection() to give the connection back to the pool.

How does applet recognize the height and width?
Using getParameters() method.
Why should we go for interservlet communication?
Servlets running together in the same server communicate with each other in several ways. The three major reasons to use interservlet communication are:
A) Direct servlet manipulation - allows to gain access to the other currently loaded servlets and perform certain tasks (through the ServletContext object)
B) Servlet reuse - allows the servlet to reuse the public methods of another servlet.
C) Servlet collaboration - requires to communicate with each other by sharing specific information (through method invocation)

Is it possible to call servlet with parameters in the URL?
Yes. You can call a servlet with parameters in the syntax as
(?Param1 = xxx || m2 = yyy).

What is Servlet chaining?
Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request. In servlet chaining, one servlet’s output is piped to the next servlet’s input. This process continues until the last servlet is reached. Its output is then sent back to the client.

How do servlets handle multiple simultaneous requests?
The server has multiple threads that are available to handle requests. When a request comes in, it is assigned to a thread, which calls a service method
Example: doGet(), doPost() and service()) of the servlet. For this reason, a single servlet object can have its service methods called by many threads at once.

What is Inet address?
Every computer connected to a network has an IP address. An IP address is a number that uniquely identifies each computer on the Net. An IP address is a 32-bit number.
What is the difference between TCP/IP and UDP?
TCP/IP is a two-way communication between the client and the server and it is a reliable and there is a confirmation regarding reaching the message to the destination. It is like a phone call.
UDP is a one-way communication only between the client and the server and it is not a reliable and there is no confirmation regarding reaching the message to the destination. It is like a postal mail.

What is Domain Naming Service(DNS)?
It is very difficult to remember a set of numbers(IP address) to connect to the Internet. The Domain Naming Service(DNS) is used to overcome this problem. It maps one particular IP address to a string of characters.
Example: www. mascom. com implies com is the domain name reserved for US commercial sites, moscom is the name of the company and www is the name of the specific computer, which is mascom’s server.

What is URL?
URL stands for Uniform Resource Locator and it points to resource files on the Internet.
URL has four components: http://www. address. com:80/index.html, where http - protocol name, address - IP address or host name, 80 - port number and index.html - file path.

What is RMI and steps involved in developing an RMI object?
Remote Method Invocation (RMI) allows java object that executes on one machine and to invoke the method of a Java object to execute on another machine. The steps involved in developing an RMI object are:
A) Define the interfaces
B) Implementing these interfaces
C) Compile the interfaces and their implementations with the java compiler
D) Compile the server implementation with RMI compiler
E) Run the RMI registry
F) Run the application
What is RMI architecture?
RMI architecture consists of four layers and each layer performs specific functions:
A) Application layer - contains the actual object definition.
B) Proxy layer - consists of stub and skeleton.
C) Remote Reference layer - gets the stream of bytes from the transport layer and sends it to the proxy layer.
D) Transportation layer - responsible for handling the actual machine-to-machine communication.

what is UnicastRemoteObject?
All remote objects must extend UnicastRemoteObject, which provides functionality that is needed to make objects available from remote machines.

Explain the methods, rebind() and lookup() in Naming class?
rebind() of the Naming class(found in java. rmi) is used to update the RMI registry on the server machine. Naming. rebind(”AddSever”, AddServerImpl);
lookup() of the Naming class accepts one argument, the rmi URL and returns a reference to an object of type AddServerImpl.

What is a Java Bean?
A Java Bean is a software component that has been designed to be reusable in a variety of different environments.

What is a Jar file?
Jar file allows to efficiently deploying a set of classes and their associated resources. The elements in a jar file are compressed, which makes downloading a Jar file much faster than separately downloading several uncompressed files. The package java. util. zip contains classes that read and write jar files.
What is BDK?
BDK, Bean Development Kit is a tool that enables to create, configure and connect a set of set of Beans and it can be used to test Beans without writing a code.

What is JSP?
JSP is a dynamic scripting capability for web pages that allows Java as well as a few special tags to be embedded into a web file (HTML/XML, etc). The suffix traditionally ends with .jsp to indicate to the web server that the file is a JSP files. JSP is a server side technology - you can’t do any client side validation with it. The advantages are:
A) The JSP assists in making the HTML more functional. Servlets on the other hand allow outputting of HTML but it is a tedious process. B) It is easy to make a change and then let the JSP capability of the web server you are using deal with compiling it into a servlet and running it.

What are JSP scripting elements?
JSP scripting elements lets to insert Java code into the servlet that will be generated from the current JSP page. There are three forms:
A) Expressions of the form <%= expression %> that are evaluated and inserted into the output,
B) Scriptlets of the form<% code %>that are inserted into the servlet’s service method
C) Declarations of the form <%! Code %>that are inserted into the body of the servlet class, outside of any existing methods.

What are JSP Directives?
A JSP directive affects the overall structure of the servlet class. It usually has the following form:<%@ directive attribute=”value” %> However, you can also combine multiple attribute settings for a single directive, as follows:<%@ directive attribute1=”value1″ attribute 2=”value2″ . . . attributeN =”valueN” %> There are two main types of directive: page, which lets to do things like import classes, customize the servlet superclass, and the like; and include, which lets to insert a file into the servlet class at the time the JSP file is translated into a servlet
What are Predefined variables or implicit objects?
To simplify code in JSP expressions and scriptlets, we can use eight automatically defined variables, sometimes called implicit objects. They are request, response, out, session, application, config, pageContext, and page.

What are JSP ACTIONS?
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. Available actions include: jsp:include - Include a file at the time the page is requested. jsp:useBean - Find or instantiate a JavaBean. jsp:setProperty - Set the property of a JavaBean. jsp:getProperty - Insert the property of a JavaBean into the output. jsp:forward - Forward the requester to a newpage. Jsp: plugin - Generate browser-specific code that makes an OBJECT or EMBED

How can I set a cookie in JSP?
response. setHeader(”Set-Cookie”, “cookie string”); To give the response-object to a bean, write a method setResponse (HttpServletResponse response) - to the bean, and in jsp-file:<% bean. setResponse (response); %>

How can I delete a cookie with JSP?
Suppose I have a cookie called “foo, ” that I set a while ago & I want it to go away.
I simply:
<%
Cookie killCookie = new Cookie(”foo”, null);
KillCookie. setPath(”/”);
killCookie. setMaxAge(0);
response. addCookie(killCookie);
%>

How are Servlets and JSP Pages related?
JSP pages are focused around HTML (or XML) with Java codes and JSP tags inside them. When a web server that has JSP support is asked for a JSP page, it checks to see if it has already compiled the page into a servlet. Thus, JSP pages become servlets and are transformed into pure Java and then compiled, loaded into the server and executed.
What is the difference between an Interface and an Abstract class
An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.

What is the purpose of garbage collection in Java, and when is it used
The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.

Describe synchronization in respect to multithreading.
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.

Explain different way of using thread
The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.

What are pass by reference and passby value
Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.

What is HashMap and Map
Map is Interface and Hashmap is class that implements that.
Difference between HashMap and HashTable
The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.

What is the difference between a constructor and a method
A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

What is an Iterator
Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.

State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.
Public : Public class is visible in other packages, field is visible everywhere (class must be public too) Private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.
Protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
Default : What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package.
What is an abstract class
Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such.
A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.

What is static in java
Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.

What is final
A final class can't be extended ie. final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).

Difference between Vector and ArrayList
Vector is synchronized whereas arraylist is not.

Difference between Swing and Awt
AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.

Share your requirement with me and give your business a much needed thrust.
CONTACT HERE