Java

Java Interview Questions -37

Because servlets are platform-independent Java classes that are compiled to platform-neutral byte code that can be loaded dynamically into and run by a Java technology-enabled Web server.

2.What is servlet container?

The servlet container is a part of a Web server or application server that provides the network services over which requests and responses are sent, decodes MIME-based requests, and formats MIME-based responses. A servlet container also contains and manages servlets through their lifecycle.

3.What is Java Servlet?

A servlet is a Java technology-based Web component, managed by a container called servlet container or servlet engine, that generates dynamic content and interacts with web clients via a request/response paradigm.

4.If a servlet is not properly initialized, what exception may be thrown?
During initialization or service of a request, the servlet instance can throw an UnavailableException or a ServletException.

5. What is filter? Can filter be used as request or response?
A filter is a reusable piece of code that can transform the content of HTTP requests,responses, and header information. Filters do not generally create a response or respond to a request as servlets do, rather they modify or adapt the requests for a resource, and modify or adapt responses from a resource.

6.When a client request is sent to the servlet container, how does the container choose which servlet to invoke?
The servlet container determines which servlet to invoke based on the configuration of its servlets, and calls it with objects representing the request and response.

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

ServeltRequest: which encapsulates the communication from the client to the server.
ServletResponse: which encapsulates the communication from the servlet back to the client.
ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.

8.When using servlets to build the HTML, you build a DOCTYPE line, why do you do that?

I know all major browsers ignore it even though the HTML 3.2 and 4.0 specifications require it. But building a DOCTYPE line tells HTML validators which version of HTML you are using so they know which specification to check your document against. These validators are valuable debugging services, helping you catch HTML syntax errors.

9.What is new in ServletRequest interface?(Servlet 2.4)
The following methods have been added to ServletRequest 2.4 version:
public int getRemotePort()
public java.lang.String getLocalName()
public java.lang.String getLocalAddr()
public int getLocalPort()

10.The code in a finally clause will never fail to execute, right?
Using System.exit(1); in try block will not allow finally code to execute.

11.How can I send user authentication information while makingURLConnection?

You’ll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.

12.Request parameter How to find whether a parameter exists in the request object?

13.How can a servlet refresh automatically if some new data has entered the database?

You can use a client-side Refresh or Server Push

14.What is Java Servlet session?

The session is an object used by a servlet to track a user’s interaction with a Web application across multiple HTTP requests.

15.What is servlet mapping?

The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to servlets.

16.What is servlet context ?

The servlet context is an object that contains a servlet’s view of the Web application within which the servlet is running. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use. (answer supplied by Sun’s tutorial).

17.What mechanisms are used by a Servlet Container to maintain session information?

Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information

18.Difference between GET and POST in Java Servlets?

In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 260 characters, not secure, faster, quick and easy.
In POST Your name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the form’s output. It is used to send a chunk of data to the server to be processed, more versatile, most secure.

19.Can we use the constructor, instead of init(), to initialize servlet?

Yes , of course you can use the constructor instead of init(). There’s nothing to stop you. But you shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.

20.What’s the difference between constructors and other methods?
Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.

21.What is the output of x > y? a:b = p*q when x=1,y=2,p=3,q=4?
When this kind of question has been asked, find the problems you think is necessary to ask back before you give an answer. Ask if variables a and b have been declared or initialized. If the answer is yes. You can say that the syntax is wrong. If the statement is rewritten as: x

22.What is the difference between shallow copy and deep copy?
Shallow copy shares the same reference with the original object like cloning, whereas the deep copy get a duplicate instance of the original object. If the shallow copy has been changed, the original object will be reflected and vice versa.

23.Can one create a method which gets a String and modifies it?
No. In Java, Strings are constant or immutable; their values cannot be changed after they are created, but they can be shared. Once you change a string, you actually create a new object. For example:
String s = “abc”; //create a new String object representing “abc”
s = s.toUpperCase(); //create another object representing “ABC”

24.Why is multiple inheritance not possible in Java?
It depends on how you understand “inheritance”. Java can only “extends” one super class, but can “implements” many interfaces; that doesn’t mean the multiple inheritance is not possible. You may use interfaces to make inheritance work for you. Or you may need to work around. For example, if you cannot get a feature from a class because your class has a super class already, you may get that class’s feature by declaring it as a member field or getting an instance of that class. So the answer is that multiple inheritance in Java is possible.

24.What is the difference between Swing and AWT components?
AWT components are heavy-weight, whereas Swing components are lightweight. Heavy weight components depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button.

26.Why Java does not support pointers?
Because pointers are unsafe. Java uses reference types to hide pointers and programmers feel easier to deal with reference types without pointers. This is why Java and C-sharp shine.

27.What is the relationship between synchronized and volatile keyword?
The JVM is guaranteed to treat reads and writes of data of 32 bits or less as atomic.(Some JVM might treat reads and writes of data of 64 bits or less as atomic in future) For long or double variable, programmers should take care in multi-threading environment. Either put these variables in a synchronized method or block, or declare them volatile.

JavaServer Faces (JSF) is a user interface (UI) designing framework for Java web applications. JSF provide a set of reusable UI components, standard for web applications.JSF is based on MVC design pattern. It automatically saves the form data to server and populates the form date when display at client side.

30. Define Hash table

HashTable is just like Hash Map,Collection having key(Unique),value pairs. Hashtable is a collection Synchronozed object .It does not allow duplicate values but it allows null values.

31.What is Hibernate?

Hibernate is a open source object-relational mapping and query service. In hibernate we can write HQL instead of SQL which save developers to spend more time on writing the native SQL. Hibernate has more powerful association, inheritance, polymorphism, composition, and collections. It is a beautiful approach for persisting into database using the java objects. Hibernate also allows you to express queries using java-based criteria .

32. What is the limitation of hibernate?

Slower in executing the queries than queries are used directly.
Only query language support for composite keys.
No shared references to value types.

ORM stands for Object-Relational mapping. The objects in a Java class which is mapped 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.

35.Difference between save and saveorupdate

save() – This method in hibernate is used to stores an object into the database. It insert an entry if the record doesn’t exist, otherwise not.
saveorupdate () -This method in the hibernate is used for updating the object using identifier. If the identifier is missing this method calls save(). If the identifier exists, it will call update method.

36.Difference between load and get method?

load() can’t find the object from cache or database, an exception is thrown and the load() method never returns null.
get() method returns null if the object can’t be found. The load() method may return a proxy instead of a real persistent instance get() never returns a proxy.

Pojo based programming enables reuse component.
Improve productivity and subsequently reduce development cost.
Dependency Injection can be used to improve testability.
Spring required enterprise services without a need of expensive application server.
It reduces coupling in code and improves maintainability.

41.What are the Benefits Spring Framework ?

Light weight container
Spring can effectively organize your middle tier objects
Initialization of properties is easy ? no need to read from properties file
application code is much easier to unit test
Objects are created Lazily , Singleton – configuration
Spring’s configuration management services can be used in any architectural layer, in whatever runtime environment

42.How to Create Object without using the keyword “new” in java?

Without new the Factory mehtods are used to create objects for a class. For example
Calender c=Calender.getInstance();
here Calender is a class and the method getInstance() is a Factory method which can create object for Calender class.

43. What is servlet?

Servlets is a server side components that provide a powerful mechanism for developing server side programs. Servlets is a server as well as platform-independent and Servlets are designed for a various protocols. Most commonly used HTTP protocols. Servlets uses the classes in the java packages javax.servlet, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, javax.servlet.http.HttpSession;. All servlets must implement the Servlet interface, which defines life-cycle methods.

44.Servlet is pure java object or not?

Yes, pure java object.

45.What are the phases of the servlet life cycle?

The life cycle of a servlet consists of the following phases:
1.Servlet class loading
2.Servlet instantiation
3.the init method
4.Request handling (call the service method)
5.Removal from service (call the destroy method)

46.What must be implemented by all Servlets?

The Servlet Interface must be implemented by all servlets.

47.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å¹¼reated 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();

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

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

50.What is ORM ?

ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database.

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.

55. What’s the difference between validation.xml and validator-rules.xml files in Struts Validation framework?

In Validation.xml, we define validation rules for any specific Java bean while in validator-rules.xml file, standard and generic validation rules are defined.

56. How can we display all validation errors to user on JSP page?

To display all validation errors based on the validation rules defined in validation.xml file, we use <html:errors /> tag in our JSP file.

57. What’s the difference between Jakarta Struts and Apache Struts? Which one is better to use?

Both are same and there is no difference between them.

58.Why do you need both GET and POST method implementations in Servlet?

A single servlet can be called from differenr HTML pages,so Different method calls can be possible.

59.When init() and Distroy() will be called.

init() is called whenever the servlet is loaded for the first time into the webserver.Destroy will be called whenever the servlet is removed from the webserver.

60.What is the uses Sessions ?

Its a part of the SessionTracking and it is for mainting the client state at server side.

61.What is the advantage of Servlets over other serverside technologies.

PlatForm independent, so once compiled can be used in any webserver.For different processes different threads will execute inbuilt mutithreaded.

62.What is the use of setComment and getComment methods in Cookies ?

setComment:If a user agent (web browser) presents this cookie to a user, the cookie’s purpose
will be described using this comment. This is not supported by version zero cookies.
public void setComment(String use)
{}
getComment:Returns the comment describing the purpose of this cookie, or null if no such comment has been defined.

63.What is clipping?

Clipping is the process of confining paint operations to a limited area or shape.

64. What is a native method?

A native method is a method that is implemented in a language other than Java.

65. To what value is a variable of the String type automatically initialized?

The default value of an String type is null.

66. What is a task’s priority and how is it used in scheduling?

A task’s priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks.

67. Can an anonymous class be declared as implementing an interface and extending a class?

An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

68. What is the catch or declare rule for method declarations?

If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.

69. What is the difference between a MenuItem and a CheckboxMenuItem?

The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked.

70.Explain how Struts control data flow?

Struts frame work implements MVC pattern through the use of ActionForward and ActionMapping to keep control –flow decision out of presentation layer. That is in struts-config.xml file.

71.Which Part of MVC Struts represent?

Mostly Action controller(ActionServlet) is used in MVC. Struts strictly fallow MVC to separate business logic with presentation logic(JSP).

72.What is the difference between ActionForm and DynaActionForm?

To get the data from user entered text fields we use Form bean concept in Struts. While using form bean, you need to create a java class with few setters and getter and that class need to be extended from ActionForm. While using DynaActionForm you no need to write a java class directly you can get the user details without including setter and getter methods.

73.If validation fails what Request processor will do?

When RequestProcessor decides that validation is fail then it delegates control to input page.(that you configured in struts-config.xml)

74.What is Single Threaded Model in Servlets and how is it useful give one practical example.

For every single user a differnt copy of this servlet is executed. Credit card transactions.

75.Difference between Bean:write and Bean:message?

Bean:message is to display message from .propertiesfile. Bean:write this tag is used to output bean property value from bean property

75.In a registration page when user click register button where the control goes to?

When user click on register button then control automatically goes to ActionServlet from there it goes to RequestProcessor.

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

78. When a thread is created and started, what is its initial state?

A thread is in the ready state after it has been created and started.

79. What are order of precedence and associativity, and how are they used?

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.

80. When a thread blocks on I/O, what state does it enter?

A thread enters the waiting state when it blocks on I/O.

81.Which Java class interacts with Database?

In a Struts application Model Class interacts with database.
More interview question will be updated on daily basis, come back to know interview questions about Struts 2 interview questions also.

82. What is a pure relational ORM?
The entire application, including the user interface, is designed around the relational model and SQL-based relational operations.

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

84. What is Hibernate?

Hibernate is a powerful, high performance object/relational persistence and query service. This lets the users to develop persistent classes following object-oriented
principles such as association, inheritance, polymorphism, composition, and collections.

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

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

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.

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

90. What are the benefits of ORM and Hibernate?

There are many benefits from these. Out of which the following are the most important one.
i. Productivity – Hibernate reduces the burden of developer by providing much of the functionality and let the developer to concentrate on business logic.
ii. 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.
iii. 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.
iv. Vendor independence – Irrespective of the different types of databases that are there, hibernate provides a much easier way to develop a cross platform application.

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.

93. What are Extension interfaces?

When the built-in functionalities provided by hibernate is not sufficient enough, it provides a way so that user can include other interfaces and implement those interfaces
for user desire functionality. These interfaces are called as Extension interfaces.