Friday 20 September 2013

Difference b/w Set,List and Map

Set (Interface)

  • Set is an un-ordered collection which doesn’t allows duplicate (no-duplicate) elements
  • We can iterate the values by calling iterator() method
Set s = new HashSet();
Iterator iter = s.iterator();

List (Interface)

  • List is an ordered collection which allows duplicate elements
  • We can iterate the values by calling iterator() method
List li = new ArrayList();
Iterator iter = li.iterator();

Map (Interface)

  • In Map we used to store the data in key and value pairs, we may have duplicate values but no duplicate keys
  • In Map we don’t have iterator() method, but we can get the keys by calling the method keySet()


    Map m; // insert values
    Set s = m.keySet();
    // Get Map keys into the Set and then iterate this Set object normally
    // m.keySet() returns Set object with Map keys
    Iterator iter = s.iterator();

Collections Interview Questions


Q1) What is difference between ArrayList and vector?
Ans: )
1) Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe.
2) Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.
Q2) How can Arraylist be synchronized without using Vector?
Ans)
 Arraylist can be synchronized using:
Collection.synchronizedList(List list)
Other collections can be synchronized:
Collection.synchronizedMap(Map map)
Collection.synchronizedCollection(Collection c)
Q3) If an Employee class is present and its objects are added in an arrayList. Now I want the list to be sorted on the basis of the employeeID of Employee class. What are the steps?
Ans)
 1) Implement Comparable interface for the Employee class and override the compareTo(Object obj) method in which compare the employeeID
2) Now call Collections.sort() method and pass list as an argument.
Now consider that Employee class is a jar file.
1) Since Comparable interface cannot be implemented, create Comparator and override the compare(Object obj, Object obj1) method .
2) Call Collections.sort() on the list and pass comparator as an argument.
Q4)What is difference between HashMap and HashTable?
Ans) 
Both collections implements Map. Both collections store value as key-value pairs. The key differences between the two are
1. Hashmap is not synchronized in nature but hshtable is.
2. Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.Fail-safe - “if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException�
3. HashMap permits null values and only one null key, while Hashtable doesn't allow key or value as null.
Q5) What are the classes implementing List interface?
Ans)
There are three classes that implement List interface:
1)
ArrayList : It is a resizxable array implementation. The size of the ArrayList can be increased dynamically also operations like add,remove and get can be formed once the object is created. It also ensures that the data is retrieved in the manner it was stored. The ArrayList is not thread-safe.

2)
Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized block.

3)
LinkedList: the LinkedList also implements Queue interface and provide FIFO(First In First Out) operation for add operation. It is faster if than ArrayList if it performs insertion and deletion of elements from the middle of a list.
Q6) Which all classes implement Set interface?
Ans)
 A Set is a collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. HashSet,SortedSet and TreeSet are the commnly used class which implements Set interface.
SortedSet - It is an interface which extends Set. A the name suggest , the interface allows the data to be iterated in the ascending order or sorted on the basis of Comparator or Comparable interface. All elements inserted into the interface must implement Comparable or Comparator interface.
TreeSet - It is the implementation of SortedSet interface.This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized.
HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets
Q7) What is difference between List and a Set?
Ans)
1) List can contain duplicate values but Set doesnt allow. Set allows only to unique elements.
2) List allows retrieval of data to be in same order in the way it is inserted but Set doesnt ensures the sequence in which data can be retrieved.(Except HashSet)
Q8) What is difference between Arrays and ArrayList ?
Ans)
 Arrays are created of fix size whereas ArrayList is of not fix size. It means that once array is declared as :
    1. int [] intArray= new int[6];
    2. intArray[7]   // will give ArraysOutOfBoundException.
Also the size of array cannot be incremented or decremented. But with arrayList the size is variable.
  1. Once the array is created elements cannot be added or deleted from it. But with ArrayList the elements can be added and deleted at runtime.
List list = new ArrayList();
list.add(1);
list.add(3);
list.remove(0) // will remove the element from the 1st location.
  1. ArrayList is one dimensional but array can be multidimensional.
            int[][][] intArray= new int[3][2][1];   // 3 dimensional array    
  1. To create an array the size should be known or initalized to some value. If not initialized carefully there could me memory wastage. But arrayList is all about dynamic creation and there is no wastage of memory.
Q9) When to use ArrayList or LinkedList ?
Ans)
  Adding new elements is pretty fast for either type of list. For the ArrayList, doing  random lookup using "get" is fast, but for LinkedList, it's slow. It's slow because there's no efficient way to index into the middle of a linked list. When removing elements, using ArrayList is slow. This is because all remaining elements in the underlying array of Object instances must be shifted down for each remove operation. But here LinkedList is fast, because deletion can be done simply by changing a couple of links. So an ArrayList works best for cases where you're doing random access on the list, and a LinkedList works better if you're doing a lot of editing in the middle of the list.
Source : Read More - from java.sun
Q10) Consider a scenario. If an ArrayList has to be iterate to read data only, what are the possible ways and which is the fastest?
Ans) 
It can be done in two ways, using for loop or using iterator of ArrayList. The first option is faster than using iterator. Because value stored in arraylist is indexed access. So while accessing the value is accessed directly as per the index.
Q11) Now another question with respect to above question is if accessing through iterator is slow then why do we need it and when to use it.
Ans)
 For loop does not allow the updation in the array(add or remove operation) inside the loop whereas Iterator does. Also Iterator can be used where there is no clue what type of collections will be used because all collections have iterator.
Q12) Is it better to have a HashMap with large number of records or n number of small hashMaps?
Ans) It depends on the different scenario one is working on:
1) If the objects in the hashMap are same then there is no point in having different hashmap as the traverse time in a hashmap is invariant to the size of the Map.
2) If the objects are of different type like one of Person class , other of Animal class etc then also one can have single hashmap but different hashmap would score over it as it would have better readability.
Q13) Why is it preferred to declare: List<String> list = new ArrayList<String>(); instead of ArrayList<String> = new ArrayList<String>();
Ans)
 It is preferred because:
  1. If later on code needs to be changed from ArrayList to Vector then only at the declaration place we can do that.
  2. The most important one – If a function is declared such that it takes list. E.g void showDetails(List list);
    When the parameter is declared as List to the function it can be called by passing any subclass of List like ArrayList,Vector,LinkedList making the function more flexible
Q14) What is difference between iterator access and index access?
Ans) Index based access allow access of the element directly on the basis of index. The cursor of the datastructure can directly goto the 'n' location and get the element. It doesnot traverse through n-1 elements.
In Iterator based access, the cursor has to traverse through each element to get the desired element.So to reach the 'n'th element it need to traverse through n-1 elements.
Insertion,updation or deletion will be faster for iterator based access if the operations are performed on elements present in between the datastructure.
Insertion,updation or deletion will be faster for index based access if the operations are performed on elements present at last of the datastructure.
Traversal or search in index based datastructure is faster.
ArrayList is index access and LinkedList is iterator access.
Q15) How to sort list in reverse order?
Ans) 
To sort the elements of the List in the reverse natural order of the strings, get a reverse Comparator from the Collections class with reverseOrder(). Then, pass the reverse Comparator to the sort() method.
List list = new ArrayList();
Comparator comp = Collections.reverseOrder();
Collections.sort(list, comp)
Q16) Can a null element added to a Treeset or HashSet?
Ans) 
A null element can be added only if the set contains one element because when a second element is added then as per set defination a check is made to check duplicate value and comparison with null element will throw NullPointerException.
HashSet is based on hashMap and can contain null element.
Q17) How to sort list of strings - case insensitive?
Ans)
 using Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
Q18) How to make a List (ArrayList,Vector,LinkedList) read only?
Ans) 
A list implemenation can be made read only using Collections.unmodifiableList(list). This method returns a new list. If a user tries to perform add operation on the new list; UnSupportedOperationException is thrown.
Q19) What is ConcurrentHashMap?
Ans) 
A concurrentHashMap is thread-safe implementation of Map interface. In this class put and remove method are synchronized but not get method. This class is different from Hashtable in terms of locking; it means that hashtable use object level lock but this class uses bucket level lock thus having better performance.
Q20) Which is faster to iterate LinkedHashSet or LinkedList?
Ans) LinkedList.
Q21) Which data structure HashSet implements
Ans)
 HashSet implements hashmap internally to store the data. The data passed to hashset is stored as key in hashmap with null as value.
Q22) Arrange in the order of speed - HashMap,HashTable, Collections.synchronizedMap,concurrentHashmap
Ans) HashMap is fastest, ConcurrentHashMap,Collections.synchronizedMap,HashTable.
Q23) What is identityHashMap?
Ans)
 The IdentityHashMap uses == for equality checking instead of equals(). This can be used for both performance reasons, if you know that two different elements will never be equals and for preventing spoofing, where an object tries to imitate another.
Q24) What is WeakHashMap?
Ans)
 A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently than other Map implementations.





























Thursday 19 September 2013

Selenium WebDriver Interface

The interface WebDriver represents the main interface for testing a web browser instance. If you are using Selenium 2 then it is highly recommended to use the WebDriver instance because of the benefits suggested in my previous posts.
This interface provides most of the basic requirements for testing a web application. Normally the testing of a web application requires either one or all of the following three functions:

  • Controling The browser
  • Selecting the WebElement
  • Debugging aids
The methods in this class provide solutions to the requirements in all the three categories mentioned above:
· Control of the browser:
    • get(): Loads the web page rendered by the URL string passed to this method. Similar results can be obtained by using WebDriver.Navigation.to(String)
    • navigate():Loads the web page rendered by the URL and access browser history
    • close(): Closes the ‘Current’ browser window
    • quite(): Closes ‘All’ browser windows associated with the webDriver instance
    • switchTo(): Changes current window and redirects all commands to the new ‘current’ window (example: switchTo().window(String))
    • manage(): Enables access to browser menu items, such as add cookies, logs etc 
        
· Selection of WebElement:
    • findElement(): Returns the first ‘Webelement’ found
    • findElements(): Returns all the ‘WebElements’ found in the current web page
· Debugging aids:
    • getCurrentUrl(): Returns the current URL loaded in the browser session
    • getPageSource(): Returns HTML source of the current page loaded in the browser
    • getTitle(): Returns the title of current page
    • getWindowHandle(): Return unique string identifier of the current window in the driver instance
    • getWindowHandles(): Return identifiers of all the windows in the driver instance

Comparative analysis of the WebDrivers’ Drivers

While working with selenium webdriver you have an option to choose from multiple webdrivers, such as HtmlUnitDriver, FirefoxDriver, InternetExplorerDriver, ChromeDriver and OperaDriver. Each one of them is a separate implementation of the WebDriver interface provided by Selenium. All of them have unique advantages and disadvantages because of the implementation differences for catering to different requirements. It is good to know the comparative advantages and disadvantages of each one before picking one of them.
The first major point to note is that there are two groups of driver implementations. One of those that invoke the actual browser installed on your system and the other that emulates the behavior of another browser. FirefoxDriver, InternetExplorerDriver, ChromeDriver and OperaDriver invoke the actual browser installed on the machine; however the HtmlUnitDriver emulates other browsers JS behavior. 

HtmlUnitDriver

 HtmlUnit is a java based framework for testing webApps basically a wrapper around ‘HttpClient’ by Jakarta. HtmlUnit provides UI-Less emulation of browsers to test web applications. The HtmlUnit APIs let you do the typical functions performed in an actual web browser, such as click links, fill forms, invoke web pages, submit values etc. HtmlUnit supports java script and complex AJAX libraries. Javascript is disabled in the HtmlUnitDriver by default, however if it can be enabled if required. The mechanism to enable javascript with the HtmlUnitDriver is as follows:

HtmlUnitDriver MyhtmlDriver = new HtmlUnitDriver();
 MyhtmlDriver.setJavascriptEnabled(true);
OR
HtmlUnitDriver MyhtmlDriver = new HtmlUnitDriver(true);

When enabled, the HtmlUnitDriver emulates the java script behavior of Internet Explorer by default. However we can direct the HtmlUnitDriver to emulate the JavaScript behavior of the browser of our choice by invoking the constructor that accepts the browser version. This can be done as follows:
HtmlUnitDriver MyhtmlDriver = new HtmlUnitDriver(BrowserVersion.Firefox_2);

Internet Explorer Driver

 The IE driver class ‘InternetExplorerDriver.class’ is located at ‘\org\openqa\selenium\ie\’ directory in the ‘selenium-server-standalone-2.7.0.jar’. To use the InternetExplorerDriver all you need to do is to have the selenium-server-standalone-2.7.0.jar in your CLASSPATH.  The IE driver runs only on windows and supports both 32-bit and 64-bit operations. Depending on the thread that instantiates the InternetExplorerDriver corresponding version of the IE is launched i.e. if the thread instantiating driver is running in 32-bit then the 32-bit version of the IE will be launched and if the thread instantiating driver is running in 64-bit then the 64-bit version of the IE will be launched.

The Internet Explorer driver uses the native or OS-level events to perform various functions on the browser, such as inputs from keyboard and mouse. This approach has both advantages and limitations both. The advantages are that it bypasses the limitations of the Javascript sandbox but there can be issues like the browser window under test might be out of focus.

Firefox Driver

selenium-server-standalone-X.X.X.jar’ contains all the drivers implementing the WebDriver interface of selenium. Hence the 'FirefoxDriver.class' can be found in the ‘\org\openqa\selenium\firefox directory in the selenium-server-standalone-X.X.X.jar. The driver when instantiated is added as an extension to the firefox profile. You can specify the profile with which you want to load firefox session. If no profile is specified then the driver creates an anonymous profile by default.
A profile can be created for the firefox driver as follows:

FirefoxProfile myProfile = new FirefoxProfile();

Multiple operations can be performed on the newly created profile, such as:

myProfile.addExtension(File);
myProfile.clean();
myProfile.getPort();
myProfile.setPort(int port);
myProfile.enableNativeEvents();
myProfile.setPreference(String key, String value); etc...

After creating the your profile you can pass the profile while creating the driver instance as follows:
WebDriver myFireFoxDriver = new FirefoxDriver(myProfile);

This driver is faster than the InternetExplorerDriver and executes the test in real Firefox web browser.

Wednesday 4 September 2013

SeleniumQuestions..


  1. Which of these WebDriver interface methods is used to open a URL in the browser?
    A)get
    b)navigate().to
    c)Any of the above
    d)None of the above
    ans c
  2. What is the difference between WebDriver close and quit methods?
    a)Nothing, these methods are interchangeable.
    b)close method clears the browser memory and the quit method closes the browser window.
    c)close method closes the browser but the quit method additionally removes the connection to the server.
    d)close method closes the main browser window but the quit method closes all the browser windows including popups.
    Ans :d


  1. When invoked on a web element, what does the submit method do?
a)It is used to submit a form and it works on any web element.
b)It is used to submit a form but it works only on the web element whose type is "submit".
c)It is the same as the click method.
d)There is no submit method for a web element.
Ans:a
4. Which WebDriver method is used to change focus to an alert, a web element or a browser window?
a)changeFocus
b)switchTo
c)goTo
d)setFocus
Ans:b
5 . What functionality does WebDriver support on browser cookies?
a)add and delete an individual cookie
b)delete all cookies
c)any of the above
d)none of the above
ans:c
6. What is the scope of an implicit wait?
a)All instances of WebDriver
b)Current WebDriver instance
c)Current expected condition
d)Current web element
ans:b
7. What kind of application is the Selenium IDE?
a)Windows application
b)Web application
c)Firefox add-on
d)None of these
ans:c

8. A Selenium IDE test case has three columns, Command, Target and Value. What data is stored in the Target column?
a)Element or location where the command is executed
b)Test step execution result
c)[Optional] purpose of the test step
d)None of these
ans: a
9. By default, in which format does the Selenium IDE save a test case?
a)In proprietary format
b)As HTML
c)As Java source code
d)As Ruby or Python or C# code depending on user options selected during installation
ans:b
9. What features are available in Selenium IDE to debug an automated test case?
a)Toggle Breakpoint
b)Pause/ Resume
c)Step
d)All of these
ans:d
10. What is the Selenium print command?
a)echo
b)print
c)alert
d)System.out.println()
ans: a
11. What is the difference between a command and the same command with "AndWait" (e.g. click and clickAndWait commands)?
a)Selenium waits indefinitely for the result of the "AndWait" command.
b)It waits for the result of the "AndWait" command but only for 30 seconds (default timeout).
c)It waits for the result of the "AndWait" command but only up to a maximum of 30 seconds (default timeout).
d)Some commands do not have an "AndWait" command, so this question is incorrect.
Ans: c
12. What is the correct syntax to access the value of a Selenium variable called name?
a)name
b)$name
c){name}
d)${name}
ans:d
13. What is the difference between assert and verify commands?
a)Assert commands are more uncommon than verify commands.
b)Typically, an assert command is followed by verify command(s).
c)A failed assert command stops the test but a failed verify command does not do so.
d)All of the above
ans: d
14. In which associative array does Selenium store all of a test case's variables and their respective values?
a)Array
b)storedVars
c)var
d)There is no such array in Selenium.
Ans b

15. Where can you create your own Selenium commands?
a)This is not possible.
b)In user-extensions.js file
c)In any JavaScript file, but the preferred name is user-extensions.js for consistency
d)In any Java, C#, Python, Ruby, PHP or Perl file
ans:c
16. What URLs does the Selenium open command allow?
a)Only the base URL
b)Any URL relative to the base URL
c)Any absolute URL
d)Any of the above
ans: d
17. What is the purpose of the Find button?
a)Highlight the element that is given in the locator
b)Search the appropriate command for the given target
c)Find the current value of the target
d)None of the above
ans:a
18. Which one of the following statements is incorrect?
a)Breakpoint and Start point cannot both exist on the same command.
b)The shortcut key for Breakpoint is B and for Start point is S.
c)A Breakpoint or a Start point cannot be put on a comment line.
d)Both Breakpoint and Start point are used in debugging the test case.
Ans:c

19. Which add-on is commonly used with Selenium IDE to identify individual elements on a web page?
a)FirePath
b)Firebug
c)XPath
d)No add-on is required. You can view the Page Source and locate any element within the HTML code easily.
Ans b(Firebug is the required add-on. FirePath is only a Firebug extension that shows XPath.)

20. Why are relative XPaths preferred over absolute XPaths as locators?
a)For non-root elements, absolute XPaths are longer and slow down the test automation.
b)Absolute XPaths fail if any part of the path changes even slightly.
c)Relative XPaths are the default in Selenium.
d)None of the above
ans: b

21. Which of the following is an incorrect target for pattern matching as in verifyTextPresent command?
a)glob:Customer*Subscriber
b)You entered the character, ?
c)regexp:[JFM]
d)exact:* Summary
ans:D(The exact pattern does not use any special character for patterns.)

22. What is the best way to handle asynchronous data retrieval from the server as in AJAX applications?
a)Run the test case at the slowest speed.
b)Use the pause command.
c)Use the "AndWait" commands.
d)Use the "waitFor" commands.
Ans:d

23. What happens when the application creates a JavaScript alert during test case play?
a)The alert is suppressed by Selenium..
b)If there is no command to handle the alert, the play is stopped with an error.
c)If the alert is handled with assertAlert, assertAlertPresent or verifyAlert, no alert is displayed and there is no error.
d)Each of the above
ans :D

24. What is data parameterization?
a)Using variable test data in place of fixed test data values
b)Using different number of test data values when executing the same test case
c)Putting pre-requisites for the test case to execute
d)Limiting the test case execution only when certain conditions exist
ans:a

25. Which of the following statements is correct for a Test Suite?
a)A Test Suite is a comma separated values file.
b)A Test Suite is an HTML file containing a table with a single column.
c)The test cases of a Test Suite must be placed in the same folder as the Test Suite.
d)A new Test Suite can have only new test cases.
Ans:b
26. What are the different modes that Selenium uses?
a)*iehta
b)*firefox and *iexplore
c)*chrome
d)All of the above
ans:d
27. How do you start the browser?
a)selenium.Start()
b)get start()
c)selenium.server start()
d)None of the above
ans :a
28. Do you need to have Selenium .jar files as a dependency of your tests?
a)Yes
b)No
c)Yes, but as a good practice only
d)No Selenium jar file is provided with Selenium RC.
Ans:a
29. How many parameters does the Selenium object take when using DefaultSelenium?
a)2
b)3
c)4
d)6
ans:c
30. How do you start selenium rc server with user extensions?
a)java -jar selenium-server.jar
b)java -jar selenium-server.jar -userExtensions user-extensions.js
c)java -jar selenium-server.jar user-extensions.js
d)java -jar selenium-server.jar user-extensions.js -h
ans:B

31. Which Selenium command do you use to run commands in slow motion in Selenium RC?
a)selenium.setSpeed()
b)selenium.speed()
c)selenium.serverSpeed()
d)None of the above
ans:a
32. Which command is used to get the alert box?
a)assertequals(selenium.getAlert())
b)selenium.getAlert()
c)selenium.alertBox()
d)selenium.click()
ans:b
33. Which command is used for verifying if a web element exists?
a)selenium.isElementPresent(String locator)
b)assertTrue(Selenium.isElementPresent())
c)selenium.ElementPresent()
d)None of the above
ans:a
34. Which command is used for typing in a textbox?
a)selenium.input()
b)selenium.type(String locator, String value)
c)assertequals(selenium.getValues())
d)selenium.textInput()
ans:b
35. What is the command to load a page?
a)selenium.waitForPageToLoad(String timeoutInMilliseconds)
d)selenium.waitForPageToLoadInt timeoutInMilliseconds
c)selenium.waitForPageToLoad(timeoutInMilliseconds)
d)selenium.waitForPageToLoad()
ans a