A Quick Referesher On JAVA

Why Java?

Java derives much of its character from C and C++. This is by intent. The Java designers knew that using the familiar syntax of C and echoing the object-oriented features of C++ would make their language appealing to the legions of
experienced C/C++ programmers. In addition to the surface similarities, Java shares some of the other attributes that helped make C and C++ successful. First, Java was designed, tested, and refined by real, working programmers. It is a language grounded in the needs and experiences of the people who devised it.


Thus, Java is also a programmer’s language. Second, Java is cohesive and logically consistent. Third, except for those constraints imposed by the Internet environment, Java gives you, the programmer, and full control. If you program well, your programs reflect it.

JAVA Interview Preparation

Question: 1 Can we define private and protected modifiers for variables in interfaces?(Core Java)

Answer: No.

Question: 2 What is the query used to display all tables names in SQL Server (Query
analyzer)? (JDBC)

Answer: select * from information_schema.tables

Question: 3 What is Externalizable? (Core Java)

Answer: Externalizable is an Interface that extends Serializable Interface. And sends
data into Streams in Compressed Format. It has two methods,
writeExternal(ObjectOuput out) and readExternal(ObjectInput in)

Question: 4 What modifiers are allowed for methods in an Interface? (Core Java)

Answer: Only public and abstract modifiers are allowed for methods in interfaces.

Question: 5 What is a local, member and a class variable? (Core Java)

Answer: Variables declared within a method are “local” variables. Variables declared
within the class i.e not within any methods are “member” variables (global variables).
Variables declared within the class i.e not within any methods and are defined as
“static” are class variables.

Question: 6 How many types of JDBC Drivers are present and what are they? (JDBC)

Answer: There are 4 types of JDBC Drivers

  • Type 1: JDBC-ODBC Bridge Driver
  • Type 2: Native API Partly Java Driver
  • Type 3: Network protocol Driver
  • Type 4: JDBC Net pure Java Driver

Question: 7 Can we implement an interface in a JSP? (JSP)

Answer: No

Question: 8 What is the difference between ServletContext and PageContext? (JSP)

Answer: ServletContext: Gives the information about the container PageContext: Gives
the information about the Request

Question:9 What is the difference in using request.getRequestDispatcher() and
context.getRequestDispatcher()? (JSP)

Answer: request.getRequestDispatcher(path): In order to create it we need to give the
relative path of the resource context.getRequestDispatcher(path): In order to create it
we need to give the absolute path of the resource.

Question:10 How to pass information from JSP to included JSP? (JSP)

Answer: Using <%jsp:param> tag.

Question: 11 What is the difference between directives include and jsp include? (JSP)

Answer: <%@ include> : Used to include static resources during translation time. :
Used to include dynamic content or static content during.

Question: 12 What are Predefined variables or implicit objects?

Answer: 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.

Question: 13 What is BDK?

Answer: 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.

Question: 14 What is a Jar file?

Answer: 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.

Question: 15 Explain the methods, rebind() and lookup() in Naming class?

Answer: 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.

Question: 16 what is UnicastRemoteObject?

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

Question: 17 What is RMI architecture?

Answer: 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 sendsit to the proxy layer.
  • d) Transportation layer – responsible for handling the actual machine-to-machine communication.

Question: 18 What steps are involved in developing an RMI object?

Answer: 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.

Question: 19 What is RMI?

Answer: 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.

Question: 20 How do servlets handle multiple simultaneous requests?

Answer: 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 (for 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.

Question: 21 What is Servlet chaining?

Answer: 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.

Question: 22 Is it possible to call servlet with parameters in the URL?

Answer: Yes. You can call a servlet with parameters in the syntax as
(?Param1 = xxx || m2 = yyy).

Question: 23 Why should we go for interservlet communication?

Answer: 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)

Question: 24 What is connection pooling?

Answer 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.

Question: 25 Is it possible to communicate from an applet to servlet and how many ways
and how?

Answer: 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

Question: 26 What are cookies and how will you use them?

Answer: 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().

Question: 27 What is Server-Side Includes (SSI)?

Answer: 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.

Question: 28 What is session tracking and how do you track a user session in servlets?

Answer: 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.

Question:29 How many ways can we track client and what are they?

Answer: The servlet API provides two ways to track client state and they are:

  • a) Using Session tracking and
  • b) Using Cookies.

Question: 30 What is the difference between doPost and doGet methods?

Answer:

  • a) doGet() method is used to get information, while doPost() method is used for posting information.
  • b) 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.
  • c) 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.

Question: 31 How to create and call stored procedures?

Answer: 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();

Question: 32 What is stored procedure?

Answer: 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.

Question: 33 What are the types of statements in JDBC?

Answer: 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.

Question: 34 What are the steps involved for making a connection with a database or
how do you connect to a database?

Answer:

  • a) 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.
  • b) 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”);
  • c) 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”);
  • d) 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”);

Question: 35 What are the types of JDBC Driver Models and explain them?

Answer:

There are two types of JDBC Driver Models and they are:

  • a) Two tier model and
  • b) 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.

Question: 36 What is the difference between JDBC and ODBC?

Answer:

  • a) OBDC is for Microsoft and JDBC is for Java applications.
  • b) ODBC can’t be directly used with Java because it uses a C interface.
  • c) ODBC makes use of pointers which have been removed totally from Java.
  • d) ODBC mixes simple and advanced features together and has complex options for simple queries. But JDBC is designed to keep things simple while allowing advanced capabilities when required.
  • e) ODBC requires manual installation of the ODBC driver manager and driver on all client machines. JDBC drivers are written in Java and JDBC code is automatically installable, secure, and portable on all platforms.
  • f) JDBC API is a natural Java interface and is built on ODBC. JDBC retains some of the basic features of ODBC.

Question: 37 What is JDBC?

Answer: JDBC is a set of Java API for executing SQL statements. This API consists of a
set of classes and interfaces to enable programs to write pure Java Database
applications.

Question: 38 What is serialization and deserialization?

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

Question:39 What is the difference between Reader/Writer and InputStream/Output
Stream?

Answer: The Reader/Writer class is character-oriented and the
InputStream/OutputStream class is byte-oriented.

Question: 40 What is a stream and what are the types of Streams and classes of the
Streams?

Answer: A Stream is an abstraction that either produces or consumes information. There
are two types of Streams and they are:

Byte Streams: Provide a convenient means for handling input and output of bytes.
Character Streams: Provide a convenient means for handling input & output of
characters.

Byte Streams classes: Are defined by using two abstract classes, namely InputStream
and OutputStream.

Character Streams classes: Are defined by using two abstract classes, namely Reader
and Writer.

Question: 41 What are Vector, Hashtable, LinkedList and Enumeration?

Answer:
Vector : The Vector class provides the capability to implement a growable array of
objects.
Hashtable : The Hashtable class implements a Hashtable data structure. A Hashtable
indexes and stores objects in a dictionary using hash codes as the object’s keys. Hash
codes are integer values that identify objects.
LinkedList: Removing or inserting elements in the middle of an array can be done using
LinkedList. A LinkedList stores each object in a separate link whereas an array stores
object references in consecutive locations.
Enumeration: An object that implements the Enumeration interface generates a series
of elements, one at a time. It has two methods, namely hasMoreElements() and
nextElement(). HasMoreElemnts() tests if this enumeration has more elements and
nextElement method returns successive elements of the series.

Question: 42 How are the elements of different layouts organized?

Answer:
FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to
right fashion.
BorderLayout: The elements of a BorderLayout are organized at the borders (North,
South, East and West) and the center of a container.
CardLayout: The elements of a CardLayout are stacked, on top of the other, like a deck
of cards.
GridLayout: The elements of a GridLayout are of equal size and are laid out using the
square of a grid.
GridBagLayout: The elements of a GridBagLayout are organized according to a grid.
However, the elements are of different size and may occupy more than one row or
column of the grid. In addition, the rows and columns may have different sizes.

Question: 43 What is a layout manager and what are different types of layout managers
available in java AWT?

Answer: A layout manager is an object that is used to organize components in a
container. The different layouts are available are FlowLayout, BorderLayout,
CardLayout, GridLayout and GridBagLayout.

Question: 44 What is the difference between scrollbar and scrollpane?

Answer: A Scrollbar is a Component, but not a Container whereas Scrollpane is a
Conatiner and handles its own events and perform its own scrolling.

Question: 45 What is source and listener ?

Answer: Source : A source is an object that generates an event. This occurs when the
internal state of that object changes in some way.
Listener : A listener is an object that is notified when an event occurs. It has two major requirements. First, it
must have been registered with one or more sources to receive notifications about specific types of events. Second, it
must implement methods to receive and process these notifications.

Question: 46 How do you set security in applets?

Answer: using setSecurityManager() method.

Question: 47 What is the lifecycle of an applet?

Answer: init() method – Can be called when an applet is first loaded start() method –
Can be called each time an applet is started. paint() method – Can be called when the
applet is minimized or maximized. stop() method – Can be used when the browser
moves off the applet’s page. destroy() method – Can be called when the browser is
finished with the applet.

Question: 48 When do you use codebase in applet?

Answer: When the applet class file is not in the same directory, codebase is used.

Question: 49 How does applet recognize the height and width?

Answer: Using getParameters() method.

Question: 50 Are there any global variables in Java, which can be accessed by other part
of your program?

Answer: No, it is not the main method in which you define variables. Global variables
is not possible because concept of encapsulation is eliminated here.

Question: 51 What is daemon thread and which method is used to create the daemon
thread?

Answer: Daemon thread is a low priority thread which runs intermittently in the back
ground doing the garbage collection operation for the java runtime system. setDaemon
method is used to create a daemon thread.

Question: 52 When you will synchronize a piece of your code?

Answer: When you expect your code will be accessed by different threads and these
threads may change a particular data causing data corruption.

Question: 53 What is synchronization?

Answer: Synchronization is the mechanism that ensures that only one thread is accessed
the resources at a time.

Question: 54 What is the class and interface in java to create thread and which is the
most advantageous method?

Answer: Thread class and Runnable interface can be used to create threads and using
Runnable interface is the most advantageous method to create threads because we need
not extend thread class here.

Question: 55 What are the methods for inter-thread communication and what is the class
in which these methods are defined?

Answer: wait (), notify () and notifyAll() methods can be used for inter-thread
communication and these methods are in Object class. wait() :
When a thread executes a call to wait() method, it surrenders the object lock
and enters into a waiting state. notify() or notifyAll() : To remove a thread from the
waiting state, some other thread must make a call to notify() or notifyAll() method on the
same object.

Question: 56 What is multithreading?

Answer: Multithreading is the mechanism in which more than one thread run independent
of each other within the process.

Question: 57 What is the difference between process and thread?

Answer Process is a program in execution whereas thread is a separate path of
execution in a program.

Question: 58 What is the difference between Array and vector?

Answer: Array is a set of related data type and static whereas vector is a growable
array of objects and dynamic.

Question: 59 What is the difference between String and String Buffer?

Answer:

  • a) String objects are constants and immutable whereas StringBuffer objects are not.
  • b) String class supports constant strings whereas StringBuffer class supports growable and modifiable strings.

Question: 60 Can you have an inner class inside a method and what variables can you
access?

Answer: Yes, we can have an inner class inside a method and final variables can be
accessed.