Showing posts sorted by relevance for query interview questions. Sort by date Show all posts
Showing posts sorted by relevance for query interview questions. Sort by date Show all posts

JSF Interview questions

JSF Interview questions
Q: What is the significance of properties file (Resource Bundle) and how to use this in our JSF page?
Properties file is a collection of param=value pairs. This provides a great benefit to the application like we can modify these values easily and there is no need to change the JSP file. For example, we can create "message.properties" like :
prompt=Enter Your Name:
greeting_text=Welcome In Roseindia
button_text=Submit

Q: Now edit the configuration file using <message-bundle> element which tells the application where the message resource file is located.

<application>
<message-bundle>roseindia.messages</message-bundle>
</application>

Q: Now, message resource bundle is loaded first using core tag <f:loadBundle> in view page. That loads the bundle and stores it in the request scope.
<f:loadBundle basename="roseindia.messages" var="message"/>

Q: We can now use this in our JSP like below :
<h:outputText value="#{message.prompt}"/>
Q: How can I use several configuration resource files in one single application?
JSF finds configuration file or files looking in context initialization parameter, javax.faces.CONFIG_FILES in web.xml, that specifies one or more paths to multiple configuration files for your web application. These multiple paths must be comma separeted. The important point to remember is not to register /WEB-INF/faces-config.xml file in the web.xml. Otherwise, the JSF implementation will process it twice. For example, make changes in web.xml like below :
<context-param>
<param-name>javax.faces.CONFIG_FILES</param-name>
<param-value>
/WEB-INF/test1-config.xml,/WEB-INF/test2-config.xml
</param-value>
</context-param>
Q: Can we use a different configuration resource file in place of traditional "faces-config.xml" file in our application?
JavaServer Faces technology provides an XML document for configuring resources. This file is used to register application's resources, such as validators, converters, managed beans, and navigation rules. This application configuration resource file is usually called faces-config.xml. You can have more than one application configuration resource file but it must be valid against the DTD located at http://java.sun.com/dtd/web-facesconfig_1_0.dtd. Now register the file within context-param element in web.xml file.


Q: What is JSF (or JavaServer Faces)?
A server side user interface component framework for Java™ technology-based web applications.JavaServer Faces (JSF) is an industry standard and a framework for building component-based user interfaces for web applications.

JSF contains an API for representing UI components and managing their state; handling events, server-side validation, and data conversion; defining page navigation; supporting internationalization and accessibility; and providing extensibility for all these features.

Complete Linked List with operations

Complete Linked List with operations
We have discussed the various concepts including the operations of Linked List in our previous post. So if you are unaware of these concepts, please visit our previous tutorials

Lets look at the complete Linked List creation in Java with all the operations we have discussed.
Here is the Java Code.
import org.omg.Messaging.SyncScopeHelper;

public class LinkedList {

 static LinkedNode head =  null;
 public static void main(String[] args) {
  LinkedList linkedList = new LinkedList();
  LinkedNode node = new LinkedNode(1);
  linkedList.addNode(node);
  LinkedNode node2 = new LinkedNode(2);
  linkedList.addNode(node2);
  LinkedNode node3 = new LinkedNode(3);
  linkedList.addNode(node3);
  System.out.println("After adding nodes, the list is -");
  linkedList.printList();
  int search = linkedList.searchNode(node3);
  System.out.println("Node 3 found in index " + search);
  linkedList.deleteNode(new LinkedNode(2));
  System.out.println("After deleting node 2 if present, the list is -");
  linkedList.printList();

 }

 private void deleteNode(LinkedNode node2) {
  if(head == null){
   System.out.println("List is empty");
   return;
  }
  if(head.value == node2.value){
   head = head.next;
   return;
  }else{
   LinkedNode temp1 = head;
   LinkedNode temp = head.next;
   while(temp != null && temp.value != node2.value ){
    temp1 = temp;
    temp = temp.next;
   }
   if(temp == null){
    System.out.println("The node to be delete is not found ");
   }else{
    temp1.next = temp.next;
   }
  }
 }

 private void printList() {
  if(head != null){
   LinkedNode temp = head;
   while(temp != null){
    System.out.print(temp.value + " ");
    temp = temp.next;
   }
   System.out.println();
  }else{
   System.out.println("The List is empty, Please add node elements first");
  }


 }

 private int searchNode(LinkedNode node2) {
  int position = 0;
  if(head == null){
   System.out.println("List is empty");
   return -1;
  }
  if(head.value == node2.value){
   System.out.println("Node found a position " + position);
   return -1;
  }else{

   LinkedNode temp = head;
   while(temp != null && temp.value != node2.value ){
    position++;
    temp = temp.next;
   }
   if(temp == null){
    System.out.println("Node found a position " + position);
    return -1;
   }
  }
  return position;
 }



 private void addNode(LinkedNode node) {
  if(head == null){
   head = node;
   return;
  }
  else{
   LinkedNode temp = head;
   while(temp.next != null){
    temp = temp.next;
   }
   temp.next = node;
  }
 }

}

class LinkedNode {
 protected int value;
 protected LinkedNode next;
 public LinkedNode(int value) {
  this.value = value;
  this.next = null;
 }

}

//output
//After adding nodes, the list is -
//1 2 3 
//Node 3 found in index 2
//After deleting node 2 if present, the list is -
//1 3 

That's all for Single Linked List. We will discuss about double linked list and circular linked list as part of our next tutorials. We will also discuss various interview questions related to these concepts.

Hope you like it. Please comment on any doubts.
Happy Learning !!!

JSF Interview questions

JSF Interview questions
Q: What is Managed Bean?
JavaBean objects managed by a JSF implementation are called managed beans. A managed bean describes how a bean is created and managed. It has nothing to do with the bean's functionalities.

Q: What is Backing Bean?
Backing beans are JavaBeans components associated with UI components used in a page. Backing-bean management separates the definition of UI component objects from objects that perform application-specific processing and hold data.
The backing bean defines properties and handling-logics associated with the UI components used on the page. Each backing-bean property is bound to either a component instance or its value. A backing bean also defines a set of methods that perform functions for the component, such as validating the component's data, handling events that the component fires and performing processing associated with navigation when the component activates.

Q: What are the differences between a Backing Bean and Managed Bean?

Backing Beans are merely a convention, a subtype of JSF Managed Beans which have a very particular purpose. There is nothing special in a Backing Bean that makes it different from any other managed bean apart from its usage.

What makes a Backing Bean is the relationship it has with a JSF page; it acts as a place to put component references and Event code.
Backing Beans Managed Beans
A backing bean is any bean that is referenced by a form. A managed bean is a backing bean that has been registered with JSF (in faces-config.xml) and it automatically created (and optionally initialized) by JSF when it is needed.
The advantage of managed beans is that the JSF framework will automatically create these beans, optionally initialize them with parameters you specify in faces-config.xml,
Backing Beans should be defined only in the request scope The managed beans that are created by JSF can be stored within the request, session, or application scopes

Backing Beans should be defined in the request scope, exist in a one-to-one relationship with a particular page and hold all of the page specific event handling code.In a real-world scenario, several pages may need to share the same backing bean behind the scenes.A backing bean not only contains view data, but also behavior related to that data.

Q: What is view object?
A view object is a model object used specifically in the presentation tier. It contains the data that must display in the view layer and the logic to validate user input, handle events, and interact with the business-logic tier. The backing bean is the view object in a JSF-based application. Backing bean and view object are interchangeable terms

Q: What is domain object model?

Domain object model is about the business object and should belong in the business-logic tier. It contains the business data and business logic associated with the specific business object.
Q: What is the difference between the domain object model and a view object?
In a simple Web application, a domain object model can be used across all tiers, however, in a more complex Web application, a separate view object model needs to be used. Domain object model is about the business object and should belong in the business-logic tier. It contains the business data and business logic associated with the specific business object. A view object contains presentation-specific data and behavior. It contains data and logic specific to the presentation tier.
Q: What do you mean by Bean Scope?
Bean Scope typically holds beans and other objects that need to be available in the different components of a web application.
Q: What are the different kinds of Bean Scopes in JSF?
JSF supports three Bean Scopes. viz.,
• Request Scope: The request scope is short-lived. It starts when an HTTP request is submitted and ends when the response is sent back to the client.
• Session Scope: The session scope persists from the time that a session is established until session termination.
• Application Scope: The application scope persists for the entire duration of the web application. This scope is shared among all the requests and sessions.

JSF Interview Questions - home

JSF Interview Questions - home
Q: What is JavaServer Faces?
A: JavaServer Faces (JSF) is a user interface (UI) framework for Java web applications. It is designed to significantly ease the burden of writing and maintaining applications that run on a Java application server and render their UIs back to a target client. JSF provides ease-of-use in the following ways:

• Makes it easy to construct a UI from a set of reusable UI components
• Simplifies migration of application data to and from the UI
• Helps manage UI state across server requests
• Provides a simple model for wiring client-generated events to server-side application code
• Allows custom UI components to be easily built and re-used

Most importantly, JSF establishes standards which are designed to be leveraged by tools to provide a developer experience which is accessible to a wide variety of developer types, ranging from corporate developers to systems programmers. A "corporate developer" is characterized as an individual who is proficient in writing procedural code and business logic, but is not necessarily skilled in object-oriented programming. A "systems programmer" understands object-oriented fundamentals, including abstraction and designing for re-use. A corporate developer typically relies on tools for development, while a system programmer may define his or her tool as a text editor for writing code. Therefore, JSF is designed to be tooled, but also exposes the framework and programming model as APIs so that it can be used outside of tools, as is sometimes required by systems programmers.

Q: How to pass a parameter to the JSF application using the URL string?
A: if you have the following URL: http://your_server/your_app/product.jsf?id=777, you access the passing parameter id with the following lines of java code:

FacesContext fc = FacesContext.getCurrentInstance();
String id = (String) fc.getExternalContext().getRequestParameterMap().get("id");
From the page, you can access the same parameter using the predefined variable with name param. For example,
<h:outputText value="#{param['id']}" />
Note: You have to call the jsf page directly and using the servlet mapping.

Q: How to add context path to URL for outputLink?
A: Current JSF implementation does not add the context path for outputLink if the defined path starts with '/'. To correct this problem use #{facesContext.externalContext.requestContextPath} prefix at the beginning of the outputLink value attribute. For example:
<h:outputLink value="#{facesContext.externalContext.requestContextPath}/myPage.faces">
Q: How to get current page URL from backing bean?
A: You can get a reference to the HTTP request object via FacesContext like this:

FacesContext fc = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest();
and then use the normal request methods to obtain path information. Alternatively,
context.getViewRoot().getViewId();
will return you the name of the current JSP (JSF view IDs are basically just JSP path names).

Q: How to access web.xml init parameters from java code?
You can get it using externalContext getInitParameter method. For example, if you have:
<context-param>
<param-name>connectionString</param-name>
<param-value>jdbc:oracle:thin:scott/tiger@cartman:1521:O901DB</param-value>
</context-param>
You can access this connection string with:
FacesContext fc = FacesContext.getCurrentInstance();
String connection = fc.getExternalContext().getInitParameter("connectionString");

Q: How to access web.xml init parameters from jsp page?
You can get it using initParam pre-defined JSF EL valiable.
For example, if you have:
<context-param>
<param-name>productId</param-name>
<param-value>2004Q4</param-value>
</context-param>
You can access this parameter with #{initParam['productId']} . For example:
Product Id: <h:outputText value="#{initParam['productId']}"/>

JSF Interview questions

JSF Interview questions
Q: What is the use of immediate attribute?
UIInput components and command components can set the immediate attribute to true. This attribute, when set to true, forces the conversion and validation phase to occur earlier in the lifecycle, during the apply request values phase. In other words, if some components on the page have their immediate attributes set to true, then the validation, conversion, and events associated with these components will be processed during apply request values phase.

The immediate attribute can be used for the following purposes :
a. Immediate attribute, when set to true, allows a commandLink or commandButton to process the back-end logic and ignore validation process related to the fields on the page. This allows navigation to occur even when there are validation errors.
b. To make one or more input components "high priority" for validation, so validation is performed, if there is any invalid component data, only for high priority input components and not for low priority input components in the page. This helps reducing the number of error messages shown on the page.
For example :
In the code below, button performs navigation without validating the required field.
<h:inputText id="it" required="true"/>
<t:message for="it"/>
<t:commandButton value="submit" immediate="true" action="welcome"/>
c. In the code below, validation is performed only for the first component when button is clicked in spite of being both the input components required.
<h:inputText id="it1" immediate="true" required="true"/>
<h:inputText id="it2" required="true"/>
<t:message for="it1"/>
<t:message for="it2"/>
<t:commandButton value="submit" action="welcome"/>

Q: Explain the usage of immediate attribute in an application.

Take an example of shopping cart application in which a page contain quantity fields for each product and two hyperlinks "Continue Shopping" and "Update quantities". Now we have set the immediate attributes to "false" for all the quantity fields, "true" for "Continue Shopping" hyperlink and "false" for "Update quantities" hyperlink. If we click the "Continue Shopping" hyperlink, none of the changes entered into the quantity input fields will be processed. If you click the "Update Quantities" hyperlink, the values in the quantity fields will be updated in the shopping cart.

Q: How to get the error messages displayed?
Error messages can be displayed using "message" and "messages" tag. "message" tag is used to display single error message for a particular component. The ID of the component for which the message is to be displayed is specified is specified in "for" attribute of the message tag.
Error messages for all the components can be displayed at a place using "messages" tag. It supports two layouts "table" and "list". List layout shows all the messages in a line and table layout places all the messages in a tabular format.

Q: How to avoid that all the messages are shown on the same line?

"messages" tag displays all error messages in a line because the default layout it supports is "list". This tag also supplies one more value "table" for "layout" attribute which displays all error messages in a tabular format i.e. in subsequent lines. So specifying explicitly the value of "layout" attribute to "table" can solve the problem of displaying all messages in the same line.

Q: How can we replace the JSF Standard Error Message?

Create the message bundle file and set the value of the key for a particular type of error specified in JSF specification.
For example, JSF specification supplies value "Value is required" for key "javax.faces.component.UIInput.REQUIRED" so replace the value in our message bundle file similar to the following :
javax.faces.component.UIInput.REQUIRED= Please enter the required value.
Register the message bundle within <application> tag in the configuration file (faces-config.xml) and restart the server. Now when we use message or messages tag in the view page then the value specified in this message bundle file for a particular error is displayed.

Q: How we can change the appearance of error messages in a JSF Page?
The appearance can be changed by any of the two methods :
Using "style" attribute or "styleClass" attribute. "style" attribute is used to set the CSS style definition for the component while styleClass attribute is used to set the CSS class for the component. Using "styleClass" attribute is same as html "class" attribute.

JSF Interview questions

JSF Interview questions
Q: What are the advantages of JSF?
The major benefits of JavaServer Faces technology are:
• JavaServer Faces architecture makes it easy for the developers to use. In JavaServer Faces technology, user interfaces can be created easily with its built-in UI component library, which handles most of the complexities of user interface management.
• Offers a clean separation between behavior and presentation.
• Provides a rich architecture for managing component state, processing component data, validating user input, and handling events.
• Robust event handling mechanism.
• Events easily tied to server-side code.
• Render kit support for different clients
• Component-level control over statefulness
• Highly 'pluggable' - components, view handler, etc
• JSF also supports internationalization and accessibility
• Offers multiple, standardized vendor implementations

Q: What are differences between struts and JSF?
In a nutshell, Faces has the following advantages over Struts:
• Eliminated the need for a Form Bean
• Eliminated the need for a DTO Class
• Allows the use of the same POJO on all Tiers because of the Backing Bean

The primary advantages of Struts as compared to JavaServer Faces technology are as follows:
• Because Struts is a web application framework, it has a more sophisticated controller architecture than does JavaServer Faces technology. It is more sophisticated partly because the application developer can access the controller by creating an Action object that can integrate with the controller, whereas JavaServer Faces technology does not allow access to the controller. In addition, the Struts controller can do things like access control on each Action based on user roles. This functionality is not provided by JavaServer Faces technology.
• Struts includes a powerful layout management framework, called Tiles, which allows you to create templates that you can reuse across multiple pages, thus enabling you to establish an overall look-and-feel for an application.
• The Struts validation framework includes a larger set of standard validators, which automatically generate both server-side and client-side validation code based on a set of rules in a configuration file. You can also create custom validators and easily include them in your application by adding definitions of them in your configuration file.

The greatest advantage that JavaServer Faces technology has over Struts is its flexible, extensible UI component model, which includes:
• A standard component API for specifying the state and behavior of a wide range of components, including simple components, such as input fields, and more complex components, such as scrollable data tables. Developers can also create their own components based on these APIs, and many third parties have already done so and have made their component libraries publicly available.
• A separate rendering model that defines how to render the components in various ways. For example, a component used for selecting an item from a list can be rendered as a menu or a set of radio buttons.
• An event and listener model that defines how to handle events generated by activating a component, such as what to do when a user clicks a button.
• Conversion and validation models for converting and validating component data.


Q: What are the available implementations of JavaServer Faces?
The main implementations of JavaServer Faces are:
• Reference Implementation (RI) by Sun Microsystems.
• Apache MyFaces is an open source JavaServer Faces (JSF) implementation or run-time.
• ADF Faces is Oracle’s implementation for the JSF standard.


Q: What typical JSF application consists of?
A typical JSF application consists of the following parts:
• JavaBeans components for managing application state and behavior.
• Event-driven development (via listeners as in traditional GUI development).
• Pages that represent MVC-style views; pages reference view roots via the JSF component tree.


Q: What Is a JavaServer Faces Application?
JavaServer Faces applications are just like any other Java web application. They run in a servlet container, and they typically contain the following:
• JavaBeans components containing application-specific functionality and data.
• Event listeners.
• Pages, such as JSP pages.
• Server-side helper classes, such as database access beans.
In addition to these items, a JavaServer Faces application also has:
• A custom tag library for rendering UI components on a page.
• A custom tag library for representing event handlers, validators, and other actions.
• UI components represented as stateful objects on the server.
• Backing beans, which define properties and functions for UI components.
• Validators, converters, event listeners, and event handlers.
• An application configuration resource file for configuring application resources.

JSF Interview questions

JSF Interview questions
Q: Which standard converters have their own tags?
DateTimeConverter and NumberConverter are two standard converters that have their own tags convertDateTime and convertNumber respectively that help configuring the format of the component data by configuring tag attributes.
DateTimeConverter : A component data can be converted to a Date object using convertDateTime tag within the component tag like,
<h:inputText value="#{Bean.RegisterDate}">
<f:convertDateTime pattern="MMM,dd,YYYY" />
</h:inputText>

Q: NumberConverter : Converter for dealing with numbers such as type of number, maximum integer digits, currency symbol etc.

<h:inputText id="it" value="#{Bean.value}">
<f:convertNumber maxFractionDigits="3"
type="currency"
currencySymbol="$"
maxIntegerDigits="4" />
</h:inputText>

Q: What are the ways of using standard converters of JSF?

Standard converters other than the two which have their own tags (DateTimeConverter and NumberConverter) can be used in one of the following three ways. The first one converts the model value of the component and the other two ways convert the component's local value.
a. Bind UI Component to Backing Bean Property :
Make sure that the component has its value bound to a backing bean property of the same type as the converter. For example, converting component data to a float number requires binding the component to the property like :
Float value = 0.0;
public Float getValue(){ return value;}
public void setValue(Float value) {this.value = value;}
b. Use “converter” attribute on the UI Component :
Using the converter attribute of the component tag. Just specify the fully qualified class name or ID of the converter in the converter attribute. If the component is not bound to a bean property then this option can be used. For example,
<h:inputText converter="javax.faces.Integer" />
c.
d. Use <f:converter> Tag with ConverterId Attribute :
Using converter tag within the component tag and refer the converter by specifying the ID of the converter in the convertId attribute. For example:
<h:inputText value="#{Bean.Value}" />
<f:converter converterId="Float" />
</h:inputText>

Q: When to create and use custom convertors?
The main reasons behind creating our converter are :
a. When we want to convert a component's data to a type other than a standard type
b. When we want to convert the format of the data.
Read more at http://www.roseindia.net/jsf/customconverter.shtml

Q: What are the steps of creating and using custom converter in our application?

Creating and using a custom converter requires the following steps :

Steps to follow :
a. Create a class that implements javax.faces.converter.Converter interface.
b. Import necessary packages and classes.
c. Implement two abstract methods "getAsObject()", "getAsString()" provided by Converter interface. getAsObject() method converts the String (User Input) to Object and getAsString() method converts the Object to String to send back to the page.
d. Register the converter class in configuration file (faces-config.xml) adding <converter> element. This element has child elements <converter-id> (name of the converter to be used while programming )and <converter-class> ( name of the converter class which we have created).
e. Create view page where <f:converter> tag is used with attribute "converterId" which specifies the name of the converter which we have specified in <converter-id> element of <converter> element in "faces-config.xml" file.
f. Use <h:message> tag to display the error message.
Read more at http://www.roseindia.net/jsf/customconverter.shtml
Q: What are the ways to register the custom converters in faces context?
After creating custom converter class implementing Converter interface it needs to register in the faces context. This can be done in one of the two ways :
a. Register the converter class with the id. This id is used in <f:convertrer> tag in our view page (For example, JSP).
<converter>
<converter-id>ms_Converter</converter-id>
<converter-class>ms_Converter</converter-class>
</converter>
b. Use this converter in the view page as :
<h:inputText id="input_text">
<f:converter converterId="ms_Converter" />
</h:inputText>
c.
d. Register the converter class to handle all "Email" objects, for example, automatically.
<converter> <converter-for-class>Email</converter-for-class> <converter-class>EmailConverter</converter-class>
</converter>
e. If we register the EmailConverter class to handle all Email objects automatically then there is no need to use the <f:converter/> tag in view page. Use this converter as :
<h:inputText id="phone" value="#{Bean.email}">
</h:inputText>

JSF Interview Questions

JSF Interview Questions

Q: What is the difference between JSP and JSF?
JSP simply provides a Page which may contain markup, embedded Java code, and tags which encapsulate more complicated logic / html.
JSF may use JSP as its template, but provides much more. This includes validation, rich component model and lifecycle, more sophisticated EL, separation of data, navigation handling, different view technologies (instead of JSP), ability to provide more advanced features such as AJAX, etc.
32. What is JSF life cycle and its phases?
The series of steps followed by an application is called its life cycle. A JSF application typically follows six steps in its life.
a. Restore view phase
b. Apply request values phase
c. Process validations phase
d. Update model values phase
e. Invoke application phase
f. Render response phase

Q: What is the role of Renderer in JSF? and justify the statement "JSF supports multiple client devices".
After creating JSF components, it is also necessary for each component to be rendered to the client so that it can be visible to the client’s device. Each of the tag gives rise to an associated component. A renderer is a type of class that is responsible for encoding and decoding components. Encoding displays the component while decoding translates the user’s input into components value i.e. transform it into values the component can understand.
Now a days there are many devices that are web enabled. So application developers have challenge to develop components that can work across various platforms. For example, if we have an application that works on standard web browser and we want to extend it to make it enable to work on a WAP device. So, to handle this case we need components to be rendered in more than one way. Here JSF can be helpful. This is a simple task for JSF. The solution is to develop separate renderers for the component. JSF components use different renderers depending on the device used.


Q: What is Render Kit in JSF?
Component classes generally transfer the task of generating output to the renderer. All JSF components follow it. Render kit is a set of related renderers. javax.faces.render.RenderKit is the class which represents the render kit. The default render kit contains renderers for html but it’s up to you to make it for other markup languages. Render kit can implement a skin (a look & feel). Render kit can target a specific device like phone, PC or markup language like HTML, WML, SVG. This is one of the best benefit of JSF because JSF doesn't limit to any device or markup.


Q: What is conversion and validation? and how are they related?
This is one of the phase of JSF life cycle that happens before binding the component data to the related backing bean in the Update model values phase.
Conversion is the process of transforming the component data from String to Java objects and vice versa. For example, an user enters a value (String) in an input component and this value is to store in a Date field in the backing bean then this String value is converted to a java.util.Date value when request is sent to the server and vice versa. This process is called Conversion.
Validation is the process of ensuring data contains the expected content. For example, checking the Date value is in MM./dd/YYYY format or any integer value is between 1 to 10.
The main purpose of conversion and validation is to ensure the values are of correct type and following the required criteria before updating model data. So this step allows you to focus on business logic rather than working on tedious qualifications of input data such as null checks, length qualifiers, range boundaries, etc.


Q: When automatic conversion is supplied by JSF Implementation?
JSF implementation automatically converts component data between presentation view and model when the bean property associated with the component is of one of the types supported by the component's data.
For example, If a UISelectBoolean component is associated with a bean property of type Boolean, then JSF implementation will automatically convert the data from String to Boolean.
1. Which type of converters can we use in our application?
A JSF application can use two types of converters :
1. JSF standard Converters
JSF supplies built-in converters known as standard converters. All standard converters implements javax.faces.convert.Converter interface. These converter classes are listed below :
1. BigDecimalConverter
2. BigIntegerConverter
3. BooleanConverter
4. ByteConverter
5. CharacterConverter
6. DateTimeConverter
7. DoubleConverter
8. FloatConverter
9. IntegerConverter
10. LongConverter
11. NumberConverter
12. ShortConverter
2. Custom Converter
Custom data converter is useful in in converting field data into an application-specific value object. For example,
1. String to User object.
2. String to Product object etc.

JSF Interview questions

JSF Interview questions
Q: What is the difference between JSP-EL and JSF-EL?
JSP-EL JSF-EL
In JSP-EL the value expressions are delimited by ${…}. In JSf-EL the value expressions are delimited by #{…}.
The ${…} delimiter denotes the immediate evaluation of the expressions, at the time that the application server processes the page. The #{…} delimiter denotes deferred evaluation. With deferred evaluation ,the application server retains the expression and evaluates it whenever a value is needed.
note:As of JSF 1.2 and JSP 2.1 ,the syntax of both expression languages has been unified.
Q: What are The main tags in JSF?
JSF application typically uses JSP pages to represent views. JSF provides useful special tags to enhance these views. Each tag gives rise to an associated component. JSF (Sun Implementation) provides 43 tags in two standard JSF tag libraries:
• JSF Core Tags Library.
• JSF Html Tags Library.
18. How do you declare the managed beans in the faces-config.xml file?
The bean instance is configured in the faces-config.xml file:

<managed-bean>
<managed-bean-name>login</managed-bean-name>
<managed-bean-class>com.developersBookJsf.loginBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
This means: Construct an object of the class com.developersBookJsf.loginBean, give it the name login, and keep it alive for the duration of the request.
Q: How to declare the Message Bundle in JSF?
We can declare the message bundle in two ways:
(Let’s assume com.developersBookJsf.messages is the properties file)
1. The simplest way is to include the following elements in faces-config.xml file:
<application>
<resource-bundle>
<base-name>com.developersBookJsf.messages</base-name>
<var>message</var>
</resource-bundle>
</application>

2. Alternatively, you can add the f:loadBundle element to each JSF page that needs access to the bundle:

<f:loadBundle baseName = “com.developersBookJsf.messages” var=”message”/>

Q: How to declare the page navigation (navigation rules) in faces-config.xml file ?
Navigation rules tells JSF implementation which page to send back to the browser after a form has been submitted. We can declare the page navigation as follows:
<naviagation-rule>
<from-view-id>/index.jsp</from-view-id>
<navigation-case>
<from-outcome>login</from-outcome>
<to-view-id>/welcome.jsp</to-view-id>
</navigation-case>
</naviagation-rule>
This declaration states that the login action navigates to /welcome.jsp, if it occurred inside /index.jsp.

Q: What if no navigation rule matches a given action?
If no navigation rule matches a given action, then the current page is redisplayed.

Q: What are the JSF life-cycle phases?
The six phases of the JSF application lifecycle are as follows (note the event processing at each phase): 1. Restore view
2. Apply request values; process events
3. Process validations; process events
4. Update model values; process events
5. Invoke application; process events
6. Render response

Q: Explain briefly the life-cycle phases of JSF?
1. Restore View : A request comes through the FacesServlet controller. The controller examines the request and extracts the view ID, which is determined by the name of the JSP page.
2. Apply request values: The purpose of the apply request values phase is for each component to retrieve its current state. The components must first be retrieved or created from the FacesContext object, followed by their values.
3. Process validations: In this phase, each component will have its values validated against the application's validation rules.
4. Update model values: In this phase JSF updates the actual values of the server-side model ,by updating the properties of your backing beans.
5. Invoke application: In this phase the JSF controller invokes the application to handle Form submissions.
6. Render response: In this phase JSF displays the view with all of its components in their current state.

Q: What does it mean by render kit in JSF?

A render kit defines how component classes map to component tags that are appropriate for a particular client. The JavaServer Faces implementation includes a standard HTML render kit for rendering to an HTML client.

Q: Is it possible to have more than one Faces Configuration file?
We can have any number of config files. Just need to register in web.xml.
Assume that we want to use faces-config(1,2,and 3),to register more than one faces configuration file in JSF,just declare in the web.xml file
<context-param>
<param-name>javax.faces.CONFIG_FILES</param-name>
<param-value>
/WEB-INF/faces-config1.xml,
/WEB-INF/faces-config2.xml,
/WEB-INF/faces-config3.xml
</param-value>
</context-param>

JSF Interview questions

JSF Interview questions

Q: What is the difference between JSP and JSF?
JSP simply provides a Page which may contain markup, embedded Java code, and tags which encapsulate more complicated logic / html.
JSF may use JSP as its template, but provides much more. This includes validation, rich component model and lifecycle, more sophisticated EL, separation of data, navigation handling, different view technologies (instead of JSP), ability to provide more advanced features such as AJAX, etc.
32. What is JSF life cycle and its phases?
The series of steps followed by an application is called its life cycle. A JSF application typically follows six steps in its life.
a. Restore view phase
b. Apply request values phase
c. Process validations phase
d. Update model values phase
e. Invoke application phase
f. Render response phase

Q: What is the role of Renderer in JSF? and justify the statement "JSF supports multiple client devices".
After creating JSF components, it is also necessary for each component to be rendered to the client so that it can be visible to the client’s device. Each of the tag gives rise to an associated component. A renderer is a type of class that is responsible for encoding and decoding components. Encoding displays the component while decoding translates the user’s input into components value i.e. transform it into values the component can understand.
Now a days there are many devices that are web enabled. So application developers have challenge to develop components that can work across various platforms. For example, if we have an application that works on standard web browser and we want to extend it to make it enable to work on a WAP device. So, to handle this case we need components to be rendered in more than one way. Here JSF can be helpful. This is a simple task for JSF. The solution is to develop separate renderers for the component. JSF components use different renderers depending on the device used.


Q: What is Render Kit in JSF?
Component classes generally transfer the task of generating output to the renderer. All JSF components follow it. Render kit is a set of related renderers. javax.faces.render.RenderKit is the class which represents the render kit. The default render kit contains renderers for html but it’s up to you to make it for other markup languages. Render kit can implement a skin (a look & feel). Render kit can target a specific device like phone, PC or markup language like HTML, WML, SVG. This is one of the best benefit of JSF because JSF doesn't limit to any device or markup.


Q: What is conversion and validation? and how are they related?
This is one of the phase of JSF life cycle that happens before binding the component data to the related backing bean in the Update model values phase.
Conversion is the process of transforming the component data from String to Java objects and vice versa. For example, an user enters a value (String) in an input component and this value is to store in a Date field in the backing bean then this String value is converted to a java.util.Date value when request is sent to the server and vice versa. This process is called Conversion.
Validation is the process of ensuring data contains the expected content. For example, checking the Date value is in MM./dd/YYYY format or any integer value is between 1 to 10.
The main purpose of conversion and validation is to ensure the values are of correct type and following the required criteria before updating model data. So this step allows you to focus on business logic rather than working on tedious qualifications of input data such as null checks, length qualifiers, range boundaries, etc.


Q: When automatic conversion is supplied by JSF Implementation?
JSF implementation automatically converts component data between presentation view and model when the bean property associated with the component is of one of the types supported by the component's data.
For example, If a UISelectBoolean component is associated with a bean property of type Boolean, then JSF implementation will automatically convert the data from String to Boolean.
1. Which type of converters can we use in our application?
A JSF application can use two types of converters :
1. JSF standard Converters
JSF supplies built-in converters known as standard converters. All standard converters implements javax.faces.convert.Converter interface. These converter classes are listed below :
1. BigDecimalConverter
2. BigIntegerConverter
3. BooleanConverter
4. ByteConverter
5. CharacterConverter
6. DateTimeConverter
7. DoubleConverter
8. FloatConverter
9. IntegerConverter
10. LongConverter
11. NumberConverter
12. ShortConverter
2. Custom Converter
Custom data converter is useful in in converting field data into an application-specific value object. For example,
1. String to User object.
2. String to Product object etc.

JSF Interview Questions -

JSF Interview Questions -
Q: How to terminate the session?
A: In order to terminate the session you can use session invalidate method.
This is an example how to terminate the session from the action method of a backing bean:

public String logout() {
FacesContext fc = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
session.invalidate();
return "login_page";
}
The following code snippet allows to terminate the session from the jsp page:
<% session.invalidate(); %> <c:redirect url="loginPage.jsf" />

Q: How to implement "Please, Wait..." page?
A: The client-side solution might be very simple. You can wrap the jsp page (or part of it you want to hide) into the DIV, then you can add one more DIV that appears when user clicks the submit button. This DIV can contain the animated gif you speak about or any other content.
Scenario: when user clicks the button, the JavaScript function is called. This function hides the page and shows the "Wait" DIV. You can customize the look-n-fill with CSS if you like.
This is a working example:
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="demo.bundle.Messages" var="Message"/>

<html>
<head>
<title>Input Name Page</title>
<script>
function gowait() {
document.getElementById("main").style.visibility="hidden";
document.getElementById("wait").style.visibility="visible";
}
</script>

</head>
<body bgcolor="white">
<f:view>
<div id="main">
<h1><h:outputText value="#{Message.inputname_header}"/></h1>
<h:messages style="color: red"/>
<h:form id="helloForm">

<h:outputText value="#{Message.prompt}"/>
<h:inputText id="userName" value="#{GetNameBean.userName}" required="true">
<f:validateLength minimum="2" maximum="20"/>
</h:inputText>
<h:commandButton onclick="gowait()" id="submit"
action="#{GetNameBean.action}" value="Say Hello" />
</h:form>
</div>
<div id="wait" style="visibility:hidden; position: absolute; top: 0; left: 0">
<table width="100%" height ="300px">
<tr>
<td align="center" valign="middle">
<h2>Please, wait...</h2>
</td>
</tr>
</table>
</div>
</f:view>
</body>
</html>
If you want to have an animated gif of the "Wait" Page, the gif should be reloaded after the form is just submitted. So, assign the id for your image and then add reload code that will be called after some short delay. For the example above, it might be:
<script>
function gowait() {
document.getElementById("main").style.visibility="hidden";
document.getElementById("wait").style.visibility="visible";
window.setTimeout('showProgress()', 500);
}
function showProgress(){
var wg = document.getElementById("waitgif");
wg.src=wg.src;
}
</script>
....
....
....

<img id="waitgif" src="animated.gif">
Q: How to reload the page after ValueChangeListener is invoked?
A: At the end of the ValueChangeListener, call FacesContext.getCurrentInstance().renderResponse()

Q: How to download PDF file with JSF?
A: This is an code example how it can be done with action listener of the backing bean.
Add the following method to the backing bean:
public void viewPdf(ActionEvent event) {
String filename = "filename.pdf";
// use your own method that reads file to the byte array
byte[] pdf = getTheContentOfTheFile(filename);
FacesContext faces = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().getResponse();
response.setContentType("application/pdf");
response.setContentLength(pdf.length);
response.setHeader( "Content-disposition", "inline; filename=\""+fileName+"\"");
try {
ServletOutputStream out;
out = response.getOutputStream();
out.write(pdf);
} catch (IOException e) {
e.printStackTrace();
}
faces.responseComplete();
}
This is a jsp file snippet:
<h:commandButton immediate="true" actionListener="#{backingBean.viewPdf}" value="Read PDF" />

Q: What is JSF?
Ans. JSF stands for Java Server Faces. JSF has set of pre-assembled User Interface (UI). By this it means complex components are pre-coded and can be used with ease. It is event-driven programming model. By that it means that JSF has all necessary code for event handling and component organization. Application programmers can concentrate on application logic rather sending effort on these issues. It has component model that enables third-party components to be added like AJAX.

Q: What is required for JSF to get started?
Ans. Following things required for JSF:
• JDK (Java SE Development Kit)
• JSF 1.2
• Application Server (Tomcat or any standard application server)
• Integrated Development Environment (IDE) Ex. Netbeans 5.5, Eclipse 3.2.x, etc.
Once JDK and Application Server is downloaded and configured, one can copy the JSF jar files to JSF project and could just start coding. :-)
If IDE is used, it will make things very smooth and will save your time.

Top 20 collection framework interview questions and answers in java

Top 20 collection framework interview questions and answers in java

1.Why Map interface doesn’t extend Collection interface?

  • Set is unordered collection and does not allows duplicate elements.
  • List is ordered collection allows duplicate elements.
  • Where as Map is key-value pair.
  • It is viewed as set of keys and collection of values.
  • Map is a collection of key value pairs so by design they separated from collection interface.

 

 

2.What is difference between HashMap and Hashtable?

  • Synchronization or Thread Safe 
  • Null keys and null values 
  • Iterating the values 
  •  Default Capacity

    3.Differences between comparable and comparator?

    • Comparable Interface is actually from java.lang package.
    • It will have a method compareTo(Object obj)to sort objects
    • Comparator Interface is actually from java.util package.
    • It will have a method compare(Object obj1, Object obj2)to sort objects

    4.How can we sort a list of Objects?

    •  To sort the array of objects we will use  Arrays.sort() method.
    • If we need to sort collection of object we will use Collections.sort().

     

    5.What is difference between fail-fast and fail-safe?

    • Fail fast is nothing but immediately report any failure. whenever a problem occurs fail fast system fails. 
    • in java Fail fast iterator while iterating through collection of objects sometimes concurrent modification exception will come there are two reasons for this.
    • If one thread is iterating a collection and another thread trying to modify the collection.
    • And after remove() method call if we try to modify collection object

     

    6. What is difference between Iterator ,ListIterator and Enumeration?

    • Enumeration interface implemented in java 1.2 version.So Enumeration is legacy interface.
    • Enumeration uses elements() method.
    • Iterator is implemented on all Java collection classes.
    • Iterator uses iterator() method.
    • Iterator can traverse in forward direction only.
    • ListIterator is implemented only for List type classes
    • ListIterator uses listIterator() method.

    7.What is difference between Set and List in Java?

    • A set is a collection that allows unique elements.
    • Set having no index.
    • Set allows only one null value.
    • Set having classes like :
    • HashSet
    • LinkedHashMap
    • TreeSet
    • List having index.
    • List allows n number of null values.
    • List will display Insertion order with index.
    • List having classes like :
    • Vector
    • ArrayList
    • LinkedList

    8.Differences between arraylist and vector?

    • Vector was introduced in  first version of java . that's the reason only vector is legacy class.
    • ArrayList was introduced in java version1.2, as part of java collections framework.
    • Vector is  synchronized. 
    • ArrayList is not synchronized.

    9.What are the classes implementing List interface?

    • ArrayList     
    • LinkedList     
    • Vector

    10. Which all classes implement Set interface ?

    • HashSet
    • LinkedHashSet
    • TreeSet

    11.How to make a collection thread safe?

    • Vector, Hashtable, Properties and Stack are synchronized classes, so they are thread-safe and can be used in multi-threaded environment.
    • By using Collections.synchronizedList(list)) we can make list classes thread safe.
    • By using 
      java.util.Collections.synchronizedSet()  we can make set classes thread safe.

    12.Can a null element added to a TreeSet or HashSet?

    • One null element can be added to hashset.
    • TreeSet also allow null value once.

    13. Explain Collection’s interface hierarchy?

     

    14.Which design pattern Iterator follows?

    • Iterator design pattern

    15.Which data structure HashSet implements

    • Hashset implements hashmap internally.

    16.Why doesn't Collection extend Cloneable and Serializable?

    • List and Set and queue extends Collection interface.
    • SortedMap extends Map interface.

    17.What is the importance of hashCode() and equals() methods? How they are used in Java?

    • equals() and hashcode() methods defined in "object" class. 
    • If equals() method return true on comparing two objects then hashcode() of those two objects must be same.

    18.What is difference between array & arraylist?

    • Array is collection of similar type of objects and fixed in size.
    • Arraylist is collection of homogeneous and heterogeneous elements.

    19.What is the Properties class?

    • Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key and the value is String.

    20.How to convert a string array to arraylist?

    • Using arrayList.toArray();