Tuesday, 7 July 2015

Advanced Java Interview Questions -6



1. What are the legal operands of the instanceof operator?

The left operand is an object reference or null value and the right operand is a class, interface, or array type.

2. How are the elements of a GridBagLayout organized?

The elements of a GridBagLayout are of equal size and are laid out using the squares of a grid.

3. What an I/O filter?

An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.

4. If an object is garbage collected, can it become reachable again?

Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.

5. What is the Set interface?

The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.

6. What classes of exceptions may be thrown by a throw statement?

A throw statement may throw any expression that may be assigned to the Throwable type.

7. What are E and PI?

E is the base of the natural logarithm and PI is mathematical value pi.

8. Are true and false keywords?

The values true and false are not keywords.

9. What is a void return type?

A void return type indicates that a method does not return a value.

10. What method is invoked to cause an object to begin executing as a separate thread?

The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread.

11. Name two subclasses of the TextComponent class.

TextField and TextArea.

12. Which containers may have a MenuBar?

Frame.

13. How are commas used in the intialization and iteration parts of a for statement?

Commas are used to separate multiple statements within the initialization and iteration parts of a for statement.

14. What happens if a try-catch-finally statement does not have a catch clause to handle an exception 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's termination.

15. What is numeric promotion?

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

16. What is the purpose of the File class?

The File class is used to create objects that provide access to the files and directories of a local file system.

17. Can an exception be rethrown?

Yes, an exception can be rethrown.
18. Which Math method is used to calculate the absolute value of a number?

The abs() method is used to calculate absolute values.

19. How does multithreading take place on a computer with a single CPU?

The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.

20. When does the compiler supply a default constructor for a class?

The compiler supplies a default constructor for a class if no other constructors are provided.

21. What invokes a thread's run() method?

After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.

22. Which class is extended by all other classes?

The Object class is extended by all other classes.

23. Can an object be garbage collected while it is still reachable?

A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected..

24. Is the ternary operator written x : y ? z or x ? y : z ?

It is written x ? y : z.

25. What is the difference between the Font and FontMetrics classes?

The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.

26. What is the Map interface?

The Map interface replaces the JDK 1.1

27. What happens if an exception is not caught?

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

28. What is a layout manager?

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

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

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

30. 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 unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.

Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

31. 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 displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system.

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

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

34. Can try statements be nested?

Try statements may be tested.

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

The default value of the boolean type is false.

36. Can an unreachable object become reachable again?

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

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

38. 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 its own events and performs its own scrolling.

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

The postfix form returns the current value all of the expression and then performs the increment operation on that value.

40. What is the purpose of a statement block?

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

41. What is the ResourceBundle class?

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

Dictionary class and is used associate keys with values.

42 How can a GUI component handle its own events in Java Programming?

A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.

43 How are the elements of a GridBagLayout organized in Java Programming?

The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.

44 What advantage do Java’s layout managers provide over traditional windowing systems?

Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java’s layout managers aren’t tied to absolute sizing and positioning, they are able to accommodate platform-specific differences among windowing systems.

45 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 displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system.

46 What is the purpose of the Runtime class in Java Programming?

The purpose of the Runtime class is to provide access to the Java runtime system in Java Programming.

47 What is the purpose of the System class in Java Programming?

The purpose of the System class is to provide access to system resources in Java Programming.

48 What is the purpose of the finally clause of a try-catch-finally statement in Java Programming?

The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.

49 What classes of exceptions may be caught by a catch clause in Java Programming?

A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.

50 If a class is declared without any access modifiers, where may the class be accessed in Java Programming?

A class that is declared without any access modifiers is said to have package or friendly access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.

51  What is the difference between static and non-static variables in Java Programming?

A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.

52  What is the difference between the paint() and repaint() methods in Java Programming?

The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.

53 What is the purpose of the File class in Java Programming?

The File class is used to create objects that provide access to the files and directories of a local file system.

54 What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy in Java Programming?

The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.

55 What is the difference between a static and a non-static inner class in Java Programming?

A non-static inner class may have object instances that are associated with instances of the class’s outer class. A static inner class does not have any object instances.

56 What is an object’s lock and which object’s have locks in Java Programming?

An object’s lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object’s lock. All objects and classes have locks. A class’s lock is acquired on the class’s Class object.

57  When can an object reference be cast to an interface reference in Java Programming?

An object reference be cast to an interface reference when the object implements the referenced interface.

58  What is the difference between a Window and a Frame in Java Programming?

The Frame class extends Window to define a main application window that can have a menu bar.

59  What do heavy weight components mean in Java Programming?

Heavy weight components like Abstract Window Toolkit (AWT), 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. In this relationship, the Motif button is called the peer to the java.awt.Button. If you create two Buttons, two peers and hence two Motif Buttons are also created. The Java platform communicates with the Motif Buttons using the Java Native Interface. For each and every component added to the application, there is an additional overhead tied to the local windowing system, which is why these components are called heavyweight.

60 How are this() and super() used with constructors in Java Programming?

this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor in Java Programming.

61 What is the difference between the Boolean & operator and the && operator in Java Programming?

If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator
is applied to the operand. When an expression involving the && operator is evaluated, the first operand is
evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is
then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the
second operand is skipped.

Operator & has no chance to skip both sides evaluation and && operator does. If asked why, give details as above.

62 Which class should you use to obtain design information about an object in Java Programming?

The Class class is used to obtain information about an object’s design.


63 How does multithreading take place on a computer with a single CPU in Java Programming?

The operating system’s task scheduler allocates execution time to multiple tasks. By quickly switching between
executing tasks, it creates the impression that tasks execute sequentially.

64 What restrictions are placed on method overloading in Java Programming?

Two methods may not have the same name and argument list but different return types.

65 What is the Map interface in Java Programming?

The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.

66 Does a class inherit the constructors of its superclass in Java Programming?

A class does not inherit constructors from any of its superclasses.

67 Name primitive Java types?

The primitive types are byte, char, short, int, long, float, double, and boolean.

68 What is the Gregorian Calendar class in Java Programming?

The Gregorian Calendar provides support for traditional Western calendars in Java Programming.

69 What is the SimpleTimeZone class in Java Programming?

The SimpleTimeZone class provides support for a Gregorian calendar in Java Programming.


70 Which package has light weight components in Java Programming?

javax. Swing package. All components in Swing, except JApplet, JDialog, JFrame and JWindow are lightweight components in Java Programming.

71 What are peerless components in Java Programming?

The peerless components are called light weight components.

72 What is the difference between the Font and FontMetrics classes in Java Programming?

The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.

73 What happens when a thread cannot acquire a lock on an object in Java Programming?

If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object’s lock, it enters the waiting state until the lock becomes available.

74 What restrictions are placed on method overriding in Java Programming?

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

75 What is casting in Java Programming?

There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.

76 Name Container classes in Java Programming?

Container classes in Java:

Window,
Frame,
Dialog,
FileDialog,
Panel,
Applet,
or ScrollPane

77 What class allows you to read objects directly from a stream in Java Programming?

The ObjectInputStream class supports the reading of objects from input streams.

78  Which Container method is used to cause a container to be laid out and redisplayed in Java Programming?

validate();
Container method is used to cause a container to be laid out and redisplayed in Java Programming

79 What is the Properties class in Java Programming?

The properties class is a subclass of Hash table that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.

80 Which class is the super class for every class in Java Programming?

Object class is the super class for every class in Java Programming

81 What invokes a thread’s run() method in Java Programming?

After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread’s run() method when the thread is initially executed.

82 Define class and object. Explain them with an example using java.

Class: A class is a program construct which encapsulates data and operations on data. In object oriented programming, the class can be viewed as a blue print of an object

83 Explain class vs. instance with example using java.

A class is a program construct which encapsulates data and operations on data. It is a blue print of an object

84 What is a method? Provide several signatures of the methods.

A java method is a set of statements to perform a task. A method is placed in a class. Signatures of methods: The
name of the method, return type and the number of parameters comprise the method signature

86 Explain the difference between instance variable and a class variable. Provide example to explain them.

An instance variable is a variable which has one copy per object / instance. That means every object will have one copy of it

87 Explain how to create instance of a class by giving an example. 

Java supports 3 ways of creating instances. By using new operator – Ex : Product prodMouse = new Product();

88 Define an abstract class. Explain its purpose.

A class with one of more abstract methods is called an Abstract class. An abstract method is a method with signature without code in it

89 What is the difference between an Abstract class and Interface?

An abstract class can have both abstract and concrete methods whereas an interface can have only method signatures

90 What is singleton class? Where is it used?

A class is defined as singleton class, if and only if it can create only one object. This class is useful when
only one object is to be used in the application. The following are some of the uses of singleton class

91 What is a native method?

A native method is a method which is implemented in a non-java language that is targeted for a single machine
type. Native methods can pass or return Java objects

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

A class with access specifier ‘public’ can be accessed across the packages. A package is like a folder in GUI
based operating systems. For example, the “public class String” class is a public class which can be accessed
across the packages

93 What is the purpose of the Runtime class?

The java runtime system can be accessed by the Runtime class. The runtime information – memory availability,
invoking the garbage collector is possible by using Runtime class

94 What is the difference between a static and a non-static inner class?

Like static methods and static members are defined in a class, a class can also be static. To specify the static
class, prefix the keyword ‘static’ before the keyword ‘class’

95 What is the difference between the String and StringBuffer classes?

String class is immutable. The characters of string objects can not be changed / modified. StringBuffer is
mutable. The characters of StringBuffer objects can be modified / changed

97 What is the Dictionary class?

The Dictionary class is an abstract class. The class maps keys to values. The classes such as HashTable are the
sub classes of the abstract class Dictionary

98 What is the ResourceBundle class?

A ResourceBundle is a group of related sub classes which are sharing the same base name. For example, ButtonLabel
is the base name. All the characters following the base name indicates the following elements respectively

99 What is the Vector class?

The capability of implementing a growable array of object is provided by the class Vector

100 What is the SimpleTimeZone class?

SimpleTimeZone is a concrete subclass of TimeZone class. The TimeZone class represents a time zone that is to be
used with Gregorian calendar

101 What is the purpose of the System class?

System class is provided with useful fields (static members) that are pertaining to the environment

102 How are this() and super() used with constructors?

this() constructor is invoked within a method of a class, if the execution of the constructor is to be done before
the functionality of that method

103 How is it possible in Java Programming for two String objects with identical values not to be equal under the
operator?

The  operator compares two objects to determine if they are the same object in memory. It is possible for two
String objects to have the same value, but located indifferent areas of memory.

104 What an I/O filter in Java Programming?

An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way
as it is passed from one stream to another.

105 What is the Set interface in Java Programming?

The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow
duplicate elements.

106 What is the purpose of the enableEvents() method in Java Programming?

The enableEvents() method is used to enable an event for a particular object. Normally, an event is enabled when a
listener is added to an object for a particular event. The enableEvents() method is used by objects that handle
events by overriding their event-dispatch methods.

107 Is Java a super set of JavaScript?

No. They are completely different. Some syntax may be similar.
Read Full

Advanced Java Interview Questions -2



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

2.Given the request path below, which are context path, servlet path and path info?
 

/bookstore/education/index.html
context path: /bookstore
servlet path: /education
path info: /index.html

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

4.Explain the life cycle of Servlet.
Loaded(by the container for first request or on start up if config file suggests load-on-startup), initialized( using init()), service(service() or doGet() or doPost()..), destroy(destroy()) and unloaded.

5.When is the servlet instance created in the life cycle of servlet? What is the importance of configuring a servlet?
An instance of servlet is created when the servlet is loaded for the first time in the container. Init() method is used to configure this servlet instance. This method is called only once in the life time of a servlet, hence it makes sense to write all those configuration details about a servlet which are required for the whole life of a servlet in this method.

6.Why don't we write a constructor in a servlet?
Container writes a no argument constructor for our servlet.

7.When we don't write any constructor for the servlet, how does container create an instance of servlet?

Container creates instance of servlet by calling Class.forName(className).newInstance().

8.Once the destroy() method is called by the container, will the servlet be immediately destroyed? What happens to the tasks(threads) that the servlet might be executing at that time?

Yes, but Before calling the destroy() method, the servlet container waits for the remaining threads that are executing the servlet’s service() method to finish.

9.What is the difference between callling a RequestDispatcher using ServletRequest and ServletContext?

We can give relative URL when we use ServletRequest and not while using ServletContext.

10.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).

11.Which interface must be implemented by all servlets?

Servlet interface.

12.What is 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.

13.Why is Servlet so popular?

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.

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

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

16.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()

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

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

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

1.boolean hasFoo = !(request.getParameter("foo") == null || request.getParameter("foo").equals(""));
2. boolean hasParameter = request.getParameterMap().contains(theParameter);
(which works in Servlet 2.3+)

20.How can I send user authentication information while making URL Connection?

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

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

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

You can use a client-side Refresh or Server Push

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

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

25.Difference between GET and POST ?

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.

26.What is session?

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

27.Why is it that we can't give relative URL's when using ServletContext.getRequestDispatcher() when we can use the same while calling ServletRequest.getRequestDispatcher()?

Since ServletRequest has the current request path to evaluae the relative path while ServletContext does not.

28.What’s the difference between servlets and applets?

Servlets are to servers; applets are to browsers. Unlike applets, however, servlets have no graphical user interface.

29. What’s the advantages using servlets than using CGI?

Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. It is efficient, convenient, powerful, portable, secure and inexpensive. Servlets also address the problem of doing server-side programming with platform-specific APIs: they are developed with Java Servlet API, a standard Java extension.

30.What are the uses of Servlets?

A servlet can handle multiple requests concurrently, and can synchronize requests. This allows servlets to support systems such as on-line conferencing. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries.

31.What’s the Servlet Interface?

The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet. Servlets–>Generic Servlet–>HttpServlet–>MyServlet. The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet.

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

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

34.Why is Servlet so popular?

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.

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

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

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

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

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

40.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()

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

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

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

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

1.boolean hasFoo = !(request.getParameter("foo") == null || request.getParameter("foo").equals(""));
2. boolean hasParameter = request.getParameterMap().contains(theParameter);
(which works in Servlet 2.3+)

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

You can use a client-side Refresh or Server Push

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

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

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

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

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

51.What are the uses of Servlet?

Typical uses for HTTP Servlets include:
Processing and/or storing data submitted by an HTML form.
Providing dynamic content, e.g. returning the results of a database query to the client.
A Servlet can handle multiple request concurrently and be used to develop high performance system
Managing state information on top of the stateless HTTP, e.g. for an online shopping cart system which manages shopping carts for many concurrent customers and maps every request to the right customer.

52.What are the advantages of Servlet over CGI?

Servlets have several advantages over CGI:
A Servlet does not run in a separate process. This removes the overhead of creating a new process for each request.
A Servlet stays in memory between requests. A CGI program (and probably also an extensive runtime system or interpreter) needs to be loaded and started for each CGI request.
There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
Several web.xml conveniences
A handful of removed restrictions
Some edge case clarifications

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

The life cycle of a servlet consists of the following phases:
Servlet class loading : For each servlet defined in the deployment descriptor of the Web application, the servlet container locates and loads a class of the type of the servlet. This can happen when the servlet engine itself is started, or later when a client request is actually delegated to the servlet.

Servlet instantiation : After loading, it instantiates one or more object instances of the servlet class to service the client requests.

Initialization (call the init method) : After instantiation, the container initializes a servlet before it is ready to handle client requests. The container initializes the servlet by invoking its init() method, passing an object implementing the ServletConfig interface. In the init() method, the servlet can read configuration parameters from the deployment descriptor or perform any other one-time activities, so the init() method is invoked once and only once by the servlet container.

Request handling (call the service method) : After the servlet is initialized, the container may keep it ready for handling client requests. When client requests arrive, they are delegated to the servlet through the service() method, passing the request and response objects as parameters. In the case of HTTP requests, the request and response objects are implementations of HttpServletRequest and HttpServletResponse respectively. In the HttpServlet class, the service() method invokes a different handler method for each type of HTTP request, doGet() method for GET requests, doPost() method for POST requests, and so on.

Removal from service (call the destroy method) : A servlet container may decide to remove a servlet from service for various reasons, such as to conserve memory resources. To do this, the servlet container calls the destroy() method on the servlet. Once the destroy() method has been called, the servlet may not service any more client requests. Now the servlet instance is eligible for garbage collection
The life cycle of a servlet is controlled by the container in which the servlet has been deployed.


54.Why do we need a constructor in a servlet if we use the init method?

Even though there is an init method in a servlet which gets called to initialize it, a constructor is still required to instantiate the servlet. Even though you as the developer would never need to explicitly call the servlet's constructor, it is still being used by the container (the container still uses the constructor to create an instance of the servlet). Just like a normal POJO (plain old java object) that might have an init method, it is no use calling the init method if you haven't constructed an object to call it on yet.

55.How the servlet is loaded?

A servlet can be loaded when:
First request is made.
Server starts up (auto-load).
There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
Administrator manually loads.

56.How a Servlet is unloaded?

A servlet is unloaded when:
Server shuts down.
Administrator manually unloads.


57.What is the GenericServlet class?

GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig interface. In addition to the methods declared in these two interfaces, this class also provides simple versions of the lifecycle methods init and destroy, and implements the log method declared in the ServletContext interface.
Note: This class is known as generic servlet, since it is not specific to any protocol.

58.Why is HttpServlet declared abstract?

the HttpServlet class is declared abstract because the default implementations of the main service methods do nothing and must be overridden. This is a convenience implementation of the Servlet interface, which means that developers do not need to implement all service methods. If your servlet is required to handle doGet() requests for example, there is no need to write a doPost() method too.

59.Can servlet have a constructor ?

One can definitely have constructor in servlet.Even you can use the constrctor in servlet for initialization purpose,but this type of approch is not so common. You can perform common operations with the constructor as you normally do.The only thing is that you cannot call that constructor explicitly by the new keyword as we normally do.In the case of servlet, servlet container is responsible for instantiating the servlet, so the constructor is also called by servlet container only.

60.What are the types of protocols supported by HttpServlet ?

It extends the GenericServlet base class and provides a framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol.

61.What is a servlet context object?

A servlet context object contains the information about the Web application of which the servlet is a part. It also provides access to the resources common to all the servlets in the application. Each Web application in a container has a single servlet context associated with it.

62.What's the use of the servlet wrapper classes??

The HttpServletRequestWrapper and HttpServletResponseWrapper classes are designed to make it easy for developers to create custom implementations of the servlet request and response types. The classes are constructed with the standard HttpServletRequest and HttpServletResponse instances respectively and their default behaviour is to pass all method calls directly to the underlying objects.

63.Should I override the service() method?

We never override the service method, since the HTTP Servlets have already taken care of it . The default service function invokes the doXXX() method corresponding to the method of the HTTP request.For example, if the HTTP request method is GET, doGet() method is called by default. A servlet should override the doXXX() method for the HTTP methods that servlet supports. Because HTTP service method check the request method and calls the appropriate handler method, it is not necessary to override the service method itself. Only override the appropriate doXXX() method.

64.What is preinitialization of a servlet?

A container does not initialize the servlets as soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.

65.What is session?

A session refers to all the requests that a single client might make to a server in the course of viewing any pages associated with a given application. Sessions are specific to both the individual user and the application. As a result, every user of an application has a separate session and has access to a separate set of session variables.

66.What is Session Tracking?

Session tracking is a mechanism that servlets use to maintain state about a series of requests from the same user (that is, requests originating from the same browser) across some period of time.

67.What is the need of Session Tracking in web application?

HTTP is a stateless protocol i.e., every request is treated as new request. For web applications to be more realistic they have to retain information across multiple requests. Such information which is part of the application is reffered as "state". To keep track of this state we need session tracking.

68.What are the types of Session Tracking ?

Sessions need to work with all web browsers and take into account the users security preferences. Therefore there are a variety of ways to send and receive the identifier:
URL rewriting : URL rewriting is a method of session tracking in which some extra data (session ID) is appended at the end of each URL. This extra data identifies the session. The server can associate this session identifier with the data it has stored about that session. This method is used with browsers that do not support cookies or where the user has disabled the cookies.

Hidden Form Fields : Similar to URL rewriting. The server embeds new hidden fields in every dynamically generated form page for the client. When the client submits the form to the server the hidden fields identify the client.

Cookies : Cookie is a small amount of information sent by a servlet to a Web browser. Saved by the browser, and later sent back to the server in subsequent requests. A cookie has a name, a single value, and optional attributes. A cookie's value can uniquely identify a client.

Secure Socket Layer (SSL) Sessions : Web browsers that support Secure Socket Layer communication can use SSL's support via HTTPS for generating a unique session key as part of the encrypted conversation.

69.How do I use cookies to store session state on the client?

In a servlet, the HttpServletResponse and HttpServletRequest objects passed to method HttpServlet.service() can be used to create cookies on the client and use cookie information transmitted during client requests. JSPs can also use cookies, in scriptlet code or, preferably, from within custom tag code.
To set a cookie on the client, use the addCookie() method in class HttpServletResponse. Multiple cookies may be set for the same request, and a single cookie name may have multiple values.
To get all of the cookies associated with a single HTTP request, use the getCookies() method of class HttpServletRequest

70.What are some advantages of storing session state in cookies?

Cookies are usually persistent, so for low-security sites, user data that needs to be stored long-term (such as a user ID, historical information, etc.) can be maintained easily with no server interaction.
For small- and medium-sized session data, the entire session data (instead of just the session ID) can be kept in the cookie.

71.What are some disadvantages of storing session state in cookies?

Cookies are controlled by programming a low-level API, which is more difficult to implement than some other approaches.
All data for a session are kept on the client. Corruption, expiration or purging of cookie files can all result in incomplete, inconsistent, or missing information.
Cookies may not be available for many reasons: the user may have disabled them, the browser version may not support them, the browser may be behind a firewall that filters cookies, and so on. Servlets and JSP pages that rely exclusively on cookies for client-side session state will not operate properly for all clients. Using cookies, and then switching to an alternate client-side session state strategy in cases where cookies aren't available, complicates development and maintenance.
Browser instances share cookies, so users cannot have multiple simultaneous sessions.
Cookie-based solutions work only for HTTP clients. This is because cookies are a feature of the HTTP protocol. Notice that the while package javax.servlet.http supports session management (via class HttpSession), package javax.servlet has no such support.


72.A client sends requests to two different web components. Both of the components access the session. Will they end up using the same session object or different session ?

Creates only one session i.e., they end up with using same session .
Sessions is specific to the client but not the web components. And there is a 1-1 mapping between client and a session.

73.What is servlet lazy loading?

A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading.
The servlet specification defines the <load-on-startup> element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up.
The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.

74.What is Servlet Chaining?

Servlet Chaining is a method where the output of one servlet is piped into a second servlet. The output of the second servlet could be piped into a third servlet, and so on. The last servlet in the chain returns the output to the Web browser.

75.How are filters?

Filters are Java components that are used to intercept an incoming request to a Web resource and a response sent back from the resource. It is used to abstract any useful information contained in the request or response. Some of the important functions performed by filters are as follows:
Security checks
Modifying the request or response
Data compression
Logging and auditing
Response compression
Filters are configured in the deployment descriptor of a Web application. Hence, a user is not required to recompile anything to change the input or output of the Web application.


76.What is URL rewriting?

URL rewriting is a method of session tracking in which some extra data is appended at the end of each URL. This extra data identifies the session. The server can associate this session identifier with the data it has stored about that session.
Every URL on the page must be encoded using method HttpServletResponse.encodeURL(). Each time a URL is output, the servlet passes the URL to encodeURL(), which encodes session ID in the URL if the browser isn't accepting cookies, or if the session tracking is turned off.
E.g., http://abc/path/index.jsp;jsessionid=123465hfhs
Advantages
URL rewriting works just about everywhere, especially when cookies are turned off.
Multiple simultaneous sessions are possible for a single user. Session information is local to each browser instance, since it's stored in URLs in each page being displayed. This scheme isn't foolproof, though, since users can start a new browser instance using a URL for an active session, and confuse the server by interacting with the same session through two instances.
Entirely static pages cannot be used with URL rewriting, since every link must be dynamically written with the session state. It is possible to combine static and dynamic content, using (for example) templating or server-side includes. This limitation is also a barrier to integrating legacy web pages with newer, servlet-based pages.
DisAdvantages
Every URL on a page which needs the session information must be rewritten each time a page is served. Not only is this expensive computationally, but it can greatly increase communication overhead.
URL rewriting limits the client's interaction with the server to HTTP GETs, which can result in awkward restrictions on the page.
URL rewriting does not work well with JSP technology.
If a client workstation crashes, all of the URLs (and therefore all of the data for that session) are lost.

77.What are the functions of an intercepting filter?

The functions of an intercepting filter are as follows:
It intercepts the request from a client before it reaches the servlet and modifies the request if required.
It intercepts the response from the servlet back to the client and modifies the request if required.
There can be many filters forming a chain, in which case the output of one filter becomes an input to the next filter. Hence, various modifications can be performed on a single request and response.

78.What are the functions of the Servlet container?

The functions of the Servlet container are as follows:
Lifecycle management : It manages the life and death of a servlet, such as class loading, instantiation, initialization, service, and making servlet instances eligible for garbage collection.
Communication support : It handles the communication between the servlet and the Web server.
Multithreading support : It automatically creates a new thread for every servlet request received. When the Servlet service() method completes, the thread dies.
Declarative security : It manages the security inside the XML deployment descriptor file.
JSP support : The container is responsible for converting JSPs to servlets and for maintaining them.

79.How can an existing session be invalidated?

An existing session can be invalidated in the following two ways:
Setting timeout in the deployment descriptor: This can be done by specifying timeout between the <session-timeout>tags as follows:
<session-config>
       <session-timeout>10</session-timeout>
</session-config>
This will set the time for session timeout to be ten minutes.
Setting timeout programmatically: This will set the timeout for a specific session. The syntax for setting the timeout programmatically is as follows:
public void setMaxInactiveInterval(int interval)
The setMaxInactiveInterval() method sets the maximum time in seconds before a session becomes invalid.
Note :Setting the inactive period as negative(-1), makes the container stop tracking session, i.e, session never expires.

80.How can the session in Servlet can be destroyed?

An existing session can be destroyed in the following two ways:
Programatically : Using session.invalidate() method, which makes the container abonden the session on which the method is called.
When the server itself is shutdown.

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

Yes. But you will not get the servlet specific things from constructor. 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 constructor 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.

82.What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?

In request.getRequestDispatcher(path) in order to create it we need to give the relative path of the resource. But in resourcecontext.getRequestDispatcher(path) in order to create it we need to give the absolute path of the resource.

83.What are context initialization parameters?

Context initialization parameters are specified by the in the web.xml file, these are initialization parameter for the whole application.

84.What is a Expression?

Expressions are act as place holders for language expression, expression is evaluated each time the page is accessed. This will be included in the service method of the generated servlet.

85.What is a Declaration?

It declares one or more variables or methods for use later in the JSP source file. A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as semicolons separate them. The declaration must be valid in the scripting language used in the JSP file. This will be included in the declaration section of the generated servlet.

86.What is a Scriptlet?

A scriptlet can contain any number of language statements, variable or expressions that are valid in the page scripting language. Within scriptlet tags, you can declare variables to use later in the file, write expressions valid in the page scripting language, use any of the JSP implicit objects or any object declared with a . Generally a scriptlet can contain any java code that are valid inside a normal java method. This will become the part of generated servlet's service method.

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

88.What is servlet context ?

The servlet context is an object that contains a information about the Web application and container. 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.

89.What is a servlet ?

servlet is a java program that runs inside a web container.

90.What's the Servlet Interface?

The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet.

91.How do I use a scriptlet to initialize a newly instantiated bean?

A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated (Only at the time of instantiation.) Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone.

92.What is the difference between ServletContext and ServletConfig?

The ServletConfig gives the information about the servlet initialization parameters. The servlet engine implements the ServletConfig interface in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet's init() method. The ServletContext gives information about the container. The ServletContext interface provides information to servlets regarding the environment in which they are running. It also provides standard way for servlets to write events to a log file.

93.How can a servlet refresh automatically?

We can use a client-side Refresh or Server Push

94.What is Server side push?

Server Side push is useful when data needs to change regularly on the clients application or browser, without intervention from client. The mechanism used is, when client first connects to Server, then Server keeps the TCP/IP connection open.

95.What are two different types of Servlets ?

GenericServlet and HttpServlet. HttpServlet is used to implement HTTP protocol, where as Generic servlet can implement any protocol.

96.What is the life cycle of servlet?

Each servlet has the same life cycle: first, the server loads and initializes the servlet by calling the init method. This init() method will be executed only once during the life time of a servlet. Then when a client makes a request, it executes the service method. finally it executes the destroy() method when server removes the servlet.

97. Can we call destroy() method on servlets from service method ?
Yes.

98.What is the need of super.init (config) in servlets ?

Then only we will be able to access the ServletConfig from our servlet. If there is no ServletConfig our servlet will not have any servlet nature.

99.What is the difference between GenericServlet and HttpServlet?

GenericServlet supports any protocol. HttpServlet supports only HTTP protocol. By extending GenericServlet we can write a servlet that supports our own custom protocol or any other protocol.

100.What are the implicit objects?

Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects are: request, response, pageContext, session, application, out, config, page, exception

101. What's the difference between forward and sendRedirect?

forward is server side redirect and sendRedirect is client side redirect. When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completely with in the web container And then returns to the calling method. When a sendRedirect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward. Client can disable sendRedirect.

102.Can we write a constructor for servlet ?

Yes. But the container will always call the default constructor only. If default constructor is not present , the container will throw an exception.

103.Question: What are the parameters for service method ?

ServletRequest and ServletResponse

104.What are cookies ?

Cookies are small textual information that are stored on client computer. Cookies are used for session tracking.

105.What is the meaning of response has already been committed error?

You will get this error only when you try to redirect a page after you already have flushed the output buffer. This happens because HTTP specification force the header to be set up before the lay out of the page can be shown. When you try to send a redirect status, your HTTP server cannot send it right now if it hasn't finished to set up the header. Simply it is giving the error due to the specification of HTTP 1.0 and 1.1

106.What is HttpTunneling?

HTTP tunneling is used to encapsulate other protocols within the HTTP or HTTPS protocols. Normally the intranet is blocked by a firewall and the network is exposed to the outer world only through a specific web server port, that listens for only HTTP requests. To use any other protocol, that by passes the firewall, the protocol is embedded in HTTP and send as HttpRequest.

107.How to pass information from JSP to included JSP?

By using jsp:param tag.

108.What is the better way to enable thread-safe servlets and JSPs? SingleThreadModel Synchronization?

The better approach is to use synchronization. Because SingleThreadModel is not scalable. SingleThreadModel is pretty resource intensive from web server's perspective. The most serious issue is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the un serviced requests are queued until something becomes free - which results in poor performance.

109.What is a output comment?

A comment that is sent to the client in the viewable page source. The JSP engine handles an output comment as un interpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.

110.What is a Hidden Comment

Hidden Comments are JSP comments. A comments that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags.

111.What are the differences between a session and a cookie?

Session is stored in server but cookie stored in client. Session should work regardless of the settings on the client browser. There is no limit on the amount of data that can be stored on session. But it is limited in cookie. Session can store objects and cookies can store only strings. Cookies are faster than session.

112.What is the difference between ServletContext and PageContext?

ServletContext gives the information about the container and PageContext gives the information about the Request

113.Why in Servlet 2.4 specification SingleThreadModel has been deprecated?

SingleThreadModel is pretty resource intensive from web server's perspective. When the number of concurrent requests exhaust the servlet instance pool, all the un serviced requests are queued until something becomes free - which results in poor performance.

114.How can I set a cookie?

Cookie c = new Cookie("name","value");
response.addCookie(c);

115. How will you delete a cookie?

Cookie c = new Cookie ("name", null);
c.setMaxAge(0);
response.addCookie(killCookie);


116.What is the difference between Context init parameter and Servlet init parameter?

Servlet init parameters are for a single servlet only. No body out side that servlet can access that. It is declared inside the tag inside Deployment Descriptor, where as context init parameter is for the entire web application. Any servlet or JSP in that web application can access context init parameter. Context parameters are declared in a tag directly inside the web-app tag. The methods for accessing context init parameter is getServletContext ().getInitParamter (“name”) where as method for accessing servlet init parameter is getServletConfig ().getInitParamter (“name”);

117. What is the difference between setting the session time out in deployment descriptor and setting the time out programmatically?

In DD time out is specified in terms of minutes only. But in programmatically it is specified in seconds. A session time out value of zero or less in DD means that the session will never expire. To specify session will never expire programmatically it must be negative value.

118.How can we set the inactivity period on a per-session basis?

We can set the session time out programmatically by using the method setMaxInactiveInterval() of HttpSession.

119. How can my application get to know when a HttpSession is removed?

You can define a class which implements HttpSessionBindingListener and override the valueUnbound() method.

120.How many cookies can one set in the response object of the servlet? Also, are there any restrictions on the size of cookies?

If the client is using Netscape, the browser can receive and store 300 total cookies and 4 kilobytes per cookie. And the no of cookie is restricted to 20 cookies per server or domain 
Read Full

Jsp

Advanced Java Interview Questions -5
1.Explain the new Features of JDBC 2.0 Core API?

The JDBC 2.0 API includes the complete JDBC API, which includes both core and Optional Package API, and provides inductrial-strength database computing capabilities.
New Features in JDBC 2.0 Core API:
Scrollable result sets- using new methods in the ResultSet interface allows programmatically move the to particular row or to a position relative to its current position
JDBC 2.0 Core API provides the Batch Updates functionality to the java applications.
Java applications can now use the ResultSet.updateXXX methods.
New data types - interfaces mapping the SQL3 data types
Custom mapping of user-defined types (UTDs)
Miscellaneous features, including performance hints, the use of character streams, full precision for java.math.BigDecimal values, additional security, and support for time zones in date, time, and timestamp values.

2.How you can force the garbage collection?
Garbage collection automatic process and can’t be forced.

3.What is OOPS?

OOP is the common abbreviation for Object-Oriented Programming.

4.Explain garbage collection?

Garbage collection is one of the most important feature of Java. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program cann’t directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. I Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.

5.Describe the principles of OOPS.

There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.

6.Explain the Polymorphism principle.

The meaning of Polymorphism is something like one name many forms. Polymorphism enables one entity to be used as as general category for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can be explained as “one interface, multiple methods”.

7.Explain the different forms of Polymorphism.

From a practical programming viewpoint, polymorphism exists in three distinct forms in Java:
Method overloading
Method overriding through inheritance
Method overriding through the Java interface

8.Explain the Encapsulation principle.

Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.

9.Explain the Inheritance principle.

Inheritance is the process by which one object acquires the properties of another object.

10.What are Access Specifiers available in Java?

Access specifiers are keywords that determines the type of access to the member of a class. These are: Public ,Protected , Private , Defaults

11.Describe the wrapper classes in Java.

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.

12.What do you understand by JSP Actions?

JSP actions are XML tags that direct the server to use existing components or control the behavior of the JSP engine. JSP Actions consist of a typical (XML-based) prefix of “jsp” followed by a colon, followed by the action name followed by one or more attribute parameters.

13.What is the difference between and <%@ include file = ... >?.

Both the tag includes the information from one page in another. The differences are as follows:
: 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 to for modularizing the web application. If the included file changed then the new content will be included in the output.
<%@ 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 in the included file changes, the changed content will not included in the output. This approach is used when the code from one jsp file required to include in multiple jsp files.

14.What is the difference between and response.sendRedirect(url),?

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 kills the session variables.

15.What are all the different scope values for the tag?

tag is used to use any java object in the jsp page. Here are the scope values for tag:

a) page
b) request
c) session and
d) application

16.What is JSP Output Comments?

JSP Output Comments are the comments that can be viewed in the HTML source file.

17.What are implicit Objects available to the JSP Page?

Implicit objects are the objects available to the JSP page. These objects are created by Web container and contain information related to a particular request, page, or application.

18.What is JSP declaration?

JSP Decleratives are the JSP tag used to declare variables. Declaratives are enclosed in the <%! %> tag and ends in semi-colon. You declare variables and functions in the declaration tag and can use anywhere in the JSP. Here is the example of declaratives:

<%@page contentType="text/html" %>

<%!
int cnt=0;
private int getCount(){
//increment cnt and return the value
cnt++;
return cnt;
}
%>

Values of Cnt are:
<%=getCount()%>

19.What is JSP Scriptlet?

JSP Scriptlet is jsp tag which is used to enclose java code in the JSP pages. Scriptlets begins with <% tag and ends with %> tag. Java code written inside scriptlet executes every time the JSP is invoked.
Example:

<%
//java codes
String userName=null;
userName=request.getParameter(”userName”);
%>

20.What is J2EE?

J2EE Stands for Java 2 Enterprise Edition. J2EE is an environment for developing and deploying enterprise applications. J2EE specification is defined by Sun Microsystems Inc. The J2EE platform is one of the best platform for the development and deployment of enterprise applications. The J2EE platform is consists of a set of services, application programming interfaces (APIs), and protocols, which provides the functionality necessary for developing multi-tiered, web-based applications. You can download the J2EE SDK and development tools from http://java.sun.com/.

21.What are the life-cycle methods of JSP?

Life-cycle methods of the JSP are:
a) jspInit(): The container calls the jspInit() to initialize the servlet instance. It is called before any other method, and is called only once for a servlet instance.
b)_jspService(): The container calls the _jspservice() for each request and it passes the request and the response objects. _jspService() method cann’t be overridden.
c) jspDestroy(): The container calls this when its instance is about to destroyed.
The jspInit() and jspDestroy() methods can be overridden within a JSP page.

22.What do you understand by a J2EE module?

A J2EE module is a software unit that consists of one or more J2EE components of the same container type along with one deployment descriptor of that type. J2EE specification defines four types of modules:
a) EJB
b) Web
c) application client and
d) resource adapter
In the J2EE applications modules can be deployed as stand-alone units. Modules can also be assembled into J2EE applications.

23.What are the contents of web module?

A web module may contain:
a) JSP files
b) Java classes
c) gif and html files and
d) web component deployment descriptors

24.Differentiate between .ear, .jar and .war files.

These files are simply zipped file using java jar tool. These files are created for different purposes. Here is the description of these files:
.jar files: These files are with the .jar extenstion. The .jar files contains the libraries, resources and accessories files like property files.
.war files: These files are with the .war extension. The war file contains the web application that can be deployed on the any servlet/jsp container. The .war file contains jsp, html, javascript and other files for necessary for the development of web applications.
.ear files: The .ear file contains the EJB modules of the application.

25.What is the difference between Session Bean and Entity Bean?

Session Bean: Session is one of the EJBs and it represents a single client inside the Application Server. Stateless session is easy to develop and its efficient. As compare to entity beans session beans require few server resources.
A session bean is similar to an interactive session and is not shared; it can have only one client, in the same way that an interactive session can have only one user. A session bean is not persistent and it is destroyed once the session terminates.
Entity Bean: An entity bean represents persistent global data from the database. Entity beans data are stored into database.

26.Why J2EE is suitable for the development distributed multi-tiered enterprise applications?

The J2EE platform consists of multi-tiered distributed application model. J2EE applications allows the developers to design and implement the business logic into components according to business requirement. J2EE architecture allows the development of multi-tired applications and the developed applications can be installed on different machines depending on the tier in the multi-tiered J2EE environment . The J2EE application parts are:
a) Client-tier components run on the client machine.
b) Web-tier components run on the J2EE server.
c) Business-tier components run on the J2EE server and the
d) Enterprise information system (EIS)-tier software runs on the EIS servers

27.Why do understand by a container?

Normally, thin-client multi-tiered applications are hard to write because they involve many lines of intricate code to handle transaction and state management, multithreading, resource pooling, and other complex low-level details. The component-based and platform-independent J2EE architecture makes J2EE applications easy to write because business logic is organized into reusable components. In addition, the J2EE server provides underlying services in the form of a container for every component type.
In short containers are the interface between a component and the low-level platform specific functionality that supports the component. The application like Web, enterprise bean, or application client component must be assembled and deployed on the J2EE container before executing.

28.What are the services provided by a container?

The services provided by container are as follows:
a) Transaction management for the bean
b) Security for the bean
c) Persistence of the bean
d) Remote access to the bean
e) Lifecycle management of the bean
f) Database-connection pooling
g) Instance pooling for the bean

29.What are types of J2EE clients?

J2EE clients are the software that access the services components installed on the J2EE container. Following are the J2EE clients:
a) Applets
b) Java-Web Start clients
c) Wireless clients
d) Web applications

30.What is Deployment Descriptor?

A deployment descriptor is simply an XML(Extensible Markup Language) file with the extension of .xml. Deployment descriptor describes the component deployment settings. Application servers reads the deployment descriptor to deploy the components contained in the deployment unit. For example ejb-jar.xml file is used to describe the setting of the EJBs.

31.What do you understand by JTA and JTS?

JTA stands for Java Transaction API and JTS stands for Java Transaction Service. JTA provides a standard interface which allows the developers to demarcate transactions in a manner that is independent of the transaction manager implementation. The J2EE SDK uses the JTA transaction manager to implement the transaction. The code developed by developers does not calls the JTS methods directly, but only invokes the JTA methods. Then JTA internally invokes the JTS routines. JTA is a high level transaction interface used by the application code to control the transaction.

32.What is JAXP?

The Java API for XML Processing (JAXP) enables applications to parse and transform XML documents independent of a particular XML processing implementation. JAXP or Java API for XML Parsing is an optional API provided by Javasoft. It provides basic functionality for reading, manipulating, and generating XML documents through pure Java APIs. It is a thin and lightweight API that provides a standard way to seamlessly integrate any XML-compliant parser with a Java application.

33.What is J2EE Connector architecture?

J2EE Connector Architecture (JCA) is a Java-based technology solution for connecting application servers and enterprise information systems (EIS) as part of enterprise application integration (EAI) solutions. While JDBC is specifically used to connect Java EE applications to databases, JCA is a more generic architecture for connection to legacy systems (including databases). JCA was developed under the Java Community Process as JSR 16 (JCA 1.0) and JSR 112 (JCA 1.5). As of 2006, the current version of JCA is version 1.5. The J2EE Connector API is used by J2EE tools developers and system integrators to create resource adapters.

34.What is difference between Java Bean and Enterprise Java Bean?

Java Bean as is a plain java class with member variables and getter setter methods. Java Beans are defined under JavaBeans specification as Java-Based software component model which includes the features like introspection, customization, events, properties and persistence.
Enterprise JavaBeans or EJBs for short are Java-based software components that comply with Java’s EJB specification. EJBs are delpoyed on the EJB container and executes in the EJB container. EJB is not that simple, it is used for building distributed applications. Examples of EJB are Session Bean, Entity Bean and Message Driven Bean. EJB is used for server side programming whereas java bean is a client side. Bean is only development but the EJB is developed and then deploy on EJB Container.

35.What is the difference between JTS and JTA?

In any J2EE application transaction management is one of the most crucial requirements of the application. Given the complexity of today’s business requirements, transaction processing occupies one of the most complex segments of enterprise level distributed applications to build, deploy and maintain. JTS specifies the implementation of a Java transaction manager. JTS specifies the implementation of a Transaction Manager which supports the Java Transaction API (JTA) 1.0 This transaction manager supports the JTA, using which application servers can be built to support transactional Java applications. Internally the JTS implements the Java mapping of the OMG OTS 1.1 specifications. The Java mapping is specified in two packages: org.omg.CosTransactions and org.omg.CosTSPortability. The JTS thus provides a new architecture for transactional application servers and applications, while complying to the OMG OTS 1.1 interfaces internally. This allows the JTA compliant applications to interoperate with other OTS 1.1 complaint applications through the standard IIOP. Java-based applications and Java-based application servers access transaction management functionality via the JTA interfaces. The JTA interacts with a transaction management implementation via JTS. Similarly, the JTS can access resources via the JTA XA interfaces or can access OTS-enabled non-XA resources. JTS implementations can interoperate via CORBA OTS interfaces.
The JTA specifies an architecture for building transactional application servers and defines a set of interfaces for various components of this architecture. The components are: the application, resource managers, and the application server. The JTA specifies standard interfaces for Java-based applications and application servers to interact with transactions, transaction managers, and resource managers JTA transaction management provides a set of interfaces utilized by an application server to manage the beginning and completion of transactions. Transaction synchronization and propagation services are also provided under the domain of transaction management.
In the Java transaction model, the Java application components can conduct transactional operations on JTA compliant resources via the JTS. The JTS acts as a layer over the OTS. The applications can therefore initiate global transactions to include other OTS transaction managers, or participate in global transactions initiated by other OTS compliant transaction managers.

36.Can Entity Beans have no create() methods?

Entity Beans can have no create() methods. Entity Beans have no create() method, when entity bean is not used to store the data in the database. In this case entity bean is used to retrieve the data from database.

37.What are the call back methods in Session bean?

Callback methods are called by the container to notify the important events to the beans in its life cycle. The callback methods are defined in the javax.ejb.EntityBean interface.The callback methods example are ejbCreate(), ejbPassivate(), and ejbActivate().

38.What is bean managed transaction?

In EJB transactions can be maintained by the container or developer can write own code to maintain the transaction. If a developer doesn't want a container to manage transactions, developer can write own code to maintain the database transaction.

39.How can one prove that the array is not null but empty?

Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.

40.What is meant by Endianness ?

Endianness describes how multiple data types such as short , int and long are stored in memory.If it takes two bytes to represent a short, then to predict if the most significant or the least significant comes first.If the most significant byte is first, followed by the least significant one then the machine is said to be big endian. Machines such as the SPARC and Power PC are big-endian, while the Intel x86 series is little-endian.

41.How many types of literals are there in JAVA?

There are four types of literals they are Integer literals, Floating point literals, Boolean literals and character literals.

42.A note on compiling & Executing a JAVA pgm?

(i) The name of the source file is called in terms of .java
(ii) A source file is called a compilation unit. This has one or more class definitions.
(iii) The name of the class should be same as that of the file.
(iv) Once compiled the .java file creates a .class file. This is done by the compiler javac
(v) This classfile contains the bytecode version of the program.

43.A note on PUBLIC , PRIVATE , STATIC , VOID & MAIN.

(i) All Java applications begin execution by calling main ()
(ii) When a class member is defined as public. Then that member may be accessed by code outside the class in which it is declared.
(iii) The opposite of public is private which prevents a member from being used by code defined outside of its class.
(iv) The keyword static allows main() to be called without having to instantiate a particular instance of the class. This is mandatory because main () is called by the Java interpreter before any objects are made.
(v) CASE SENSITIVE : Main () is different from main(). It is important to know that that Main() would be compiled. But the Java interpreter would report an error if it would not find main().

44.What is meant by Garbage collection ?

The technique that automatically destroys the dynamically created objects is called garbage collection. When no reference to an object exists, that object is assumed to be no longer needed , and memory occupied by that object can be reclaimed.

45.What are the access modifiers?

There are three types of access modifiers.
(i) Private - Makes a method or a variable accessible only from within its own class.
(ii) (ii) Protected - Makes a method or a variable accessible only to classes in the same package or subclasses of the class.
(iii) (iii) Public - Makes a class , method or variable accessible from any other class.

46.A note on keywords for Error handling.

(i) Catch - Declares the block of code used to handle an exception.
(ii) Finally - Block of code , usually following a typecatch statement, which is executed no matter what program flow occurs when dealing with an exception. (iii) Throw - Used to pass an exception up to the method that calls this method.
(iv) Throws - Indicates the method will pass an exception to the method that called it.
(v) Try - Block of code that will be tried but which may cause an exception.
(vi) Assert - Evaluates a conditional _expression to verify the programmer’s assumption.

47.How many ways can you represent integer numbers in JAVA?

There are three ways , you can represent integer numbers in JAVA. They are decimal (base 10) , octal (base  , and hexadecimal (base 16).

48.Difference between a process and a thread?

I remember having read this answer somewhere. “Threads are like tiny ropes. A Process would denote a rope made out from these threads.” Fun apart, a process can contain multiple threads. Also a process gets its own memory address space while a thread doesn’t.

49.What are checked and unchecked exceptions?

Checked exceptions are the ones which you expect beforehand to be raised when an exceptional condition occurs and so write your code in a try-catch block to handle that sufficiently. For example: InsuffucientBalanceException which might be raised when money is being withdrawn from a bank account and the account has insufficient balance. Checked exceptions are sub classes of Exception.
Unchecked exceptions are the ones which cannot be handled in the code. These are rather unexpected exceptions like NullPointerException, OutOfMemoryError, DivideByZeroException, typically, programming errors. Unchecked exceptions are subclasses of RunTimeExceptions.

50.What is singleton class? where is it used?

Singleton is a design pattern meant to provide one and only one instance of an object. Other objects can get a reference to this instance through a static method (class constructor is kept private). Why do we need one? Sometimes it is necessary, and often sufficient, to create a single instance of a given class. This has advantages in memory management, and for Java, in garbage collection. Moreover, restricting the number of instances may be necessary or desirable for technological or business reasons–for example, we may only want a single instance of a pool of database connections.

51.Garbage collection thread belongs to which priority..min?normal?max?

The Java garbage collection is implemented as a low priority thread

52.What is meant by time slicing?

its a task scheduling method. With time slicing, or “Round-Robin Systems”, several processes are executed sequentially to completion. Each executable task is assigned a fixed-time quantum called a time slice in which to execute.

53.What is a compilation unit?

The smallest unit of source code that can be compiled, i.e. a .java file.

54.Is string a wrapper class?

String is a class, but not a wrapper class. Wrapper classes like (Integer) exist for each primitive type. They can be used to convert a primitive data value into an object, and vice-versa.

55.how can you retrieve warning in jdbc?

Write my JDBC code in a try-catch block and catch the SQLExcpetions

56.Is there any tool in java that can create reports?

Yes there are third party tools available.

57.What is JTS? Where is it used?

JTS specifies the implementation of a transaction manager which supports the Java Transaction API (JTA) and implements the Java mapping of the Object Management Group (OMG) Object Transaction Service (OTS) specification (at the level below the API).

58.Why java does not have multiple inheritance?

The reasons for omitting multiple inheritance from the Java language mostly stem from the “simple, object oriented, and familiar” goal. As a simple language, Java’s creators wanted a language that most developers could grasp without extensive training. To that end, they worked to make the language as similar to C++ as possible (familiar) without carrying over C++’s unnecessary complexity (simple). In the designers’ opinion, multiple inheritance causes more problems and confusion than it solves. So they cut multiple inheritance from the language (just as they cut operator overloading). The designers’ extensive C++ experience taught them that multiple inheritance just wasn’t worth the headache.

59.Why java is not a 100% oops?

In a 100% Object oriented language, everything is an Object. That is not the case with Java. Java uses primitive types such as int, char, double. Java primitive types ARE NOT OBJECTS. All the rest are objects. Keep in mind that int, char and other primitive types CAN NOT BE STORED in collections (e.g. Vector, Hashtable) to store these types in a collections, you need to Use wrapper classes (e.g. Integer, Double).

60.What is a resource bundle?

In its simplest form, a resource bundle is represented by a text file containing keys and a text value for each key.

61.What is meant by resource leak?

Resource leakage generally refers to memory leakage but can refer to any type of system resource that isn’t managed correctly.
Memory leakage refers to memory that is no longer used but is not freed and therefore is not available for the system to reuse. Java is supposed to remove most of the memory leakage issues of other languages but it is still possible to create situations that waste memory such as java.util.Map that you never remove information from.
Resource leakage in a more general sence can refer to any system or external application finite resource. The java.awt.Graphics context is supposed to be like this because in java it is a wrapper on a system resource. If you don’t close it, it can’t be cleaned up by the system. Database resources are another example. Poor Databse code can prevent connections from being recycled by the DBMS and represent a drag on the database.

62.A note on defining floating point literal ?

A floating point literal is defined as float g = 3576.2115F.

63.A note on arrays of object references?

If the array type is CLASS then one can put objects of any subclass of the declared type into the array. The following example on sports explains the above
concept :
class sports { }
class football extends sports { }
class hockey extends sports { }
class baseball extends sports { }
sports [ ] mysports = { new football (),
new hockey (),
new baseball ()};

64.What is meant by “instanceof” comparison?

It is used for object reference variables only.You can use it to check wether an object is of a particular type.

65.when is a method said to be overloaded?

Two or more methods are defined within the same class that share the same name and their parameter declarations are different then the methods are said to be overloaded.

66.What is meant by Recursion?

It is the process of defining something in terms of itself. Interms of JAVA it is the attribute that allows a method to call itself.The following example of calculating a factorial gives an example of recursion.

class Factorial {
int fact (int n) {
int result;
if (n= 1) return 1;
result = fact(n -1) * n;
return result;
}
}
class Recursion {
Public static void main (string args[ ]) {
Factorial f = new Factorial ();
system.out.println (”Factorial of 10 is ” + f.fact(10));
}
}

67.A cool example to explain the concept of METHOD in JAVA?

Let us say you are in Mcdonalds and you order for #7 for here with medium coke. The cashier takes your order and punches it on the computer. The folks in the kitchen get the order and they get the crispy chicken and pass it on to the guy who puts a medium fries and finally a medium coke is filled and the order is served to you. In other terms if all this was supposed to be done by a robot then it could have been programmed the following way.

void #7forherewithmediumcoke( )
{
Get (crispy chicken, lattice, butter, fries, coke);
make (sandwich);
fill (coke, fries);
}

68.Java network programming

Java is a great language for network programming. IT includes UDP and TCP socket API that is arguably simpler then C/C++/PERL Socket API in Windows (Winsock) or Unix (Berklay Socket API). On the other hand it provides RMI API that could be used for higher level implementations. With RMI network operations look like method calls.
Java also had API for handling Http / SMTP (email) / FTP and CORBA. Many third party APIs are also available for accessing other network services. Apache foundation has released Http client for Java, that can replace Built in Http API in Java and supports cookies, redirects, http 1.1 and many more features.

69.What two protocols are used in Java RMI technology?

Java Object Serialization and HTTP. The Object Serialization protocol is used to marshal call and return data. The HTTP protocol is used to “POST” a remote method invocation and obtain return data when circumstances warrant.

70.What is difference between Swing and JSF?

The key difference is that JSF runs on the server in a standard Java servlet container like Tomcat or WebLogic and generates html output that is viewed on Web browsers (This client). Swing is used for creating Thick clients.

71.What is JSF?

JSF stands for Java Server Faces, or simply Faces. It is a framework for building Web-based user interfaces in Java. Like Swing, it provides a set of standard widgets such as buttons, hyperlinks, checkboxes, and so on.

72.What is CDATA ?

A predefined XML tag for character data that means “don’t interpret these characters,” as opposed to parsed character data (PCDATA), in which the normal rules of XML syntax apply. CDATA sections are typically used to show examples of XML syntax.

73.What is the difference between URL instance and URLConnection instance?

A URL instance represents the location of a resource, and a URLConnection instance represents a link for accessing or communicating with the resource at the location.

74.What Is a Socket?

A socket is one end-point of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent. Socket classes are used to represent the connection between a client program and a server program. The java.net package provides two classes–Socket and ServerSocket–which implement the client side of the connection and the server side of the connection, respectively.

75.What information is needed to create a TCP Socket?

The Local System's IP Address and Port Number. And the Remote System’s IPAddress and Port Number.

76.What are the two important TCP Socket classes?

Socket and ServerSocket. ServerSocket is used for normal two-way socket communication. Socket class allows us to read and write through the sockets. getInputStream() and getOutputStream() are the two methods available in Socket class.

77.When MalformedURLException and UnknownHostException throws?

When the specified URL is not connected then the URL throw MalformedURLException and If InetAddress? methods getByName and getLocalHost are unable to resolve the host name they throw an UnknownHostException.

78.What does RMI stand for?

It stands for Remote Method Invocation.

79.What is CORBA ?

Common Object Request Broker Architecture. A language-independent distributed object model specified by the OMG.

80.What is RMI?

RMI is a set of APIs that allows to build distributed applications. RMI uses interfaces to define remote objects to turn local method invocations into remote method invocations.

81.How do I make a connection to URL?

You obtain a URL instance and then invoke openConnection on it. URLConnection is an abstract class, which means you can’t directly create instances of it using a constructor. We have to invoke openConnection method on a URL instance, to get the right kind of connection for your URL. Eg. URL url;
URLConnection connection;
try{ url = new URL(”…”);
connection = url.openConnection();
}catch (MalFormedURLException e) { }

82.How is JSP used in the MVC model?

JSP is usually used for presentation in the MVC pattern (Model View Controller ) i.e. it plays the role of the view. The controller deals with calling the model and the business classes which in turn get the data, this data is then presented to the JSP for rendering on to the client.

83.What are context initialization parameters?

Context initialization parameters are specified by the <context-param> in the web.xml file, these are initialization parameter for the whole application and not specific to any servlet or JSP.

84.What is JNDI?

Abbreviate of Java Naming and Directory Interface.

85.What class is the top of the AWT event hierarchy?

The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy.

86.What is certificate authority ?

A trusted organization that issues public key certificates and provides identification to the bearer.

87.What is CTS ?

Compatibility test suite. A suite of compatibility tests for verifying that a J2EE product complies with the J2EE platform specification.

88.What is client-certificate authentication ?

An authentication mechanism that uses HTTP over SSL, in which the server and, optionally, the client authenticate each other with a public key certificate that conforms to a standard that is defined by X.509 Public Key Infrastruct

89.What is a output comment?

A comment that is sent to the client in the viewable page source. The JSP engine handles an output comment as un-interpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.

90.What is a Hidden Comment?

A comment that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or “comment out” part of your JSP page.

91.What is a Expression?

Expressions are act as place holders for language expression, expression is evaluated each time the page is accessed.

92.What is a Declaration?

It declares one or more variables or methods for use later in the JSP source file. A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as semicolons separate them. The declaration must be valid in the scripting language used in the JSP file.

93.What is a Scriptlet?

A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language. Within scriptlet tags, you can declare variables or methods to use later in the file, write expressions valid in the page scripting language, use any of the JSP implicit objects or any object declared with a <jsp:useBean>.

94.What are the implicit objects?

List them. Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects are:
request
response
pageContext
session
application
out
config
page
exception

95.What’s the difference between forward and sendRedirect?

When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completely with in the web container And then returns to the calling method. When a sendRedirect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.

96.What are the different scope values for the <jsp:useBean>?

The different scope values for <jsp:useBean> are:
page
request
session
application

97.Why are JSP pages the preferred API for creating a web-based client program?

Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.

98.Is JSP technology extensible?

Yes, it is. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.

99.What is difference between custom JSP tags and beans?

Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. Custom tags and beans accomplish the same goals — encapsulating complex behavior into simple and accessible forms. There are several differences:
Custom tags can manipulate JSP content; beans cannot.
Complex operations can be reduced to a significantly simpler form with custom tags than with beans.
Custom tags require quite a bit more work to set up than do beans.
Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page.
Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.

100.How is JSP used in the MVC model?

JSP is usually used for presentation in the MVC pattern (Model View Controller ) i.e. it plays the role of the view. The controller deals with calling the model and the business classes which in turn get the data, this data is then presented to the JSP for rendering on to the client.

101.What are context initialization parameters?

Context initialization parameters are specified by the <context-param> in the web.xml file, these are initialization parameter for the whole application and not specific to any servlet or JSP.

------------------------------------

Read Full