Java Interview Questions -32

Java Interview Questions -32

1.What is a SessionFactory? Is it a thread-safe object?

SessionFactory is Hibernates concept of a single datastore and is threadsafe so that many threads can access it concurrently and request for sessions and immutable
cache of compiled mappings for a single database. A SessionFactory is usually only built once at startup. SessionFactory should be wrapped in some kind of singleton
so that it can be easily accessed in an application code.

2.What does an ORM solution comprises of?

It should have an API for performing basic CRUD (Create, Read, Update, Delete) operations on objects of persistent classes Should have a language or an API for
specifying queries that refer to the classes and the properties of classes An ability for specifying mapping metadata It should have a technique for ORM
implementation to interact with transactional objects to perform dirty checking, lazy association fetching, and other optimization functions

3.What are the different levels of ORM quality?

There are four levels defined for ORM quality.
Pure relational
object mapping
Medium object mapping
Full object mapping

4.What is a pure relational ORM?

The entire application, including the user interface, is designed around the relational model and SQL-based relational operations.

5.Why do you need ORM tools like hibernate?

The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:
>> Improved productivity
* High-level object-oriented API
* Less Java code to write
* No SQL to write
>> Improved performance
* Sophisticated caching
* Eager loading
>> Improved maintainability
* A lot less code to write
>> Improved portability
* ORM framework generates database-specific SQL for you

6.What is a meant by light object mapping?

The entities are represented as classes that are mapped manually to the relational tables. The code is hidden from the business logic using specific design patterns.
This approach is successful for applications with a less number of entities, or applications with common, metadata-driven data models. This approach is most known
to all.

7.What is Hibernate?

Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using
(XML) configuration files.Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.

8.What is a meant by medium object mapping?

The application is designed around an object model. The SQL code is generated at build time. And the associations between objects are supported by the persistence
mechanism, and queries are specified using an object-oriented expression language. This is best suited for medium-sized applications with some complex
transactions. Used when the mapping exceeds 25 different database products at a time.

9.What is meant by full object mapping?

Full object mapping supports sophisticated object modeling: composition, inheritance, polymorphism and persistence. The persistence layer implements transparent
persistence; persistent classes do not inherit any special base class or have to implement a special interface. Efficient fetching strategies and caching strategies are
implemented transparently to the application.

10.What are the benefits of ORM and Hibernate?

There are many benefits from these. Out of which the following are the most important one.
Productivity : Hibernate reduces the burden of developer by providing much of the functionality and let the developer to concentrate on business logic.
Maintainability :As hibernate provides most of the functionality, the LOC for the application will be reduced and it is easy to maintain. By automated object/relational persistence it even reduces the LOC.
Performance : Hand-coded persistence provided greater performance than automated one. But this is not true all the times. But in hibernate, it provides more
optimization that works all the time there by increasing the performance. If it is automated persistence then it still increases the performance.
Vendor independence : Irrespective of the different types of databases that are there, hibernate provides a much easier way to develop a cross platform application.

11.What the Core interfaces are of hibernate framework?

There are many benefits from these. Out of which the following are the most important one.
Session Interface : This is the primary interface used by hibernate applications. The instances of this interface are lightweight and are inexpensive to create and destroy. Hibernate sessions are not thread safe.
SessionFactory Interface : This is a factory that delivers the session objects to hibernate application. Generally there will be a single SessionFactory for the whole application and it will be shared among all the application threads.
Configuration Interface : This interface is used to configure and bootstrap hibernate. The instance of this interface is used by the application in order to specify the location of hibernate specific mapping documents.
Transaction Interface : This is an optional interface but the above three interfaces are mandatory in each and every application. This interface abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction.
Query and Criteria Interface : This interface allows the user to perform queries and also control the flow of the query execution.

12.What are Callback interfaces?

These interfaces are used in the application to receive a notification when some object events occur. Like when an object is loaded, saved or deleted. There is no need
to implement callbacks in hibernate applications, but they're useful for implementing certain kinds of generic functionality.

13.What should SessionFactory be placed so that it can be easily accessed?

As far as it is compared to J2EE environment, if the SessionFactory is placed in JNDI then it can be easily accessed and shared between different threads and various
components that are hibernate aware. You can set the SessionFactory to a JNDI by configuring a property hibernate.session_factory_name in the

14.What are POJOs?

POJO stands for plain old java objects. These are just basic JavaBeans that have defined setter and getter methods for all the properties that are there in that bean.
Besides they can also have some business logic related to that property. Hibernate applications works efficiently with POJOs rather then simple java classes.

15.What is object/relational mapping metadata?

ORM tools require a metadata format for the application to specify the mapping between classes and tables, properties and columns, associations and foreign keys,
Java types and SQL types. This information is called the object/relational mapping metadata. It defines the transformation between the different data type systems and
relationship representations.

16.What is HQL?

HQL stands for Hibernate Query Language. Hibernate allows the user to express queries in its own portable SQL extension and this is called as HQL. It also allows
the user to express in native SQL.

17.What are the most common methods of Hibernate configuration?

The most common methods of Hibernate configuration are:
* Programmatic configuration
* XML configuration (hibernate.cfg.xml)

18.What are the important tags of hibernate.cfg.xml?

An Action Class is an adapter between the contents of an incoming HTTP rest and the corresponding business logic that should be executed to process this rest.

19.What are the Core interfaces are of Hibernate framework?

People who read this also read:
The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control
* Session interface
* SessionFactory interface
* Configuration interface
* Transaction interface
* Query and Criteria interfaces

20.What is ORM?

ORM stands for Object/Relational mapping. It is the programmed and translucent perseverance of objects in a Java application in to the tables of a relational database
using the metadata that describes the mapping between the objects and the database. It works by transforming the data from one representation to another.

21.What role does the Session interface play in Hibernate?

The Session interface is the primary interface used by Hibernate applications. It is a single-threaded, short-lived object representing a conversation between the
application and the persistent store. It allows you to create query objects to retrieve persistent objects.
Session session = sessionFactory.openSession();
Session interface role:

22.Hibernate Interview Questions And Answers
* Wraps a JDBC connection
* Factory for Transaction
* Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier

23.What role does the SessionFactory interface play in Hibernate?

The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole application—created during
application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data
that has been read in one unit of work and may be reused in a future unit of work
SessionFactory sessionFactory = configuration.buildSessionFactory();

24.What is Hibernate Query Language (HQL)?

Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language,
the Hibernate query Language (HQL), is an object-oriented extension to SQL.

25.How do you map Java Objects with Database tables?

* First we need to write Java domain objects (beans with setter and getter). The variables should be same as database columns.
* Write hbm.xml, where we map java class to table and database columns to Java class variables.
Example :
<class name=&#8221;com.test.User&#8221;  table=&#8221;user&#8221;>
<property  column=&#8221;USER_NAME&#8221; length=&#8221;255&#8243;
name=&#8221;userName&#8221; not-null=&#8221;true&#8221;  type=&#8221;java.lang.String&#8221;/>
<property  column=&#8221;USER_PASSWORD&#8221; length=&#8221;255&#8243;
name=&#8221;userPassword&#8221; not-null=&#8221;true&#8221;  type=&#8221;java.lang.String&#8221;/>

26.What Does Hibernate Simplify?

Hibernate simplifies:
* Saving and retrieving your domain objects
* Making database column and table name changes
* Centralizing pre save and post retrieve logic
* Complex joins for retrieving related items
* Schema creation from object model

27.What is the difference between load() and get()?

load() vs. get()
load() Only use the load() method if you are sure that the object exists.
load() method will throw an exception if the unique id is not found in the database.load() just returns a proxy by default and database won&#8217;t be hit until
the proxy is first invoked.
If you are not sure that the object exists, then use one of the get() methods.
get() method will return null if the unique id is not found in the database.
get() will hit the database immediately.

28.What is the general flow of Hibernate communication with RDBMS?

The general flow of Hibernate communication with RDBMS is :
* Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files
* Create session factory from configuration object
* Get one session from this session factory
* Create HQL Query
* Execute query to get list containing Java objects

29.What is the difference between and merge and update?

Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your
modifications at any time without consideration of the state of the session.

30.How do you define sequence generated primary key in hibernate?

Using <generator> tag.
<id column=&#8221;USER_ID&#8221; name=&#8221;id&#8221; type=&#8221;java.lang.Long&#8221;>
<generator class=&#8221;sequence&#8221;>
<param name=&#8221;table&#8221;>SEQUENCE_NAME</param>

31.Define cascade and inverse option in one-many mapping?

cascade - enable operations to cascade to child entities.
inverse - mark this collection as the &#8220;inverse&#8221; end of a bidirectional association.
Essentially &#8220;inverse&#8221; indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you
ask the parent for its list of children, or ask the children who the parents are?

32.What does it mean to be inverse?

It informs hibernate to ignore that end of the relationship. If the one-to-many was marked as inverse, hibernate would create a child->parent relationship
(child.getParent). If the one-to-many was marked as non-inverse then a child->parent relationship would be created.

33.What do you mean by Named - SQL query?

Named SQL queries are defined in the mapping xml document and called wherever required.
<sql-query name = &#8220;empdetails&#8221;>
<return alias=&#8221;emp&#8221; class=&#8221;com.test.Employee&#8221;/>
SELECT emp.EMP_ID AS {emp.empid},
emp.EMP_ADDRESS AS {emp.address},
emp.EMP_NAME AS {}
FROM Employee EMP WHERE emp.NAME LIKE :name
Invoke Named Query :
List people = session.getNamedQuery(&#8221;empdetails&#8221;)
.setString(&#8221;TomBrady&#8221;, name)

34.How do you invoke Stored Procedures?

<sql-query name=&#8221;selectAllEmployees_SP&#8221; callable=&#8221;true&#8221;>
<return alias=&#8221;emp&#8221; class=&#8221;employee&#8221;>
<return-property name=&#8221;empid&#8221; column=&#8221;EMP_ID&#8221;/>
<return-property name=&#8221;name&#8221; column=&#8221;EMP_NAME&#8221;/>
<return-property name=&#8221;address&#8221; column=&#8221;EMP_ADDRESS&#8221;/>
{ ? = call selectAllEmployees() }

35.Explain Criteria API?

Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like &#8220;search&#8221;
screens where there is a variable number of conditions to be placed upon the result set.
Example :
List employees = session.createCriteria(Employee.class)
.add(;name&#8221;, &#8220;a%&#8221;) )
.add(;address&#8221;, &#8220;Boston&#8221;))
.addOrder(Order.asc(&#8221;name&#8221;) )

36.Define HibernateTemplate?

org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also
converts checked HibernateExceptions into unchecked DataAccessExceptions.

37.What are the benefits does HibernateTemplate provide?

The benefits of HibernateTemplate are :
* HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.
* Common functions are simplified to single method calls.
* Sessions are automatically closed.
* Exceptions are automatically caught and converted to runtime exceptions.

38.How do you switch between relational databases without code changes?

Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.

39.If you want to see the Hibernate generated SQL statements on console, what should we do?

In Hibernate configuration file set as follows:
<property name=&#8221;show_sql&#8221;>true</property>

40.What are derived properties?

The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined
using the formula attribute of the element.
People who read this also read:
Core Java Questions
Spring Questions
SCJP 6.0 Certification
EJB Interview Questions
Servlets Questions

41.What is component mapping in Hibernate?

* A component is an object saved as a value, not as a reference
* A component can be saved directly without needing to declare interfaces or identifier properties
* Required to define an empty constructor
* Shared references not supported

42.What is the difference between sorted and ordered collection in hibernate?

sorted collection vs. order collection
sorted collection :-A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. The sorting occurs in the memory of JVM
which running Hibernate, after the data being read from database using java comparator.If your collection is not large, it will be more efficient way to sort it.
order collection :-Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.If your collection is very large, it will be more efficient way to sort it .

43.How will you configure Hibernate?

The configuration files hibernate.cfg.xml (or and mapping files *.hbm.xml are used by the Configuration class to create (i.e. configure and
bootstrap hibernate) the SessionFactory, which in turn creates the Session instances. Session instances are the primary interface for the persistence service.
" hibernate.cfg.xml (alternatively can use These two files are used to configure the hibernate sevice (connection driver class, connection URL,
connection username, connection password, dialect etc). If both files are present in the classpath then hibernate.cfg.xml file overrides the settings found in the file.
" Mapping files (*.hbm.xml): These files are used to map persistent objects to a relational database. It is the best practice to store each object in an individual mapping
file (i.e mapping file per class) because storing large number of persistent classes into one mapping file can be difficult to manage and maintain. The naming
convention is to use the same name as the persistent (POJO) class name. For example Account.class will have a mapping file named Account.hbm.xml. Alternatively
hibernate annotations can be used as part of your persistent class code instead of the *.hbm.xml files.

44.What is a Session? Can you share a session object between different theads?

Session is a light weight and a non-threadsafe object (No, you cannot share it between threads) that represents a single unit-of-work with the database. Sessions are
opened by a SessionFactory and then are closed when all work is complete. Session is the primary interface for the persistence service. A session obtains a database
connection lazily (i.e. only when required). To avoid creating too many sessions ThreadLocal class can be used as shown below to get the current session no matter
how many times you make call to the currentSession() method.

45.What are the benefits of detached objects?

Detached objects can be passed across layers all the way up to the presentation layer without having to use any DTOs (Data Transfer Objects). You can later on
re-attach the detached objects to another session.

46.What are the pros and cons of detached objects?

" When long transactions are required due to user think-time, it is the best practice to break the long transaction up into two or more transactions. You can use
detached objects from the first transaction to carry data all the way up to the presentation layer. These detached objects get modified outside a transaction and later on
" In general, working with detached objects is quite cumbersome, and better to not clutter up the session with them if possible. It is better to discard them and re-fetch
them on subsequent requests. This approach is not only more portable but also more efficient because - the objects hang around in Hibernate's cache anyway.
" Also from pure rich domain driven design perspective it is recommended to use DTOs (DataTransferObjects) and DOs (DomainObjects) to maintain the separation
between Service and UI tiers.

47.How does Hibernate distinguish between transient (i.e. newly instantiated) and detached objects?

" Hibernate uses the version property, if there is one.
" If not uses the identifier value. No identifier value means a new object. This does work only for Hibernate managed surrogate keys. Does not work for natural keys
and assigned (i.e. not managed by Hibernate) surrogate keys.
" Write your own strategy with Interceptor.isUnsaved().

48.What is the difference between the session.get() method and the session.load() method?

Both the session.get(..) and session.load() methods create a persistent object by loading the required object from the database. But if there was not such object in the
database then the method session.load(..) throws an exception whereas session.get(&) returns null.

49.What is the difference between the session.update() method and the session.lock() method?

Both of these methods and saveOrUpdate() method are intended for reattaching a detached object. The session.lock() method simply reattaches the object to the
session without checking or updating the database on the assumption that the database in sync with the detached object. It is the best practice to use either
session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it
does not matter because you will be overwriting all the columns that would have changed later on within the same transaction.

50.How would you reatach detached objects to a session when the same object has already been loaded into the session?

You can use the session.merge() method call.

51.What are the general considerations or best practices for defining your Hibernate persistent classes?

1.You must have a default no-argument constructor for your persistent classes and there should be getXXX() (i.e accessor/getter) and setXXX( i.e. mutator/setter)
methods for all your persistable instance variables.
2.You should implement the equals() and hashCode() methods based on your business key and it is important not to use the id field in your equals() and hashCode()
definition if the id field is a surrogate key (i.e. Hibernate managed identifier). This is because the Hibernate only generates and sets the field when saving the object.
3. It is recommended to implement the Serializable interface. This is potentially useful if you want to migrate around a multi-processor cluster.
4.The persistent class should not be final because if it is final then lazy loading cannot be used by creating proxy objects.
5.Use XDoclet tags for generating your *.hbm.xml files or Annotations (JDK 1.5 onwards), which are less verbose than *.hbm.xml files.

52.What does ORM consists of?

An ORM solution consists of the followig four pieces:
* API for performing basic CRUD operations
* API to express queries refering to classes
* Facilities to specify metadata
* Optimization facilities : dirty checking,lazy associations fetching

53.What are the ORM level?

The ORM levels are:
* Pure relational (stored procedure.)
* Light objects mapping (JDBC)
* Medium object mapping
* Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)

54.can you explain What is JSP page life cycle?
When first time a JSP page is request necessary servlet code is generated and loaded in the servlet container. Now until the JSP page is not changed the compiled servlet code serves any request which comes from the browser. When you again change the JSP page the JSP engine again compiles a servlet code for the same.
JSP page is first initialized by jspInit() method. This initializes the JSP in much the same way as servlets are initialized, when the first request is intercepted and just after translation.
Every time a request comes to the JSP, the container generated _jspService() method is invoked, the request is processed, and response generated.
When the JSP is destroyed by the server, the jspDestroy() method is called and this can be used for clean up purposes.
55.What is EL ?

EL stands for expression language. An expression language makes it possible to easily access application data.In the below expression amountofwine variable value will be rendered. There are ${amount} litres of milk in the bottle. does EL search for an attribute ?
EL parser searches the attribute in following order:
Session (if it exists)
If no match is found for then it displays empty string.
57.What are the implicit EL objects in JSP ?
Following are the implicit EL objects:-
PageContext: The context for the JSP page.
servletContext: The context for the JSP page's servlet and any web components contained n the same application.
ession: The session object for the client.
equest: The request triggering the execution of the JSP page.
esponse: The response returned by the JSP page. See Constructing Responses.And addition, several implicit objects are available that allow easy access to the following objects:
param: Maps a request parameter name to a single value.
paramValues: Maps a request parameter name to an array of values.
header: Maps a request header name to a single value.
headerValues: Maps a request header name to an array of values.
cookie: Maps a cookie name to a single cookie.
initParam: Maps a context initialization parameter name to a single value Finally, there are objects that allow access to the various scoped variables described in Using Scope Objects.
pageScope: Maps page-scoped variable names to their values
requestScope: Maps request-scoped variable names to their values.
sessionScope: Maps session-scoped variable names to their values.
applicationScope: Maps application-scoped variable names to their values.
Browser: ${header["user-agent"]}
58.How can we disable EL ?

We can disable using isELIgnored attribute of the page directive:
<%@ page isELIgnored ="true|false" %> .
59.what is JSTL ?
JSTL is also called as JSP tag libraries. They are collection of custom actions which can be accessed as JSP tags.
60.what the different types of JSTL tags are ?
Tags are classified in to four groups:-
Core tags
Formatting tags
XML tags
SQL tags
61.How can we use beans in JSP?
JSP provides three tags to work with beans:-
< jsp:useBean id=“bean name” class=“bean class” scope = “page | request | session |application ”/>
Bean name = the name that refers to the bean. Bean class = name of the java class that defines the bean.
< jsp:setProperty name = “id” property = “someProperty” value = “someValue” / > id = the name of the bean as specified in the useBean tag. property = name of the property to be passed to the bean. value = value of that particular property .
< jsp:getProperty name = “id” property = “someProperty” />
Here the property is the name of the property whose value is to be obtained from the bean.Below is a code snippet which shows how MyUserClass is used and the values accessed.
< jsp:useBean id="user" class="MyUserClass" scope="session"/>
You entered< BR>
Name: <%= user.getUsername() %>< BR>
Email: <%= user.getEmail() %>< BR>

62.What is the use of ?
It includes the output of one JSP in to other JSP file at the location of the tag. Below is the syntax for the same:-
< jsp:include page="..some.url.." flush="true or false"/>-
page: A URL that is relative to the current JSP page at request time-
flush: Determines if the buffer for the output is flushed immediately, before the included page's output.
63.What is < jsp:forward> tag for ?
It forwards the current request to another JSP page. Below is the syntax for the same:-
< jsp:forward page="...url..." />
We can also forward parameter to the other page using the param tag
< jsp:forward page="..url...">
< jsp:param ..../>

64.What are JSP directives ?

JSP directives do not produce any output. They are used to set global values like class declaration, content type etc. Directives have scope for entire JSP file. They start with <%@ and ends with %>. There are three main directives that can be used in JSP:-
page directive
include directive
taglib directive
65.How do we prevent browser from caching output of my JSP pages?
WE can prevent pages from caching JSP pages output using the below code snippet. <%response.setHeader("Cache-Control","no-cache"); //HTTP 1.1 response.setHeader("Pragma","no-cache"); //HTTP 1.0 response.setDateHeader ("Expires", 0); //prevents caching at the proxy server %>
66.How did you implement caching in JSP?
OSCache is an open-source caching library that's available free of charge from the OpenSymphony organization . OSCache has a set of JSP tags that make it easy to implement page caching in your JSP application.
Following are some Cache techniques it fulfills:-
Cache entry:
An object that's stored into a page cache is known as a cache entry. In a JSP application, a cache entry is typically the output of a JSP page, a portion of a JSP page, or a servlet.
Cache key:
A page cache is like a hash table. When you save a cache entry in a page cache, you must provide a cache key to identify the cache data. You can use keys like URI, other parameters like username, ipaddress to indentify cache data.
Cache duration:
This is the period of time that a cache entry will remain in a page cache before it expires. When a cache entry expires, it's removed from the cache and will be regenerated again.
Cache scope:
This defines at what scope the data is stored application or session scope. <%= new java.util.Date().toString() %>
The above tag says that refresh after every 60 seconds the user requests data. So if user1 s requesting the page it will display fresh date and if an other user requests with in 60 seconds it will show same data. If any other user requests the page after 60 second he will again see refreshed date.
67.what are Page directives?
Page directive is used to define page attributes the JSP file. Below is a sample of the same:- <% @ page language="Java" import="java.rmi.*,java.util.*" session="true" buffer="12kb" autoFlush="true" errorPage="error.jsp" %>
To summarize some of the important page attributes:-
import :- Comma separated list of packages or classes, just like import statements in usual Java code.
session :- Specifies whether this page can use HTTP session. If set "true" session (which refers to the javax.servlet.http.HttpSession) is available and can be used to access the current/new session for the page. If "false", the page does not participate in a session and the implicit session object is unavailable.
buffer :- If a buffer size is specified (such as "50kb") then output is buffered with a buffer size not less than that value.
isThreadSafe :- Defines the level of thread safety implemented in the page. If set "true" the JSP engine may send multiple client requests to the page at the same time. If "false" then the JSP engine queues up client requests sent to the page for processing, and processes them one request at a time, in the order they were received. This is the same as implementing the javax.servlet.SingleThreadModel interface in a servlet.
rrorPage: - Defines a URL to another JSP page, which is invoked if an unchecked runtime exception is thrown. The page implementation catches the instance of the Throwable object and passes it to the error page processing.
68.How does JSP engines instantiate tag handler classes instances?
JSP engines will always instantiate a new tag handler instance every time a tag is encountered in a JSP page. A pool of tag instances are maintained and reusing them where possible. When a tag is encountered, the JSP engine will try to find a Tag instance that is not being used and use the same and then release it.
69.what’s the difference between JavaBeans and taglib directives?
JavaBeans and taglib fundamentals were introduced for reusability. But following are the major differences between them.Taglib are for generating presentation elements while JavaBeans are good for storing information and state.
Use custom tags to implement actions and JavaBeans to present information.
70.what are the different scopes an object can have in a JSP page?

There are four scope which an object can have in a JSP page:-

Objects with page scope are accessible only within the page. Data only is valid for the current response. Once the response is sent back to the browser then data is no more valid. Even if request is passed from one page to other the data is lost. Request Scope
Objects with request scope are accessible from pages processing the same request in which they were created. Once the container has processed the request data is invalid. Even if the request is forwarded to another page, the data is still available though not if a redirect is required. Session Scope
Objects with session scope are accessible in same session. Session is the time users spend using the application, which ends when they close their browser or when they go to another Web site. So, for example, when users log in, their username could be stored in the session and displayed on every page they access. This data lasts until they leave the Web site or log out. Application Scope
Application scope objects are basically global object and accessible to all JSP pages which lie in the same application. This creates a global object that's available to all pages. Application scope variables are typically created and populated when an application starts and then used as read-only for the rest of the application.
71.what are different implicit objects of JSP?
Below are different implicit objects of JSP
pageContext :- The PageContext object.
pageScope :- A Map of all the objects that have page scope.
requestScope :- A Map of all the objects that have request scope.
sessionScope :- A Map of all the objects that have session scope.
applicationScope :- A Map of all the objects that have application scope.
param :- A Map of all the form parameters that were passed to your JSP page (for example, the HTML < input name="someName" type="text"/> is passed to your JSP page as a form parameter).
paramValues :- HTML allows for multiple values for a single form parameter. This is a Map of all the parameters, just like param, but in this object the values are an array containing all of the values for a given parameter in the event that there's more than one.
header :- A Map of all the request headers.
headerValues :- For the same reasons as paramValues, a headerValues object is provided.
cookie :- A Map of all the cookies passed to your JSP. The value returned is a Cookie object.
initParam :- A Map that maps context initialization parameter names to their parameter values.

72.What are wrapper classes?

Java provides specialized classes corresponding to each of the primitive data types. These are called wrapper classes. They are e.g. Integer, Character, Double etc.

73.Why do we need wrapper classes?

It is sometimes easier to deal with primitives as objects. Moreover most of the collection classes store objects and not primitive data types. And also the
wrapper classes provide many utility methods also. Because of these resons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass
them around as a collection. Also we can pass them around as method parameters where a method expects an object.

74.What are checked exceptions?

A:Checked exception are those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions.

75.What are runtime exceptions?

Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time

76.Is it necessary that each try block must be followed by a catch block?

It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever
exceptions are likely to be thrown should be declared in the throws clause of the method.

77.If I write return at the end of the try block, will the finally block still execute?

Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and
then the control return.

78.If I write System.exit (0); at the end of the try block, will the finally block still execute?

No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes.

79.What restrictions are placed on method overriding?

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

80. How can a dead thread be restarted?

A dead thread cannot be restarted.

81. What happens if an exception is not caught?

An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup beinginvoked, which eventually results in the termination of the program in which it is thrown.

82. What is a layout manager?

A layout manager is an object that is used to organize components in a container.

83. Which arithmetic operations can result in the throwing of an ArithmeticException?

Integer / and % can result in the throwing of an ArithmeticException.

84. What are three ways in which a thread can enter the waiting state?

A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfullyattempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter thewaiting state by invoking its (deprecated) suspend() method.

85. Can an abstract class be final?

An abstract class may not be declared as final.

86. What is the ResourceBundle class?

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

87. What happens if a try-catch-finally statement does not have a catch clause to handle anexception that is thrown within the body of the try statement?

The exception propagates up to the next higher level try-catch statement (if any) or results in the program'stermination.

88. What is numeric promotion?

Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer andfloating-point operations may take place. In numerical promotion, byte, char, and short values areconverted to int values. The int values are also converted to long values, if necessary. The long and floatvalues are converted to double values, as required.

89. What is the difference between a Scrollbar and a ScrollPane?
A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles itsown events and performs its own scrolling.

90. What is the difference between a public and a non-public class?

A public class may be accessed outside of its package. A non-public class may not be accessed outside of its package.

91. To what value is a variable of the boolean type automatically initialized?

The default value of the boolean type is false.

92. Can try statements be nested?

Try statements may be tested.

93. What is the difference between the prefix and postfix forms of the ++ operator?

The prefix form performs the increment operation and returns the value of the increment operation. Thepostfix form returns the current value all of the expression and then performs the increment operation onthat value.

94. What is the purpose of a statement block?

A statement block is used to organize a sequence of statements as a single statement group.

95. What is a Java package and how is it used?

A Java package is a naming context for classes and interfaces. A package is used to create a separate namespace for groups of classes and interfaces. Packages are also used to organize related classes and interfacesinto a single API unit and to control accessibility to these classes and interfaces.

96. What modifiers may be used with a top-level class?

A top-level class may be public, abstract, or final.

97. 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 representthe classes and interfaces that are loaded by a Java program.

98. How does a try statement determine which catch clause should be used to handle an exception?

when an exception is thrown within the body of a try statement, the catch clauses of the try statement areexamined in the order in which they appear. The first catch clause that is capable of handling the exceptionis executed. The remaining catch clauses are ignored.

99. Can an unreachable object become reachable again?

An unreachable object may become reachable again. This can happen when the object's finalize() method isinvoked and the object performs an operation which causes it to become accessible to reachable objects.

100. When is an object subject to garbage collection?

An object is subject to garbage collection when it becomes unreachable to the program in which it is used.

101. What method must be implemented by all threads?

All tasks must implement the run() method, whether they are a subclass of Thread or implement theRunnable interface.

102. What methods are used to get and set the text label displayed by a Button object?

getLabel() and setLabel()

103. What are synchronized methods and synchronized statements?

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

104. What are the two basic ways in which classes that can be run as threads may be defined?

A thread class may be declared as a subclass of Thread, or it may implement the Runnable interface.

105. What are the problems faced by Java programmers who don't use layout managers?

Without layout managers, Java programmers are faced with determining how their GUI will be displayedacross multiple windowing systems and finding a common sizing and positioning that will work within theconstraints imposed by each windowing system.

106. What is the difference between an if statement and a switch statement?

The if statement is used to select among two alternatives. It uses a boolean expression to decide whichalternative should be executed. The switch statement is used to select among multiple alternatives. It usesan int expression to determine which alternative should be executed.

107. What is the List interface?

The List interface provides support for ordered collections of objects

Also Read:



Post a Comment