Tuesday, 22 September 2015

Binary Search Program in Java

public class BinarySearch {

 public static void main(String args[])
 {
  int i, first, last, middle, n, search, array[];
  Scanner in = new Scanner(System.in);
  System.out.println("Enter number of elements-");

  n = in.nextInt();
  array = new int[n];

  System.out.println("Enter " + n + " integers -");

 for (i = 0; i < n; i++)
 {
  array[i] = in.nextInt();
 
 }

 System.out.println("Enter value to find -");
 search = in.nextInt();

 first = 0;

 last = n - 1;

 middle = (first + last)/2;

 while( first <= last )
 {
  if ( array[middle] < search )
  {
  first = middle + 1;
  }
  else if ( array[middle] == search )
  {
   System.out.println(search + " found at location " + (middle + 1) + ".");
   break;
  }
  else
  {
   last = middle - 1;
  }
  middle = (first + last)/2;
 }
 if ( first > last )
 {
  System.out.println(search + " is not present in the list.\n");
 }
}
}

SingleTon Class in java

The class which has only instance/object  through out the application is known as SingleTon class .


Code of SingleTon class creation
-------------------------------------------------------


//Creation of SingletonClass

public class SingleTonTest {

 private static SingleTonTest instance = null;

 //create an object of SingleObject
 // private static SingleObject instance = new SingleObject();
 //make the constructor private so that this class cannot be instantiated

 private SingleTonTest(){

 }
 //Get the only object available

 public static SingleTonTest getInstance() {

  if(instance == null) {
   instance = new SingleTonTest(); 
  }
  return instance;

 }

 public void showMessage(){
  System.out.println("Hello World!");
 }

 public static void main(String[] args) {

 SingleTonTest object = SingleTonTest.getInstance();
 System.out.println(object);

 SingleTonTest obj = SingleTonTest.getInstance();
 System.out.println(obj);
 //both will print same refrence no.

 }
}

If Child class overload the method of Parent class which throws exception, and if a new exception will be add in method signature with throws in child class overload method, then what will happen ?



Struts Interview Questions Answer


Question 1: What is Struts? Why you have used struts in your application or project. 

Ans: Struts is based on MVC pattern which is model view Controller pattern. 

The keyword to answer this Struts interview questions is MVC design pattern, Front Controller Pattern and better flow management which mostly interviewer are looking to hear.  

Question 2: What are the main classes which are used in struts application?

Ans 2: Main classes in Struts Framework are:

Action servlet: it’s a back-bone of web application . it’s a controller class responsible for handling the entire request. The Action Servlet selects the Action class for incoming http request defined under the action mapping tag in the struts config.xml file.
Action class: Action class should extend org.apache.struts.action.Action class. Should override the execute method of the Action class. Here we write  all the business logic and call model class (Dao class) of the application to get the data from the bean and store the processed data and return the result or error depending upon the situation.
Action Form: it’s a java bean which represents our forms and associated with action mapping. And it also maintains the session state its object is automatically populated on the server side with data entered from a form on the client side. 

Action Mapping: using this class we do the mapping between object and Action.

ActionForward: this class in Struts is used to forward the result from controller to destination.

Types of action class:

We have following types of action classes in struts:
  • Action - The basic action class in which we implement our business logic.
  • Include Action - Similar as include page directive in jsp.
  • Forward Action - Used in case we need to forward the request from one JSP to another. If we directly forward the request from one jsp .  it violates the MVC architecture. Hence an action class is used to do this job.
  • Dispatch Action - Handles multiple operations in multiple methods. It is better to have one method per operation instead of merging the entire business logic in a single execute method of an action class.
  • Look up Dispatch Action -
  • Switch Action - used to switch between different modules in struts application.

Question 3: How exceptions are handled in Struts application? 

Ans: This is little tough Struts interview question though looks quite basic not every candidate knows about it. Below is my answer of this interview questions on Struts:

There are two ways of handling exception in Struts:

Programmatically handling: using try {} catch block in code where exception can come and flow of code is also decided by programmer .its a normal java language concept. 

Declarative handling: There are two ways again either we define <global-Exception> tag inside struts config.xml file

<exception

      key="stockdataBase.error.invalidCurrencyType"

      path="/AvailbleCurrency.jsp"

      type="Stock.account.illegalCurrencyTypeException">

</exception>

Programmatic and Declarative way is some time also asked as followup questions given candidate’s response on knowledge on Struts. 

Key: The key represent the key present in MessageResource.properties file to describe the exception.

Type: The class of the exception occurred.
Path: The page where the controls are to be followed is case exception occurred.
 

Question 4: How validation is performed in struts application? 

Ans: Another classic Struts interview question it’s higher on level than previous interview questions because it’s related to important validation concept on web application. In struts validation is performed using validator framework, Validator Framework in Struts consist of two XML configuration files.

1. validator-rules.xml file: which contains the default struts pluggable validator definitions. You can add new validation rules by adding an entry in this file. This was the original beauty of struts which makes it highly configurable.

2. Validation.xml files which contain details regarding the validation routines that are applied to the different Form Beans.

These two configuration file in Struts should be place somewhere inside the /WEB-INF folder of the application to keep it safe from client and make it available in Classpath. 

<!--  Validator plugin -->
< plug-in className="org.apache.struts.validator.ValidatorPlugIn">
  < set-property
  property="pathnames"
   value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
< /plug-in>
Now the next step towards validation is create error messages inside the message resource property file which is used by validator framework.
 
Message resource Contain: 

1. CurrencyConverterForm.fromCurrency = From Currency

2. CurrencyConverterForm.toCurrency=To currency

3. errors.required={0} is required.
 

Then validation rules are defined in validation.xml for the fields of form on which we want desire validation

Form bean code that extend DynaValidatorForm

Eg; < form-beans>

<form-bean name="CurrencyConverterForm" type="org.apache.struts.validator.DynaValidatorForm">

<form-property name="fromCurrency" type="java.lang.double" />

<form-property name="toCurrecny" type="java.lang.double" />

</form-bean>

</form-beans>

Validation.xml file contains 

<form-validation>

<formset>

<form name=" CurrencyConverterForm ">

<field property=" fromCurrency " depends="required">

<arg key=" CurrencyConverterForm. fromCurrency "/>

</field>

<field property=" toCurrecny " depends="required ">

<arg key=" CurrencyConverterForm.toCurrency "/>

</field>

</form>

</formset>

</form-validation> 

To associate more than one validation rule to the property we can specify a comma-delimited list of values. The first rule in the list will be checked first and then the next rule and so on. Answer of this Struts questions gets bit longer but it’s important to touch these important concept to make it useful. 

Question 5: What is the Difference between DispatchAction and LookupDispatchAction in Struts Framework? 

Dispatch Action
LookupDispatchAction
It’s a parent class of  LookupDispatchAction
Subclass of Dispatch Action
DispatchAction provides a mechanism for grouping a set of related functions into a single action, thus eliminating the need to create separate actions for each function.
An abstract Action that dispatches to the subclass mapped executes method. This is useful in cases where an HTML form has multiple submit buttons with the same name. The button name is specified by the parameter property of the corresponding ActionMapping.
If not using Internalization functionality then dispatch action is more useful.
Lookup Dispatch Action is useful when we are using Internalization functionality
DispatchAction selects the method to execute depending on the request parameter value which is configured in the xml file.
LookupDispatchAction looks into the resource bundle file and find out the corresponding key name. We can map this key name to a method name by overriding the getKeyMethodMap() method.
DispatchAction is not useful for I18N
LookupDispatchAction is used for I18N

 
Question 6: How you can retrieve the value which is set in the JSP Page in case of DynaActionForm? 

Ans: DynaActionForm is subclass of ActionForm that allows the creation of form beans with dynamic sets of properties, without requiring the developer to create a Java class for each type of form bean. DynaActionForm eliminates the need of FormBean class and now the form bean definition can be written into the struts-config.xml file. So, it makes the FormBean declarative and this helps the programmer to reduce the development time. 

For Example: we have a CurrencyConverterForm and we don't want a java class.
CurrencyConverterForm has properties fromCurrency, toCurrency

in the struts-config.xml file, declare the form bean

<form-bean name=" CurrencyConverterForm "
type="org.apache.struts.action.DynaActionForm">
< form-property name=" fromCurrency " type="java.lang.String"/>
< form-property name=" toCurrency " type="java.lang. String "/>
< /form-bean>

Add action mapping in the struts-config.xml file:
<action path="/convertCurrency" type="com.techfaq.action.ConvertCurrencyAction"
name=" CurrencyConverterForm "
scope="request"
validate="true"
input="/pages/ currencyConverterform.jsp">

< forward name="success" path="/jsp/success.jsp"/>
< forward name="failure" path="/jsp/error.jsp" />

< /action>

In the Action class.


public class ConvertCurrencyAction extends Action
{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{

DynaActionForm currencyConverterForm = (DynaActionForm)form;


// by this way we can retrieve the value which is set in the JSP Page


String fromCurrency = (String) currencyConverterForm.get("fromCurrency ");
String toCurrency = (String) currencyConverterForm.get("toCurrency ");
return mapping.findForward("success");
}
}
}

In the JSP page


<html:text property=" fromCurrency " size="30" maxlength="30"/>
< html:text property=" toCurrency " size="30" maxlength="30"/>
 

Question 7: what the Validate () and reset () method does? 

Ans: validate() : validate method is Used to validate properties after they have been populated, and this ,method is  Called before FormBean is passed  to Action. Returns a collection of ActionError as ActionErrors. Following is the method signature for the validate() method.

public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
                        
ActionErrors errors = new ActionErrors();
if ( StringUtils.isNullOrEmpty(username) && StringUtils.isNullOrEmpty(password)){
     errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.usernamepassword.required"));
}
return errors;
}

reset(): reset() method is called by Struts Framework with each request that uses the defined ActionForm. The purpose of this method is to reset all of the ActionForm's data members prior to the new request values being set.

Example :
public void reset(ActionMapping mapping, HttpServletRequest request) {
this.password = null;
this.username = null;
}

Set null for every request.  

Question 8: How you will make available any Message Resources Definitions file to the Struts Framework Environment? 

Ans: Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through < message-resources / > tag. Example: < message-resources parameter= MessageResources / > 

Message resource definition files can available to the struts environment in two ways
1. using web.xml as
< servlet>
< servlet-name>action<servlet-name>
servlet-class>org.apache.struts.action.ActionServlet<servlet-class>
< init-param>
< param-name>application<param-name>
< param-value>resource.Application<param-value>
< /servlet>

2.
< message-resource key="myResorce" parameter="resource.Application" null="false">

 
Question 9: What configuration files are used in Struts?

Ans: ApplicationResources.properties and struts-config.xml these two files are used to between the Controller and the Model. 

Question 10: Explain Struts work Flow?

Ans:

1) A request comes in from a Java Server Page into the ActionServlet.

2) The ActionServlet having already read the struts-config.xml file, knows which form bean relates to this JSP, and delegates work to the validate method of that form bean. 

3) The form bean performs the validate method to determine if all required fields have been entered, and performs whatever other types of field validations that need to be performed. 

4) If any required field has not been entered, or any field does not pass validation, the form bean generates ActionErrors, and after checking all fields returns back to the ActionServlet. 

 5) The ActionServlet checks the ActionErrors that were returned from the form beans validate method to determine if any errors have occurred. If errors have occurred, it returns to the originating JSP displaying the appropriate errors. 

6) If no errors occurred in the validate method of the form bean, the ActionServlet passes control to the appropriate Action class. 

7) The Action class performs any necessary business logic, and then forwards to the next appropriate action (probably another JSP). 

If we overload a method and we pass String in one method and Object in another So while calling if we pass ‘null’ then which method will be called and why?

class A
{
 public void B()
 {
     System.out.println("B");
 }
 public void str(Object s)
 {
  System.out.println("==output="+s);
 }

 public void str(String s)
 {
  System.out.println("=Output 2=="+s);
 }
 public void str(int s)
 {
  System.out.println("=i=="+s);
 }

}

public class Test extends A{

 public void B()
 {
  System.out.println("BB");
 }
 public static void main(String args[])
 {
  A a=new Test();

  a.B();

  a.str(null);
  a.str("ss");

// If we overload a method and we pass String in one method and Integer in another So while calling if we pass ‘null’ then which method will be called and why?


  a.str(null);
  a.str(5);

 }
}


OUTPUT

BB

=output==null

=output2==ss

=Output==null

=i==5

Wednesday, 9 September 2015

Java- Differences between Iterator and ListIterator



Iterator
ListIterator
1)      Iterator traverses the elements in forward direction only.
ListIterator traverses the elements in backward and forward directions both.
2)      Iterator can be used in List, Set and Queue.
ListIterator can be used in List only.

java- differences between Comparable and Comparator


Comparable
Comparator
1)      Comparable provides single sorting sequence.
In other words, we can sort the collection on the basis of single element such as id or name or price etc.
 Comparator provides multiple sorting sequence.
 In other words, we can sort the collection on the  basis of multiple elements such as id, name and  price etc.
2) Comparable affects the original class i.e., actual class is modified.
 Comparator doesn't affect the original class i.e.  actual class is not modified.

3) Comparable provides compareTo() method to sort elements.
 Comparator provides compare() method to sort  elements. 

4) Comparable is found in java.lang package.
 Comparator is found in java.util package.

5) We can sort the list elements of Comparable type by Collections.sort(List) method.
 We can sort the list elements of Comparator type  by Collections.sort(List,Comparator) method.