Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Java interview faq's


Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Java interview faq's

  1. 1. JAVA, JDBC, SERVLETS AND JSP FAQs 1. What are Encapsulation, Inheritance and Polymorphism?Encapsulation is the mechanism that binds together code and data it manipulates and keeps bothsafe from outside interference and misuse. Inheritance is the process by which one objectacquires the properties of another object. Polymorphism is the feature that allows one interface tobe used for general class actions. 2. What is OOPs?Object oriented programming organizes a program around its data, i. e. , objects and a set of welldefined interfaces to that data. An object-oriented program can be characterized as datacontrolling access to code. 3. What are Class, Constructor and Primitive data types?Class is a template for multiple objects with similar features and it is a blue print for objects. Itdefines a type of object according to the data the object can hold and the operations the objectcan perform. Constructor is a special kind of method that determines how an object is initializedwhen created. Primitive data types are 8 types and they are: byte, short, int, long, float, double,boolean, char. 4. What is an Object and how do you allocate memory to it?Object is an instance of a class and it is a software unit that combines a structured set of datawith a set of operations for inspecting and manipulating that data. When an object is createdusing new operator, memory is allocated to it. 5. What is the difference between constructor and method?Constructor will be automatically invoked when an object is created whereas method has to becalled explicitly. 6. What is the use of bin and lib in JDK?Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and allpackages. 7. What are different types of access modifiers?public: Any thing declared as public can be accessed from anywhere. private: Any thing declaredas private can’t be seen outside of its class. protected: Any thing declared as protected can beaccessed by classes in the same package and subclasses in the other packages. default modifier: Can be accessed only to classes in the same package. 8. What is final, finalize() and finally?final : final keyword can be used for class, method and variables. A final class cannot besubclassed and it prevents other programmers from subclassing a secure class to invokeinsecure methods. A final method can’t be overridden. A final variable can’t change from itsinitialized value. finalize() : finalize() method is used just before an object is destroyed and can becalled just prior to garbage collection. finally : finally, a key word used in exception handling,creates a block of code that will be executed after a try/catch block has completed and before thecode following the try/catch block. The finally block will execute whether or not an exception isthrown. For example, if a method opens a file upon exit, then you will not want the code thatcloses the file to be bypassed by the exception-handling mechanism. This finally keyword isdesigned to address this contingency. 9. What is UNICODE?Unicode is used for internal representation of characters and strings and it uses 16 bits torepresent each other.
  2. 2. 10. What is Garbage Collection and how to call it explicitly?When an object is no longer referred to by any variable, java automatically reclaims memory usedby that object. This is known as garbage collection. System. gc() method may be used to call itexplicitly. 11. What is difference between overloading and overriding?a) In overloading, there is a relationship between methods available in the same class whereas inoverriding, there is relationship between a superclass method and subclass method. b)Overloading does not block inheritance from the superclass whereas overriding blocksinheritance from the superclass. c) In overloading, separate methods share the same namewhereas in overriding, subclass method replaces the superclass. d) Overloading must havedifferent method signatures whereas overriding must have same signature. 12. What is the difference between superclass and subclass?A super class is a class that is inherited whereas sub class is a class that does the inheriting. 13. What is a package?A package is a collection of classes and interfaces that provides a high-level layer of accessprotection and name space management. 14. What is interface and its use?Interface is similar to a class which may contain method’s signature only but not bodies and it is aformal set of method and constant declarations that must be defined by the class that implementsit. Interfaces are useful for: a)Declaring methods that one or more classes are expected toimplement b)Capturing similarities between unrelated classes without forcing a class relationship.c)Determining an object’s programming interface without revealing the actual body of the class. 15. What is the difference between Array and vector?Array is a set of related data type and static whereas vector is a growable array of objects anddynamic. 16. What is the difference between exception and error?The exception class defines mild error conditions that your program encounters. Exceptions canoccur when trying to open the file, which does not exist, the network connection is disrupted,operands being manipulated are out of prescribed ranges, the class file you are interested inloading is missing. The error class defines serious error conditions that you should not attempt torecover from. In most cases it is advisable to let the program terminate when such an error isencountered. 17. What is the difference between process and thread?Process is a program in execution whereas thread is a separate path of execution in a program. 18. What is multithreading and what are the methods for inter-thread communication and what isthe class in which these methods are defined?Multithreading is the mechanism in which more than one thread run independent of each otherwithin the process. wait (), notify () and notifyAll() methods can be used for inter-threadcommunication and these methods are in Object class. wait() : When a thread executes a call towait() method, it surrenders the object lock and enters into a waiting state. notify() or notifyAll() :To remove a thread from the waiting state, some other thread must make a call to notify() ornotifyAll() method on the same object. 19. What is synchronization?Synchronization is the mechanism that ensures that only one thread is accessed the resources ata time.
  3. 3. 20. Are there any global variables in Java, which can be accessed by other part of yourprogram?No, it is not the main method in which you define variables. Global variables is not possiblebecause concept of encapsulation is eliminated here. 21. What is an applet?Applet is a dynamic and interactive program that runs inside a web page displayed by a javacapable browser. 22. What is the difference between applications and applets?a)Application must be run on local machine whereas applet needs no explicit installation on localmachine. b)Application must be run explicitly within a java-compatible virtual machine whereasapplet loads and runs itself automatically in a java-enabled browser. d)Application startsexecution with its main method whereas applet starts execution with its init method. e)Applicationcan run with or without graphical user interface whereas applet must run within a graphical userinterface. 23. What is a layout manager and what are different types of layout managers available in javaAWT?A layout manager is an object that is used to organize components in a container. The differentlayouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout and GridBagLayout. 24. How are the elements of different layouts organized?- FlowLayout: The elements of aFlowLayout are organized in a top to bottom, left to right fashion. BorderLayout: The elements ofa BorderLayout are organized at the borders (North, South, East and West) and the center of acontainer. CardLayout: The elements of a CardLayout are stacked, on top of the other, like adeck of cards. GridLayout: The elements of a GridLayout are of equal size and are laid out usingthe square of a grid. GridBagLayout: The elements of a GridBagLayout are organized accordingto a grid. However, the elements are of different size and may occupy more than one row orcolumn of the grid. In addition, the rows and columns may have different sizes. 25. What are wrapper classes?Wrapper classes are classes that allow primitive types to be accessed as objects. 26. What are Vector, Hashtable, LinkedList and Enumeration?Vector : The Vector class provides the capability to implement a growable array of objects.Hashtable : The Hashtable class implements a Hashtable data structure. A Hashtable indexesand stores objects in a dictionary using hash codes as the object’s keys. Hash codes are integervalues that identify objects.LinkedList: Removing or inserting elements in the middle of an array can be done usingLinkedList. A LinkedList stores each object in a separate link whereas an array stores objectreferences in consecutive locations.Enumeration: An object that implements the Enumeration interface generates a series ofelements, one at a time. It has two methods, namely hasMoreElements() and nextElement().HasMoreElemnts() tests if this enumeration has more elements and nextElement method returnssuccessive elements of the series. 27. What is an I/O filter?An I/O filter is an object that reads from one stream and writes to another, usually altering thedata in some way as it is passed from one stream to another. 28. What is JDBC?JDBC is a set of Java API for executing SQL statements. This API consists of a set of classesand interfaces to enable programs to write pure Java Database applications.
  4. 4. 29. What are drivers available?a) JDBC-ODBC Bridge driver b) Native API Partly-Java driver c) JDBC-Net Pure Java driver d)Native-Protocol Pure Java driver. 30. What is the difference between JDBC and ODBC?a) OBDC is for Microsoft and JDBC is for Java applications. b) ODBC can’t be directly used withJava because it uses a C interface. c) ODBC makes use of pointers which have been removedtotally from Java. d) ODBC mixes simple and advanced features together and has complexoptions for simple queries. But JDBC is designed to keep things simple while allowing advancedcapabilities when required. e) ODBC requires manual installation of the ODBC driver managerand driver on all client machines. JDBC drivers are written in Java and JDBC code isautomatically installable, secure, and portable on all platforms. f) JDBC API is a natural Javainterface and is built on ODBC. JDBC retains some of the basic features of ODBC. 31. What are the types of JDBC Driver Models and explain them?There are two types of JDBC Driver Models and they are: a) Two tier model and b) Three tiermodel Two tier model: In this model, Java applications interact directly with the database. AJDBC driver is required to communicate with the particular database management system that isbeing accessed. SQL statements are sent to the database and the results are given to user. Thismodel is referred to as client/server configuration where user is the client and the machine thathas the database is called as the server. Three tier model: A middle tier is introduced in thismodel. The functions of this model are: a) Collection of SQL statements from the client andhanding it over to the database, b) Receiving results from database to the client and c)Maintaining control over accessing and updating of the above. 32. What are the steps involved for making a connection with a database or how do you connectto a database?a) Loading the driver : To load the driver, Class. forName() method is used. Class. forName(”sun.jdbc. odbc. JdbcOdbcDriver”); When the driver is loaded, it registers itself with the java. sql.DriverManager class as an available database driver. b) Making a connection with database: Toopen a connection to a given database, DriverManager. getConnection() method is used.Connection con = DriverManager. getConnection (”jdbc:odbc:somedb”, “user”, “password”); c)Executing SQL statements : To execute a SQL query, java. sql. statements class is used.createStatement() method of Connection to obtain a new Statement object. Statement stmt = con.createStatement(); A query that returns data can be executed using the executeQuery() methodof Statement. This method executes the statement and returns a java. sql. ResultSet thatencapsulates the retrieved data: ResultSet rs = stmt. executeQuery(”SELECT * FROM sometable”); d) Process the results : ResultSet returns one row at a time. Next() method of ResultSetobject can be called to move to the next row. The getString() and getObject() methods are usedfor retrieving column values: while(rs. next()) { String event = rs. getString(”event”); Object count= (Integer) rs. getObject(”count”); 33. What type of driver did you use in project?JDBC-ODBC Bridge driver (is a driver that uses native(C language) libraries and makes calls toan existing ODBC driver to access a database engine). 34. What are the types of statements in JDBC?Statement: to be used createStatement() method for executing single SQL statementPreparedStatement — To be used preparedStatement() method for executing same SQLstatement over and over. CallableStatement — To be used prepareCall() method for multipleSQL statements over and over. 35. What is servlet?
  5. 5. Servlets are modules that extend request/response-oriented servers, such as java-enabled webservers. For example, a servlet might be responsible for taking data in an HTML order-entry formand applying the business logic used to update a company’s order database. 36. What is the difference between an applet and a servlet?a) Servlets are to servers what applets are to browsers. b) Applets must have graphical userinterfaces whereas servlets have no graphical user interfaces. 37. What is the difference between doPost and doGet methods?a) doGet() method is used to get information, while doPost() method is used for postinginformation. b) doGet() requests can’t send large amount of information and is limited to 240-255characters. However, doPost()requests passes all of its data, of unlimited length. c) A doGet()request is appended to the request URL in a query string and this allows the exchange is visibleto the client, whereas a doPost() request passes directly over the socket connection as part of itsHTTP request body and the exchange are invisible to the client. 38. What are the different servers available for developing and deploying Servlets?a) Java Web Server b) JRun g) Apache Server h) Netscape Information Server i) Web Logic 39. Is it possible to communicate from an applet to servlet and how many ways and how?Yes, there are three ways to communicate from an applet to servlet and they are: a) HTTPCommunication(Text-based and object-based) b) Socket Communication c) RMI Communication 40. Why should we go for interservlet communication?Servlets running together in the same server communicate with each other in several ways. Thethree major reasons to use interservlet communication are: a) Direct servlet manipulation - allowsto gain access to the other currently loaded servlets and perform certain tasks (through theServletContext object) b) Servlet reuse - allows the servlet to reuse the public methods of anotherservlet. c) Servlet collaboration - requires to communicate with each other by sharing specificinformation (through method invocation) 41. Is it possible to call servlet with parameters in the URL?Yes. You can call a servlet with parameters in the syntax as (?Param1 = xxx || m2 = yyy). 42. What is the difference between TCP/IP and UDP?TCP/IP is a two-way communication between the client and the server and it is a reliable andthere is a confirmation regarding reaching the message to the destination. It is like a phone call.UDP is a one-way communication only between the client and the server and it is not a reliableand there is no confirmation regarding reaching the message to the destination. It is like a postalmail. 43. What is Domain Naming Service(DNS)?It is very difficult to remember a set of numbers(IP address) to connect to the Internet. TheDomain Naming Service(DNS) is used to overcome this problem. It maps one particular IPaddress to a string of characters. For example, www. mascom. com implies com is the domainname reserved for US commercial sites, moscom is the name of the company and www is thename of the specific computer, which is mascom’s server. 44. What is URL?URL stands for Uniform Resource Locator and it points to resource files on the Internet. URL hasfour components: http://www. address. com:80/index.html, where http - protocol name, address -IP address or host name, 80 - port number and index.html - file path. 45. What is RMI and steps involved in developing an RMI object?Remote Method Invocation (RMI) allows java object that executes on one machine and to invokethe method of a Java object to execute on another machine. The steps involved in developing anRMI object are: a) Define the interfaces b) Implementing these interfaces c) Compile the
  6. 6. interfaces and their implementations with the java compiler d) Compile the server implementationwith RMI compiler e) Run the RMI registry f) Run the application46. What is a Java Bean?A Java Bean is a software component that has been designed to be reusable in a variety ofdifferent environments. 47. What is a Jar file?Jar file allows to efficiently deploying a set of classes and their associated resources. Theelements in a jar file are compressed, which makes downloading a Jar file much faster thanseparately downloading several uncompressed files. The package java. util. zip contains classesthat read and write jar files.48. What is BDK?BDK, Bean Development Kit is a tool that enables to create, configure and connect a set of set ofBeans and it can be used to test Beans without writing a code. 49. What is JSP?JSP is a dynamic scripting capability for web pages that allows Java as well as a few special tagsto be embedded into a web file (HTML/XML, etc). The suffix traditionally ends with .jsp to indicateto the web server that the file is a JSP files. JSP is a server side technology - you can’t do anyclient side validation with it. The advantages are: a) The JSP assists in making the HTML morefunctional. Servlets on the other hand allow outputting of HTML but it is a tedious process. b) It iseasy to make a change and then let the JSP capability of the web server you are using deal withcompiling it into a servlet and running it. 50. How are Servlets and JSP Pages related?JSP pages are focused around HTML (or XML) with Java codes and JSP tags inside them. Whena web server that has JSP support is asked for a JSP page, it checks to see if it has alreadycompiled the page into a servlet. Thus, JSP pages become servlets and are transformed intopure Java and then compiled, loaded into the server and executed.51. Difference between application server and web-serverThe Web serverA Web server handles the HTTP protocol. When the Web server receives an HTTP request, itresponds with an HTTP response, such as sending back an HTML page. To process a request, aWeb server may respond with a static HTML page or image, send a redirect, or delegate thedynamic response generation to some other program such as CGI scripts, JSPs (JavaServerPages), servlets, ASPs (Active Server Pages), server-side JavaScripts, or some other server-sidetechnology. Whatever their purpose, such server-side programs generate a response, most oftenin HTML, for viewing in a Web browser.The application serverAn application server exposes business logic to client applications through various protocols,possibly including HTTP. While a Web server mainly deals with sending HTML for display in aWeb browser, an application server provides access to business logic for use by client application
  7. 7. programs. The application program can use this logic just as it would call a method on an object(or a function in the procedural world).Such application server clients can include GUIs (graphical user interface) running on a PC, aWeb server, or even other application servers. The information traveling back and forth betweenan application server and its client is not restricted to simple display markup. Instead, theinformation is program logic. Since the logic takes the form of data and method calls and notstatic HTML, the client can employ the exposed business logic however it wants.In most cases, the server exposes this business logic through a component API, such as the EJB(Enterprise JavaBean) component model found on J2EE (Java 2 Platform, Enterprise Edition)application servers. Moreover, the application server manages its own resources. Such gate-keeping duties include security, transaction processing, resource pooling, and messaging.52.What is Jakarta Struts Framework?Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for thedevelopment of web based applications. Jakarta Struts is robust architecture and can be used forthe development of application of any size. Struts framework makes it much easier to designscalable, reliable Web applications with Java.53.What is ActionServlet?The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the JakartaStruts Framework this class plays the role of controller. All the requests to the server goesthrough the controller. Controller is responsible for handling all the requests.54.Describe the differences between XML and HTML.Its amazing how many developers claim to be proficient programming with XML, yet do notunderstand the basic differences between XML and HTML. Anyone with a fundamental grasp ofXML should be able describe some of the main differences outlined in the table below.55.Differences Between XML and HTMLTable 1.XML HTMLUser definable tags Defined set of tags designed for web displayContent driven Format drivenEnd tags required for well formed End tags not requireddocuments
  8. 8. Quotes required around attributes Quotes not requiredvaluesSlash required in empty tags Slash not required56.Give a few examples of types of applications that can benefit from using XML.There are literally thousands of applications that can benefit from XML technologies. The point ofthis question is not to have the candidate rattle off a laundry list of projects that they have workedon, but, rather, to allow the candidate to explain the rationale for choosing XML by citing a fewreal world examples. For instance, one appropriate answer is that XML allows contentmanagement systems to store documents independently of their format, which thereby reducesdata redundancy. Another answer relates to B2B exchanges or supply chain managementsystems. In these instances, XML provides a mechanism for multiple companies to exchangedata according to an agreed upon set of rules. A third common response involves wirelessapplications that require WML to render data on hand held devices.57.What is DOM and how does it relate to XML?The Document Object Model (DOM) is an interface specification maintained by the W3C DOMWorkgroup that defines an application independent mechanism to access, parse, or update XMLdata. In simple terms it is a hierarchical model that allows developers to manipulate XMLdocuments easily Any developer that has worked extensively with XML should be able to discussthe concept and use of DOM objects freely. Additionally, it is not unreasonable to expectadvanced candidates to thoroughly understand its internal workings and be able to explain howDOM differs from an event-based interface like SAX.58.What is SOAP and how does it relate to XML?The Simple Object Access Protocol (SOAP) uses XML to define a protocol for the exchange ofinformation in distributed computing environments. SOAP consists of three components: anenvelope, a set of encoding rules, and a convention for representing remote procedure calls.Unless experience with SOAP is a direct requirement for the open position, knowing the specificsof the protocol, or how it can be used in conjunction with HTTP, is not as important as identifyingit as a natural application of XML.59. What is a Web service?A Web services is a piece of software that you can interact with using an XML message format.This message format is usually SOAP (Simple Object Access Protocol), though alternatives exist(e.g. XML-RPC, REST).Other than SOAP, there a number of other standards that can be used by your Web services andtheir clients. The interface provided by a Web service is often defined using another XML formatcalled WSDL. A WSDL description can be shared with a Web service client in many ways, but therecommended way is to use a registry to publish it. UDDI (Universal Discovery Description andIntegration) is a specification of a Web service registry that is industry accepted. UDDI registriescan be hosted internal to a company or a group of companies and used for looking up Webservices, much the same way a LDAP directory is. There is also a global UDDI registry, called aUBR (Universal Business Registry), that is hosted by IBM, Microsoft, SAP and Fujitsu.Interestingly, a UDDI registry is itself a Web service- searching and publishing to the registry canbe done using SOAP messages.
  9. 9. Besides WSDL and UDDI, there are a number of other Web service standards and specificationsthat deal with issues like security, composing Web services, Transactions etc.Important Servlet Questions:Q: Explain the life cycle methods of a Servlet.A: The javax.servlet.Servlet interface defines the three methods known as life-cycle method. public void init(ServletConfig config) throws ServletException public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException public void destroy() First the servlet is constructed, then initialized wih the init() method. Any request from client are handled initially by the service() method before delegating to the doXxx() methods in the case of HttpServlet. The servlet is removed from service, destroyed with the destroy() methid, then garbaged collected and finalized.Q: What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?A: The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a "/" it is interpreted as relative to the current context root. The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accepts relative paths. All path must sart with a "/" and are interpreted as relative to curent context root.Q: Explain the directory structure of a web application.A: The directory structure of a web application consists of two parts. A private directory called WEB-INF A public resource directory which contains public resource folder. WEB-INF folder consists of 1. web.xml 2. classes directory 3. lib directoryQ: What are the common mechanisms used for session tracking?A: Cookies SSL sessions URL- rewritingQ: Explain ServletContext.A: ServletContext interface is a window for a servlet to view its environment. A servlet can use this interface to get information such as initialization parameters for the web applicationor servlet containers version. Every web application has one and only one ServletContext and is accessible to all active resource of that application.Q: What is preinitialization of a servlet?A: 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
  10. 10. 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.Q: What is the difference between Difference between doGet() and doPost()?A: A doGet() method is limited with 2k of data to be sent, and doPost() method doesnt have this limitation. A request string for doGet() looks like the following: doPost() method call doesnt need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and its impossible to guess the data transmitted to a servlet only looking at a request string.Q: What is the difference between HttpServlet and GenericServlet?A: A GenericServlet has a service() method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1). Both these classes are abstract.Q: What is the difference between ServletContext and ServletConfig?A: ServletContext: Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized ServletConfig: The object created after a servlet is instantiated and its default constructor is read. It is created to pass initialization information to the servlet.Important JSP QuestionsQ: What is a output comment?A: A comment that is sent to the client in the viewable page source.The JSP engine handles an output comment as uninterpreted 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. JSP Syntax <!-- comment [ <%= expression %> ] --> Example 1 <!-- This is a commnet sent to client on <%= (new java.util.Date()).toLocaleString() %> --> Displays in the page source: <!-- This is a commnet sent to client on January 24, 2004 -->Q: What is a Hidden Comment?A: 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. 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. You can use any characters in the body of the comment except the closing --%> combination.
  11. 11. If you need to use --%> in your comment, you can escape it by typing --%>. JSP Syntax <%-- comment --%> Examples <%@ page language="java" %> <html> <head><title>A Hidden Comment </title></head> <body> <%-- This comment will not be visible to the colent in the page source --%> </body> </html>Q: What is a Expression?A: An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within text in a JSP file. Like <%= someexpression %> <%= (new java.util.Date()).toLocaleString() %> You cannot use a semicolon to end an expressionQ: What is a Declaration?A: A declaration 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 they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file. <%! somedeclarations %> <%! int i = 0; %> <%! int a, b, c; %>Q: What is a Scriptlet?A: 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 1.Declare variables or methods to use later in the file (see also Declaration). 2.Write expressions valid in the page scripting language (see also Expression). 3.Use any of the JSP implicit objects or any object declared with a <jsp:useBean> tag. You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet. Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it.Q: What are implicit objects? List them?A: 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 re listed below
  12. 12. • Request • response • pageContext • session • application • out • config • page • exceptionQ: Difference between forward and sendRedirect?A: 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 completly with in the web container. When a sendRedirtect 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 completly 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.Q: What are the different scope valiues for the <jsp:useBean>?A: The different scope values for <jsp:useBean> are 1. page 2. request 3.session 4.applicationQ: Explain the life-cycle mehtods in JSP?A: THe generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces. The JspPage interface declares only two mehtods - jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the client-server protocol. However the JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests. This interface declares one method _jspService(). The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance. The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects. The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.