Java Interview Book Javacodehelps
Java Interview Book Javacodehelps
PAGE
2
Contents
JAVA INTERVIEW QUIZ AND ANSWER
JAVACODEHELPS
PAGE
3
Q-2. What is the difference between creating String as new() and literal?
A- When we create string with new() Operator, its created in heap and not added into
string pool while String created using literal are created in String pool itself which exists
in PermGen area of heap.
String str = new String("Test");
does not put the object str in String pool , we need to call String.intern() method
which is used to put them into String pool explicitly. its only when you create String object as
String literal e.g. String s = "Test" Java automatically put that into String pool. By the
way there is a catch here, Since we are passing arguments as "Test", which is a String
literal, it will also create another object as "Test" on string pool.
PAGE
4
Q-4. Where does equals and hashcode method comes in picture during get
operation?
A-This core Java interview question is follow-up of previous Java question and candidate
should know that once you mention hashCode, people are most likely ask, how they are used
in HashMap.When you provide key object, first it's hashcode method is called to calculate
bucket location. Since a bucket may contain more than one entry as linked list, each of those
Map.Entry object are evaluated by using equals() method to see if they contain the
actual key object or not.
PAGE
5
A-Singleton in Java is a class with just one instance in whole Java application, for example
java.lang.Runtime is a Singleton class. Creating Singleton was tricky prior Java 4 but once Java 5
introduced Enum its very easy.
Q- 8. Give a simplest way to find out the time a method takes for execution
without using any profiling tool?
A- Read the system time just before the method is invoked and immediately after method
returns. Take the time difference, which will give you the time taken by a method for execution.
To put it in code
long start = System.currentTimeMillis ();
method ();
long end = System.currentTimeMillis ();
System.out.println (Time taken for execution is + (end start));
Remember that if the time taken for execution is too small, it might show that it is taking zero
milliseconds for execution. Try it on a method which is big enough, in the sense the one which
is doing considerable amount of processing
PAGE
6
A- If you assign a superclass object to a variable of a subclass's data type, you need to do
explicit casting. Whereas, When you assign a subclass to a variable having a supeclass type,
the casting happens automatically.
A- Wrapper class is wrapper around a primitive data type. An instance of a wrapper class
contains, or wraps, a primitive value of the corresponding type and creates an Object.
Ex: java.lang.Boolean is the Wrapper for boolean, java.lang.Long is the wrapper for long etc.
PAGE
7
3. What is the difference between < jsp : include page = ... > and < % @ include file
= ... >?
A-Both the tags include information from one JSP page in another. The differences are:
< jsp : include page = ... >
This is like a function call from one jsp to another jsp. It is executed ( the included page is executed and
the generated html content is included in the content of calling jsp) each time the client page is accessed
by the client. This approach is useful while modularizing a web application. If the included file changes
then the new content will be included in the output automatically.
< % @ include file = ... >
In this case the content of the included file is textually embedded in the page that have < % @ include
file=".."> directive. In this case when the included file changes, the changed content will not get
included automatically in the output. This approach is used when the code from one jsp file required to
include in multiple jsp files.
4. What is the difference between < jsp : forward page = ... > and
response.sendRedirect(url)?
A-The element forwards the request object containing the client request information from one JSP file to
another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the
same application context as the forwarding JSP file.
sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new
request to go the redirected page. The response.sendRedirect also kills the session variables.
PAGE
8
PAGE
9
PAGE
10
Efficient Collection Handling - Likewise, Hibernate only ever inserts/updates/deletes collection rows
that actually changed.
Rolling two updates into one - As a corollary to (1) and (3), Hibernate can roll two seemingly
unrelated updates of the same object into one UPDATE statement.
Updating only the modified columns - Hibernate knows exactly which columns need updating and, if
you choose, will update only those columns.
Outer join fetching - Hibernate implements a very efficient outer-join fetching algorithm! In addition,
you can use subselect and batch pre-fetch optimizations.
Lazy collection initialization
Lazy object initialization - Hibernate can use runtime-generated proxies (CGLIB) or interception
injected through byte code instrumentation at build-time
PAGE
11
4. What is Middlegen ?
A-Middlegen is an open source code generation framework that provides a general-purpose databasedriven engine using various tools such as JDBC, Velocity, Ant and XDoclet
PAGE
12
specifically refers to an implementation of a particular form of IOC. Dependency Injection describes the
situation where one object uses a second object to provide a particular capacity. For example, being
passed a database connection as an argument to the constructor method instead of creating one inside the
constructor. The term "Dependency injection" is a misnomer, since it is not a dependency that is
injected; rather it is a provider of some capability or resource that is injected. There are three common
forms of dependency injection: setter, constructor and interface-based injection.
Dependency injection is a way to achieve loose coupling. Inversion of control (IOC) relates to the way
in which an object obtains references to its dependencies. This is often done by a lookup method. The
advantage of inversion of control is that it decouples objects from specific lookup mechanisms and
implementations of the objects it depends on. As a result, more flexibility is obtained for production
applications as well as for testing.
2. What are the different types of dependency injection? Explain with examples.
A-There are two types of dependency injection: setter injection and constructor injection.
Setter Injection: Normally in all the java beans, we will use setter and getter method to set and get the
value of property as follows:
public class namebean {
String name;
public void setName(String a) {
name = a; }
public String getName() {
return name; }
}
We will create an instance of the bean 'namebean' (say bean1) and set property as
bean1.setName("tom"); Here in setter injection, we will set the property 'name' in spring configuration
file as shown below:
< bean id="bean1" class="namebean" >
< property name="name" >
< value > tom < / value >
< / property >
< / bean >
The subelement < value > sets the 'name' property by calling the set method as setName("tom"); This
process is called setter injection.
To set properties that reference other beans , subelement of is used as shown below,
< bean id="bean1" class="bean1impl" >
< property name="game" >
PAGE
13
< ref bean="bean2" / >
< / property >
< / bean >
< bean id="bean2" class="bean2impl" / >
Constructor injection: For constructor injection, we use constructor with parameters as shown below,
public class namebean {
String name;
public namebean(String a) {
name = a;
}
}
We will set the property 'name' while creating an instance of the bean 'namebean' as namebean bean1 =
new namebean("tom");
Here we use the < constructor-arg > element to set the property by constructor injection as
< bean id="bean1" class="namebean" >
< constructor-arg >
< value > My Bean Value < / value >
< / constructor-arg >
< / bean > -
3. What is spring? What are the various parts of spring framework? What are the
different persistence frameworks which could be used with spring ?
A-Spring is an open source framework created to address the complexity of enterprise application
development. One of the chief advantages of the Spring framework is its layered architecture, which
allows you to be selective about which of its components you use while also providing a cohesive
framework for J2EE application development. The Spring modules are built on top of the core container,
which defines how beans are created, configured, and managed. Each of the modules (or components)
that comprise the Spring framework can stand on its own or be implemented jointly with one or more of
the others. The functionality of each component is as follows:
The core container: The core container provides the essential functionality of the Spring framework. A
primary component of the core container is the BeanFactory, an implementation of the Factory pattern.
The BeanFactory applies the Inversion of Control (IOC) pattern to separate an applications
configuration and dependency specification from the actual application code.
Spring context: The Spring context is a configuration file that provides context information to the
Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail,
internalization, validation, and scheduling functionality.
Spring AOP: The Spring AOP module integrates aspect-oriented programming functionality directly
PAGE
14
into the Spring framework, through its configuration management feature. As a result you can easily
AOP-enable any object managed by the Spring framework. The Spring AOP module provides
transaction management services for objects in any Spring-based application. With Spring AOP you can
incorporate declarative transaction management into your applications without relying on EJB
components.
Spring DAO: The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for
managing the exception handling and error messages thrown by different database vendors. The
exception hierarchy simplifies error handling and greatly reduces the amount of exception code you
need to write, such as opening and closing connections. Spring DAOs JDBC-oriented exceptions
comply to its generic DAO exception hierarchy.
Spring ORM: The Spring framework plugs into several ORM frameworks to provide its Object
Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of these comply to Springs
generic transaction and DAO exception hierarchies.
Spring Web module: The Web context module builds on top of the application context module,
providing contexts for Web-based applications. As a result, the Spring framework supports integration
with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding
request parameters to domain objects.
Spring MVC framework: The Model-View-Controller (MVC) framework is a full-featured MVC
implementation for building Web applications. The MVC framework is highly configurable via strategy
interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles, iText, and
POI.
4. What is AOP? How does it relate with IOC? What are different tools to utilize
AOP ?
PAGE
15
Joinpoints: Points in a program's execution. For example, joinpoints could define calls to specific
methods in a class
Pointcuts: Program constructs to designate joinpoints and collect specific context at those points
Advices: Code that runs upon meeting certain conditions. For example, an advice could log a message
before executing a joinpoint.
PAGE
16
PAGE
17
3. what is a collection?
A-Collection is a group of objects.
There are two fundamental types of collections they are Collection and Map.
PAGE
18
Collections just hold a bunch of objects one after the other while Maps hold values in a key-value pair.
Collections Ex: ArrayList, Vector etc.
Map Ex: HashMap, Hashtable etc
PAGE
19
2. How can you minimize the need of garbage collection and make the memory use
more effective?
A-Use object pooling and weak object references. We need to ensure that all objects that are no longer
required in the program are cleared off using finalize() blocks in your code.
4. Does garbage collection guarantee that a program will not run out of memory?
A-Garbage collection does not guarantee that a program will not run out of memory. It is possible for
programs to use up memory resources faster than they are garbage collected. It is also possible for
programs to create objects that are not subject to garbage collection as well. Hence, the Garbage
PAGE
20
Collection mechanism is a "On Best Effort Basis" system where the GC tries to clean up memory as
much as possible to ensure that the system does not run out of memory but it does not guarantee the
same.
PAGE
21
PAGE
22
7. Is null a keyword?
A-No, the null value is not a keyword.
8. Which characters may be used as the second character of an identifier, but not as
the first character of an identifier?
A-The digits 0 through 9 may not be used as the first character of an identifier but they may be used
after the first character of an identifier.
10. What is the difference between the >> and >>> operators?
A-The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted
out.
11. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8
characters?
A-Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits,
it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16
uses 16-bit and larger bit patterns.
PAGE
23
13. What restrictions are placed on the location of a package statement within a
source code file?
A-A package statement must appear as the first line in a source code file (excluding blank lines and
comments). It cannot appear anywhere else in a source code file.
14. What value does readLine() return when it has reached the end of a file?
A-The readLine() method returns null when it has reached the end of a file.
17. What are order of precedence and associativity, and how are they used?
A-Order of precedence determines the order in which operators are evaluated in expressions. Associatity
determines whether an expression is evaluated left-to-right or right-to-left
PAGE
24
20. What is the difference between the Boolean & operator and the && operator?
A-&& is a short-circuit AND operator - i.e., The second condition will be evaluated only if the first
condition is true. If the first condition is true, the system does not waste its time executing the second
condition because, the overall output is going to be false because of the one failed condition.
& operator is a regular AND operator - i.e., Both conditions will be evaluated always.
PAGE
25
PAGE
26
10. What is the difference between the prefix and postfix forms of the ++ operator?
A-The prefix form performs the increment operation and returns the value of the increment operation.
The postfix form returns the current value to the expression and then performs the increment operation
on that value.
PAGE
27
PAGE
28
the whole program
In Object Oriented programming the unit of program is an object which is nothing but combination of
data and code and the data is not exposed outside the object
18. What is a cloneable interface and how many methods does it contain
A-The cloneable interface is used to identify objects that can be cloned using the Object.clone() method.
IT is a Tagged or a Marker Interface and hence it does not have any methods.
THE END
EMAIL SAHILYADAV761@GMAIL.COM
WEBSITE- http://javacodehelps.blogspot.com
Fb page- www.fb.com/javacodehelps