Search

Sunday, May 31, 2015

Selenium WebDriver Advanced Tutorials Part 7

This section of webdriver tutorial Includes MySQL Database Testing With Selenium WebDriver software testing tool tutorials, IEDriver tutorials for software testing, ChromeDriver tutorials and few add-on related tutorials for software testing process.


Learn all bellow given tutorials step by step. It will help you to implement in your real project.

MySQL Database Testing With Selenium WebDriver
  1. Download And Install MySQL For Database Testing Using Selenium
  2. MySQL - Creating Data Tables To Store Data
  3. Fetching Data From MySQL Database Table For WebDriver Test
  4. Fetching Data From MySQL Database Table With Where Clause
  5. Update Record In Database For Selenium WebDriver Test
IEDriver
  1. Running WebDriver Test In Internet Explorer Browser
  2. Resolve "Enable Protected Mode For All Zones" Error RunTime
  3. Resolve Set IE browser Zoom Level To 100% Error On RunTime
  4. How To Handle SSL Certificate Error In IE Browser For WebDriver
  5. Use Fire-IE-Selenium Tool To Locate Element For IE Only WebSites

ChromeDriver
Other Tutorials
  1. Install Firebug And Firepath Add-Ons In Firefox To Get XPath
  2. Attach Firebug and FirePath Add-On To Firefox Driver
  3. Get Element XPath/CSS Using Firebug And FirePath Add-On
  4. Finding Broken Links/Images From Page Using WebDriver

Download And Install MySQL For Database Testing Using Selenium WebDriver

Each and every application has database and It Is very Important to verify that new Inserted or updated record In database Is proper or not. In manual testing, We are executing queries manually to verify, update or delete records but If you are using selenium WebDriver as automation tool then
there should be some way to do same thing using script. My goal Is to show you that how to perform database testing using selenium WebDriver.

Download MySQL Installer
We will learn how to perform database testing using selenium WebDriver with MySQL database. First of all, We need to download MySQL Installer and then we will Install It. Steps to download MySQL are as bellow.
  • On "Download MySQL Installer" page, Click on Download button of "Windows (x86, 32-bit), MSI Installer" as shown bellow. It will ask you to login or register.


  • On login or register page, You can login using your existing oracle account or you need to create new account. After Login, It will take you to Begin Your Download page as bellow.
  • It will show you popup to save mysql Installer file as bellow.
  • Click on Save File button. It will start downloading file and get file like bellow.

Install MySQL Server Using MySQL Installer
Now we have MySQL Installer file using which we can Install MySQL server. Perform bellow given steps to Install MySQL server.
  • Double click on MySQL Installer msi file. It will check your system configuration as bellow.
  • After checking your system configuration, It will open MySQL Installer screen as bellow. Select Custom and click on Next button.
  • On Next screen, Add MySQL server In Features to be Installed box and click on Next button as shown bellow.

  • It will show you ready to Install MySQL on next screen as bellow. Click on Execute button.
  • It will start Installing MySQL server as bellow.
  • When Installation completed, Status will display Ready To Configure. Click on Next button as bellow.
  • On next screen, add port number = 3306 and click on Next button.
  • On next screen, Set password and repeat password and click on Next button. 
Note : Please remember your password. It will be required during Login In MySql. We will use It In test scripts.

  • On Next screen, keep all settings as It Is as shown In bellow Image and click on Next button.
  • Next screen will show you apply server configuration steps. Click on Execute button. It will apply all server settings one by one.

  • When server configuration applied, click on Finish button as bellow.
  • Click on Next button on product configuration step.
  • Click on Finish button on Next screen to finish MySQL server Installation process.
  • When Installation completed, You will see MySQL Command Line Client option In Start menu of Windows as bellow.

Now MySQL Is Installed In your system. We will see how to create new table and execute query In MySQL database manually In Next step.

How Add Method Works Internally in ArrayList with Example

ArrayList is one of the most useful collection class  in Java . We have already discussed   ArrayList vs Vector , Array vs ArrayList and ArrayList vs LinkedList . Let us understand some internal details about ArrayList add(int , Object) method . How add(Object)  method works internally in ArrayList or internal implementation of add(Object) method.


How Add Method works Internally in ArrayList

Before going into the details , first look at the code example of the ArrayList add(Object) method :

public class JavaHungry {

public static void main(String[] args)
{
// TODO Auto-generated method stub

ArrayList<Object> arrobj = new ArrayList<Object>();
arrobj.add(3);
arrobj.add("Java Hungry");
arrobj.add("Blogspot");
System.out.println(" is "+ arrobj);
}
}



Output : [3, Java Hungry, Blogspot]

So in the above example , we have created an ArrayList object arrobj . To add elements into the arrobj we called the add method on arrobj. After printing the arrobj , we get the desired result ,i.e , values are added to the arrobj.
But the question is how add(Object) method adds the value in ArrayList. So lets find out :

There are two overloaded add() methods in ArrayList class:


1.  add(Object)  : adds object to the end of the list.
2.  add(int index , Object )  : inserts the specified object at the specified position in the list.

As internal working of both the add methods are  almost similar. Here in this post , we will look in detail about the internal working of ArrayList add(Object) method. 


Internal working of ArrayList or How add(Object) method works internally in ArrayList in Java.


ArrayList internally uses  array  object to add(or store) the elements. In other words, ArrayList is backed by Array data -structure.The array of ArrayList is resizable (or dynamic).





If you look into the ArrayList Api in jdk  rt.jar , you will find the following code snippets in it.

private transient Object[] elementData;

When you create the ArrayList object i.e new ArrayList() , the following code is executed :

this.elementData = new Object[initialCapacity];



There are two ways to create an ArrayList object . 

a. Creates the empty list with initial capacity


 1.  List   arrlstobj = new ArrayList();

When we create ArrayList this way , the default constructor of the ArrayList class is invoked. It will create internally an array of Object with default size set to 10.

 2.  List  arrlstobj  = new ArrayList(20); 

When we create ArrayList this way , the  ArrayList will invoke the constructor with the integer argument. It will create internally an array of Object . The size of the Object[] will be equal to the argument passed in the constructor . Thus when above line of code is executed ,it  creates an Object[] of capacity 20.

Thus , above ArrayList constructors will create an empty list . Their initial capacity can be 10 or equal to the value of the argument passed in the constructor.


b. Creates the non empty list containing the elements of the specified collection. 

List  arrlstobj  = new ArrayList(Collection c);

The above ArrayList constructor will create an non empty list containing the elements of the collection passed in the constructor.




How the size of ArrayList grows dynamically? 

Inside the add(Object) , you will find the following code


    public boolean add(E e)
 
{
 
     ensureCapacity(size+1);
     elementData[size++] = e;         
     return true;
}

Important point to note from above code is that we are checking the capacity of the ArrayList , before adding the element. ensureCapacity()  determines what is the current size of occupied elements and what is the maximum size of the array. If size of the  filled elements (including the new element to be added to the ArrayList class) is greater than the  maximum size of the array then increase the size of array. But the size of the array can not be increased dynamically. So what happens internally is new Array is created with capacity

int newCapacity = (oldCapacity * 3)/2 + 1;

also, data from the old array is copied into the new array.


Interviewer : Which copy technique internally used by the ArrayList class clone() method?

There are two copy techniques present in the object oriented programming language , deep copy and shallow copy.

how add method works internally in ArrayList in java
Just like HashSet ,  ArrayList also returns the shallow copy of the  HashSet object. It means elements themselves are not cloned. In other words, shallow copy is made by copying the reference of the object.






Interviewer : How to create ArrayList from Array (Object[]) ?

One liner answer :    List  arraylistobj =  Arrays.asList(arrayobj);

Interviewer : What happens if ArrayList is concurrently modified while iterating the elements ?

According to ArrayList Oracle Java docs , The iterators returned by the ArrayList class's iterator and listiterator method are fail-fast. See the difference between fail fast and fail safe iterator .

Interviewer : What is the runtime performance of the get() method in ArrayList , where n represents the number of elements ?

get() ,set() , size() operations run in constant time i.e O(1)

add()  operation runs in amortized constant time , i.e adding n elements require O(n) time.

In case you have any doubts regarding the internal working of add(Object) method of ArrayList in java then please mention in comments.

Saturday, May 30, 2015

Best Book to Learn Java Programming for Beginners?

There is no doubt that the best book to learn Java for beginners is indeed "Head First Java, 2nd Edition". It's interesting, informative and yet easy to read, which is what a beginner wants. Only drawback of this book is that there is no 3rd Edition available. Java has moved a long way since 2nd edition of this book was released. Yes, the core of the Java programming language is not changed much and information given in this book is still relevant and sufficient for anyone who wants to learn Java programming, but an up to date book comprising changes introduced in Java 7 and Java 8 would have been much appreciated. I was hoping for Head First Java 3rd Edition when Java 8 was launched last year, but no update yet. The changes introduced in Java 8 does demand a new edition of book, but that is for advanced level. For a beginner its better to learn basics of Java before diving into lambda expression and other stuff. Head first Java will give you head start in Java programming by first explaining What is Java, What is Java's competitive advantage over other popular programming language e.g. C, C++ or Python and What is the best way to learn Java. Once you start reading this book, you will learn very quickly.
Read more »

Thursday, May 28, 2015

How to Convert Byte array to String in Java with Example

There are multiple ways to convert a byte array to String in Java but most straight forward way is to use the String constructor which accepts a byte array i.e. new String(byte []) , but key thing to remember is character encoding. Since bytes are binary data but String is character data, its very important to know the original character encoding of the text from which byte array has created. If you use a different character encoding, you will not get the original String back. For example, if you have read that byte array from a file which was encoded in "ISO-8859-1" and you have not provided any character encoding while converting byte array to String using new String() constructor then its not guaranteed that you will get the same text back? Why? because new String() by default uses platform's default encoding (e.g. Linux machine where your JVM is running), which could be different than "ISO-8859-1". If its different you may see some garbage characters or even different characters changing the meaning of text completely and I am not saying this by reading few books, but I have faced this issue in one of my project where we are reading data from database which contains some french characters. In the absent of any specified coding, our platform was defaulted on something which is not able to convert all those special character properly, I don't remember exact encoding. That issue was solved by providing "UTF-8" as character encoding while converting byte array to String. Yes, there is another overloaded constructor in String class which accepts character encoding i.e. new String(byte[], "character encoding").
Read more »

Tuesday, May 26, 2015

4 ways to concatenate Strings in Java - Best Performance

When we think about String Concatenation in Java, what comes in our mind is + operator, one of the easiest way to join two String, or a String and a numeric in Java. Since Java doesn't support operator overloading, it's pretty special for String to have behavior. But in truth, it is the worst way of concatenating String in Java. When you concatenate two String using + operator e.g. "" + 101, one of the popular way to convert int to String, compiler internally translate that to StringBuilder append call, which result in allocation of temporary objects. You can see the real difference in performance of our example program, in which we have concatenated 100,000 String using + operator. Anyway, this article is not just about + operator but also about other ways to concatenate multiple Strings. There are four ways to do this, apart from + operator, we can use StringBuffer, StringBuilder and concat() method from java.lang.String class for same purpose. StringBuilder and StringBuffer classes are there for just this reason, and you can see that in our performance comparison. StringBuilder is winner and fastest ways to concatenate Strings. StringBuffer is close second, because of synchronized method and rest of them are just 1000 times slower than them. Here we will see example of all four ways of concatenating Strings in Java.
Read more »

Sunday, May 24, 2015

Running WebDriver Test In Headless Browser Using PhantomJS GhostDriver

Earlier we have configured PhantomJS GhostDriver with eclipse In previous post to run Selenium WebDriver test In headless browser. Now we are all set to execute sample WebDriver test In eclipse using PhantomJS GhostDriver. I have created sample test as bellow which will be executed In headless browser.

We will use DesiredCapabilities to set phantomjs.exe executable file's path and then we will pass It with PhantomJSDriver Initialization as shown In bellow example.

Note : Please set proper path of phantomjs.exe file In bellow given examples.

package Testing_Pack;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class phantomjs {
WebDriver driver;

@BeforeTest
public void setup() throws Exception {
//Set phantomjs.exe executable file path using DesiredCapabilities.
DesiredCapabilities capability = new DesiredCapabilities();
capability.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "E:/phantomjs-2.0.0-windows/bin/phantomjs.exe");
driver = new PhantomJSDriver(capability);
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
}

@Test
public void phantomTest() throws IOException{
driver.get("http://only-testing-blog.blogspot.in/2014/04/calc.html");
//Get current page title using javascript executor.
JavascriptExecutor javascript = (JavascriptExecutor) driver;
String pagetitle=(String)javascript.executeScript("return document.title");
System.out.println("My Page Title Is : "+pagetitle);
driver.findElement(By.xpath("//input[@id='2']")).click();
driver.findElement(By.xpath("//input[@id='plus']")).click();
driver.findElement(By.xpath("//input[@id='3']")).click();
driver.findElement(By.xpath("//input[@id='equals']")).click();
String sum = driver.findElement(By.xpath("//input[@id='Resultbox']")).getAttribute("value");
System.out.println("****** Sum Is : "+sum+" ******");
}
}

When you run above example In eclipse, It will execute test In headless PhantomJS GhostDriver and print page title and sum result In console as bellow.


Capturing page screenshot
Question : Is It possible to capture page screenshot If your test Is executed In headless browser using PhantomJS? Answer Is Yes. You can get page screenshot when test Is being executed In headless browser.

Bellow given example will capture page screenshot and save file with name "Test.jpeg" In D: drive.
package Testing_Pack;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class phantomjs {
WebDriver driver;

@BeforeTest
public void setup() throws Exception {
//Set phantomjs.exe executable file path using DesiredCapabilities.
DesiredCapabilities capability = new DesiredCapabilities();
capability.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "E:/phantomjs-2.0.0-windows/bin/phantomjs.exe");
driver = new PhantomJSDriver(capability);
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
}

@Test
public void phantomTest() throws IOException{
driver.get("http://only-testing-blog.blogspot.in/2014/04/calc.html");
//Get current page title using javascript executor.
JavascriptExecutor javascript = (JavascriptExecutor) driver;
String pagetitle=(String)javascript.executeScript("return document.title");
System.out.println("My Page Title Is : "+pagetitle);
driver.findElement(By.xpath("//input[@id='2']")).click();
driver.findElement(By.xpath("//input[@id='plus']")).click();
driver.findElement(By.xpath("//input[@id='3']")).click();
driver.findElement(By.xpath("//input[@id='equals']")).click();
String sum = driver.findElement(By.xpath("//input[@id='Resultbox']")).getAttribute("value");
System.out.println("****** Sum Is : "+sum+" ******");

//To capture page screenshot and save In D: drive.
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("D:\\Test.jpeg"),true);
}
}

Execute above test and open D: drive when execution completed. There will be "Test.jpeg" In D: drive. This way, You can capture page screenshot for phantomjs driver test case.

Difference between Abstraction and Polymorphism in Java OOPS

Abstraction and Polymorphism are very closely related and understanding difference between them is not as easy as it looks. Their operating model is also similar and based upon relationship between parent and child class. In fact, Polymoprhism needs great support of Abstraction to power itself, without Abstraction you cannot leverage power of Polymorphism. Let's understand this by what Abstraction and Polymorphism provides to an object oriented program. Abstraction is a concept to simplify structure of your code. Abstraction allows you to view things in more general terms rather than looking them as they are at the moment, which gives your code flexibility to deal with the changes coming in future. For example, if you were to design a program to control vehicles e.g. starting, stopping, horn, accelerator, breaks etc, how do you do that? would you design your program just to work with car or bike or would you think about different kinds of vehicles? This is where Abstraction comes into picture, it allows you think in terms of Vehicle rather than thinking in terms of Car. It provide that generalization much needed for a software to be reusable and customizable.
Read more »

Saturday, May 23, 2015

How to convert String to Float in Java and vice-versa - Tutorial

There are three ways to convert a String to float primitive in Java parseFloat(), valueOf() method of Float class and new Float() constructor. Suppose you have String which represent a floating point number e.g. "3.14" which is value of PIE, you can convert it to float by using any of those three method. Since String is one of the most prominent data type in Java, you will often find yourself converting String to Int, Double and other data types and vice-versa. Java designer knows about that and they have made arrangement to carry out these basic task in a predictable and consistent manner. Once you know the trick to convert String to float, you should be able to convert String to Integer, Double and Short. BTW, converting String to byte array is little bit tricky because String is text data and bytes are binary, so character encoding comes into picture. If you want to learn more about how to do conversion between String and byte array, see this step by step tutorial for String to byte array.
Read more »

Friday, May 22, 2015

5 Difference between "implements Runnable" and "extends Thread" in Java

How to instantiate a Thread in java  either by implementing Runnable or extending Thread class . We will go through the difference between "implements Runnable" and "extends Thread" . It will help us to choose the  correct way to instantiate the Thread in our application.
Although, in the real world application you are much more likely to implement Runnable interface than extends Thread. Extending the Thread class is easiest but not a good Object Oriented practice.
In this post we will see the difference between "implements Runnable" and "extends Thread". This is one of the basic interview question on the topic of Threads.

Read Also :  Life Cycle of Thread in Java 


Difference between "implements Runnable" and "extends Thread" in Java

1. Inheritance Option:   The limitation with "extends Thread" approach is that if you extend Thread,  you can not extend anything else . Java does not support multiple inheritance.  In reality , you do not need Thread class behavior , because in order to use a thread you need to instantiate one anyway.
On the other hand,
Implementing the Runnable interface gives you the choice to extend any class you like , but still define behavior that will be run by separate thread.

2. Reusability :  In "implements Runnable" , we are creating a different Runnable class for a specific behavior  job (if the work you want to be done is job). It gives us the freedom to reuse the specific
behavior job whenever required.
"extends Thread"  contains both thread and job specific behavior code. Hence once thread completes execution , it can not be restart again.  

3Object Oriented Design:  Implementing Runnable should be preferred . It does not specializing or modifying the thread behavior . You are giving thread something to run. We conclude that Composition is the better way. Composition means two objects A and B satisfies has-a  relationship.
"extends Thread"  is not a good Object Oriented practice.

4. Loosely-coupled : "implements Runnable" makes the code loosely-coupled and easier to read .
Because the code is split into two classes . Thread class for the thread specific code and your Runnable implementation class for your job that should be run by a thread code.
"extends Thread"  makes the code tightly coupled . Single class contains the thread code as well as the job that needs to be done by the thread.

5. Functions overhead :  "extends Thread"  means inheriting all the functions of the Thread class which we may do not need .  job can be done easily by Runnable without the Thread class functions overhead.

Example of  "implements Runnable" and "extends Thread" 


public class RunnableExample implements Runnable {

public void run() { 
        System.out.println("Alive is awesome");   

 }
}


public class ThreadExample extends Thread {

public void run() { 
        System.out.println(" Love Yourself ");   
 }
}


difference between  implements Runnable and extends Thread in java


When to use "extends Thread" over "implements Runnable"

The only time it make sense to use "extends Thread"  is when you have a more specialized version of Thread class. In other words , because you have more  specialized thread specific behavior.

But the conditions are that the thread work you want is really just a job to be done by a thread. In that case you need to use "implements Runnable" which also leaves your class free to extend some other class.



Recap : Difference between "implements Runnable"  and "extends Thread"





 implements Runnable extends Thread
Inheritance optionextends any java class No  
ReusabilityYesNo
Object Oriented DesignGood,allows composition Bad  
Loosely CoupledYes No
Function OverheadNoYes





If you have any doubts regarding the difference between "implements Runnable"  and "extends Thread" then please mention in the comments .

Monday, May 18, 2015

Configure PhantomJS GhostDriver With Eclipse To Run WebDriver Test

Earlier we learnt how to execute WebDriver test In headless browser(Browser not visible during test case execution) using HTMLUnit driver In THIS POST with practical example. Same thing we can do using PhantomJS GhostDriver. It Is WebKit which Is headless and scriptable with javascript
API. You can read more about PhantomJS on THIS PAGE. Here I will describe you PhantomJs configuration steps with eclipse and next post will tell you how to execute WebDriver test case on PhantomJS headless browser which Is not visible during test case execution.

Steps to configure PhantomJS GhostDriver with eclipse

Step 1 : Download phantomjs.exe In zip format
First of all you need to download executable "phantomjs.exe" file's zip folder for windows. Go to THIS PAGE and click on "phantomjs-2.0.0-windows.zip" link for windows as shown In bellow Image. It will start downloading the folder.



Step 2 : Extract Zip folder
When completed download, You need to extract zip folder to get executable "phantomjs.exe" file. When you extract zip folder, There will be bin folder Inside It and you will get "phantomjs.exe" file In that bin folder as shown In bellow Image.


Step 3 : Download phantomjsdriver-1.2.1.jar file
You need "phantomjsdriver-1.2.1.jar" file. Go to THIS PAGE and click on phantomjsdriver-1.2.1.jar link to download It.

Step 4 : Add phantomjsdriver-1.2.1.jar file In project's build path
"phantomjsdriver-1.1.0.jar" file will be already available In your projects build path as It Is comes with WebDriver jar files. But If you will execute your WebDriver test on PhantomJS GhostDriver using 1.1.0 version then you will get error like bellow.

java.lang.NoClassDefFoundError: org/openqa/selenium/browserlaunchers/Proxies

To resolve this error, you need to remove "phantomjsdriver-1.1.0.jar" file from project's build path and add "phantomjsdriver-1.2.1.jar" file In project's build path. Latest version will resolve your error. Now configuration part of PhantomJS with eclipse Is over. Next post will describe you how to execute test In headless browser.

Wednesday, May 13, 2015

Executing Headless Browser Test In Different Browsers And Version In Selenium

We have learnt how to execute JavaScript In HtmlUnit driver test In previous post. I am also suggesting you to read how to create and run first HtmlUnit driver test In THIS POST where I have described advantages of HtmlUnit driver against all other driver Instances. One of them Is we can
choose the browser and Its version to run selenium WebDriver test.

HtmlUnit driver allows you to run your tests In different browser but In hidden mode. That means If your selected browser to run your test Is Google chrome then test will be executed In Google chrome browser but you will not see Google chrome browser on your screen during test execution. You can choose any of the bellow given browsers and versions to run your WebDriver tests In It using HtmlUnit driver.
  • CHROME
  • FIREFOX_17
  • FIREFOX_24
  • INTERNET_EXPLORER_8
  • INTERNET_EXPLORER_9
  • INTERNET_EXPLORER_11
Syntax to select browser to run test using HtmlUnit driver Is as bellow.

//Initializing HtmlUnitDriver to run test with INTERNET_EXPLORER_11 browser.


HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.INTERNET_EXPLORER_11);


Create and run bellow given example In your eclipse to see execution practically.
package Testing_Pack;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import com.gargoylesoftware.htmlunit.BrowserVersion;

public class htmlDriver {

HtmlUnitDriver driver;
String pagetitle;

@BeforeTest
public void setup() throws Exception {
//Initializing HtmlUnitDriver to run test with INTERNET_EXPLORER_11 browser.
HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.INTERNET_EXPLORER_11);
//Enabling JavaScript of HtmlUnitDriver.
driver.setJavascriptEnabled(true);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

//To hide warnings logs from execution console.
Logger logger = Logger.getLogger("");
logger.setLevel(Level.OFF);

//Opening URL In HtmlUnitDriver.
driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html");
}

@AfterTest
public void tearDown() throws Exception {
//Closing HtmlUnitDriver.
driver.quit();
}

@Test
public void googleSearch() {
//Get current page title using javascript executor.
JavascriptExecutor javascript = (JavascriptExecutor) driver;
String pagetitle=(String)javascript.executeScript("return document.title");
System.out.println("My Page Title Is : "+pagetitle);

// To locate table.
WebElement mytable = driver.findElement(By.xpath(".//*[@id='post-body-8228718889842861683']/div[1]/table/tbody"));
// To locate rows of table.
List<WebElement> rows_table = mytable.findElements(By.tagName("tr"));
// To calculate no of rows In table.
int rows_count = rows_table.size();

// Loop will execute till the last row of table.
for (int row = 0; row < rows_count; row++) {
// To locate columns(cells) of that specific row.
List<WebElement> Columns_row = rows_table.get(row).findElements(By.tagName("td"));
// To calculate no of columns(cells) In that specific row.
int columns_count = Columns_row.size();
System.out.println("Number of cells In Row " + row + " are "+ columns_count);

// Loop will execute till the last cell of that specific row.
for (int column = 0; column < columns_count; column++) {
// To retrieve text from that specific cell.
String celtext = Columns_row.get(column).getText();
System.out.println("Cell Value Of row number " + row+ " and column number " + column + " Is " + celtext);
}
System.out.println("--------------------------------------------------");
}
}
}

Above example will be executed In IE11 browser virtually to extract data from web table. It will print extracted data In console. Next post will show you how to configure PhantomJS GhostDriver with eclipse to run selenium WebDriver test case In It..

Top 50 Java Collections Interview Questions and Answers

We have already shared the most frequently asked java interview questions for experience candidates. Also shared the tricky coding interview questions in our previous posts. Today , we will learn about the top 50 java collections interview questions and answers. We will divide this post into three categories :

Beginner level (0-1 year experience (Freshers)) ,

Intermediate level (1-3 years experienced Java Developers)

Advanced level(3+ Experienced) java collections interview questions and answers

Note : Please prepare all the below questions . Interviewer may choose to ask any question.

Beginner Level (0-1 yr): Java Collections Interview Questions  and Answers


Q1  What is Collection ? What is a Collections Framework ? What are the benefits of Java Collections Framework ?

Collection : A collection (also called as container) is an object  that groups multiple elements into a single unit.

Collections Framework : Collections framework provides unified architecture for manipulating and representing collections.

Benefits of Collections Framework :

1. Improves program quality and speed
2. Increases the chances of reusability of software
3. Decreases programming effort.

Q2 What is the root interface in collection hierarchy ? 

Root interface in collection hierarchy is Collection interface . Few interviewer may argue that
Collection interface extends Iterable interface. So iterable should be the root interface. But you should reply iterable interface present in java.lang package not in java.util package .It is clearly mentioned in Oracle Collection  docs , that Collection interface is a member of the Java Collections framework.  For Iterable interface Oracle doc , iterable interface is not mentioned as a part of the Java Collections framework .So if the question includes  collection hierarchy , then you should answer the question as Collection interface (which is found in java.util package).

Q3 What is the difference between Collection and Collections ?

Collection is  an interface while Collections is a java class , both are present in java.util package and  part of java collections framework.

Q4 Which collection classes are synchronized or thread-safe ?

Stack, Properties , Vector and Hashtable can be used in multi threaded environment because they are synchronized classes (or thread-safe). 



Q5 Name the core Collection  interfaces ?

Java Collection Interfaces or Hierarchy



















                                                source of image :  By Ervinn at en.wikibooks [CC BY-SA 3.0 ], from Wikimedia Commons

The list of core collection interfaces are : just mention the important ones

Important : Collection , Set , Queue , List , Map

Other interface also in the list :  SortedSet, SortedMap , Deque, ListIterator etc.


Q6 What is the difference between List and Set ?

Set contain only unique elements while List can contain duplicate elements.
Set is unordered while List is ordered . List maintains the order in which the objects are added .

Q7 What is the difference between Map and Set ?

Map object has unique keys each containing some value, while Set contain only unique values.

Q8 What are the classes implementing List and Set interface ?

Class implementing List interface :  ArrayList , Vector , LinkedList ,

Class implementing Set interface :  HashSet , TreeSet


Q9 What is an iterator ?

Iterator is an interface . It is found in java.util package. It provides methods to iterate over any Collection.


Q10 What is the difference between Iterator and Enumeration ?

The main difference between Iterator and Enumeration is that Iterator has remove() method while Enumeration doesn't.
Hence , using Iterator we can manipulate objects by adding and removing the objects from the collections. Enumeration behaves like a read only interface as it can only traverse the objects and fetch it .

Q11 Which design pattern followed by Iterator ?

It follows iterator design pattern. Iterator design pattern provides us to navigate through the collection of objects by using a common interface without letting us know about the underlying implementation.

Enumeration is an example of Iterator design pattern.

Q12 Which methods you need to override to use any object as key in HashMap ?

To use any object as key in HashMap , it needs to implement equals() and hashCode() method .

Q13  What is the difference between Queue and Stack ?

Queue is a data structure which is based on FIFO ( first in first out ) property . An example of Queue in real world is buying movie tickets in the multiplex or cinema theaters.

Stack is a data structure which is based on LIFO (last in first out) property . An example of Stack in real world is  insertion or removal of CD  from the CD case.

Q14 How to reverse the List in Collections ?

There is a built in reverse method in Collections class . reverse(List list) accepts list as parameter.

Collections.reverse(listobject);

Q15 How to convert the array of strings into the list ?

Arrays class of java.util package contains the method asList() which accepts the array as parameter.
So,

String[]  wordArray =  {"Love Yourself"  , "Alive is Awesome" , "Be in present"};
List wordList =  Arrays.asList(wordArray);


Intermediate Level (1-3 yrs): Java Collections Interview Questions  and Answers


Q16 What is the difference between ArrayList and Vector ?

It is one of the frequently asked collection interview question , the main differences are
Vector is synchronized while ArrayList is not . Vector is slow while ArrayList is fast . Every time when needed, Vector increases the capacity twice of its initial size while ArrayList increases its ArraySize by 50%. find detailed explanation   ArrayList vs Vector  .



Q17 What is the difference between HashMap and Hashtable ?

It is one of the most popular collections interview question for java developer . Make sure you go through this once before appearing for the interview .
Main differences between HashMap and Hashtable are :

a. HashMap allows one null key and any number of null values while Hashtable does not allow null keys and null values.
b. HashMap is not synchronized or thread-safe while Hashtable is synchronized or thread-safe .
find detailed explanation here Hashtable vs HashMap in Java

Q18 What is the difference between peek(),poll() and remove() method of the Queue interface ?

Both poll() and remove() method is used to remove head object of the Queue. The main difference lies when the Queue is empty().
If Queue is empty then poll() method will return null . While in similar case , remove() method will throw NoSuchElementException .
peek() method retrieves but does not remove the head of the Queue. If queue is empty then peek() method also returns null.

Q19 What is the difference between Iterator and ListIterator.

Using Iterator we can traverse the list of objects in forward direction . But ListIterator can traverse the collection in both directions that is forward as well as backward.

Q20 What is the difference between Array and ArrayList in Java ?

This question checks whether student understand the concept of static and dynamic array. Some main differences between Array and ArrayList are :
a. Array is static in size while ArrayList is dynamic in size.
b. Array can contain primitive data types while ArrayList can not contain primitive data types.
find detailed explanation ArrayList vs Array in Java


Q21 What is the difference between HashSet and TreeSet ?

Main differences between HashSet and TreeSet are :
a.  HashSet maintains the inserted elements in random order while TreeSet maintains elements in the sorted order
b. HashSet can store null object while TreeSet can not store null object.
find detailed explanation here TreeSet vs HashSet in Java


Q22 Write java code showing insertion,deletion and retrieval of HashMap object ?

Do it yourself (DIY) , if found any difficulty or doubts then please mention in the comments.

Q23 What is the difference between HashMap and ConcurrentHashMap ?

This is also one of the most popular java collections interview question . Make sure this question is in your to do list before appearing for the interview .
Main differences between HashMap and ConcurrentHashMap are :
a. HashMap is not synchronized while ConcurrentHashMap is synchronized.
b. HashMap can have one null key and any number of null values while ConcurrentHashMap does not allow null keys and null values .
find detailed explanation here ConcurrentHashMap vs HashMap in Java

Q24 Arrange the following in the ascending order (performance):
HashMap , Hashtable , ConcurrentHashMap and Collections.SynchronizedMap 

Hashtable  <  Collections.SynchronizedMap  <  ConcurrentHashMap  <  HashMap

Q25 How HashMap works in Java ?

This is one of the most important question for java developers. HashMap  works on the principle of Hashing . Find detailed information here to understand what is hashing and how hashmap works in java .

Q26 What is the difference between LinkedList and ArrayList in Java ?

Main differences between LinkedList and ArrayList are :
a. LinkedList is the doubly linked list implementation of list interface , while , ArrayList is the resizable array implementation of list interface.
b. LinkedList can be traversed in the reverse direction using descendingIterator() method  provided by the Java Api developers , while , we need to implement our own method to traverse ArrayList in the reverse direction . find the detailed explanation here ArrayList vs LinkedList in java.



Q27 What are Comparable and Comparator interfaces ? List the difference between them ?



We already explained what is comparable and comparator interface in detail along with examples here,  Comparable vs Comparator in Java

Q28 Why Map interface does not extend the Collection interface in Java Collections Framework ?

One liner answer : Map interface is not compatible with the Collection interface.
Explanation : Since Map requires key as well as value , for example , if we want to add key-value pair then we will use put(Object key , Object value) . So there are two parameters required to add element to the HashMap object  . In Collection interface add(Object o) has only one parameter.
The other reasons are Map supports valueSet , keySet as well as other appropriate methods which have just different views from the Collection interface.

Q29 When to use ArrayList and when to use LinkedList in application?

ArrayList has constant time search operation O(1) .Hence, ArrayList is preferred when there are more get() or search operation .

Insertion , Deletion operations take constant time O(1) for LinkedList. Hence, LinkedList is preferred when there are more insertions or deletions involved in the application.


Q30 Write the code for iterating the list in different ways in java ? 

There are two ways to iterate over the list in java :
a. using Iterator
b. using for-each loop

Coding part : Do it  yourself (DIY) , in case of any doubts or difficulty please mention in the comments .

Advance Level (3+ yrs): Java Collections Interview Questions  and Answers


Q31 How HashSet works internally in java ?

This is one of the popular interview question . HashSet internally uses HashMap to maintain the uniqueness of elements. We have already discussed in detail hashset internal working in java.

Q32 What is CopyOnWriteArrayList ?  How it is different from  ArrayList in Java?

CopyOnWriteArrayList is a thread safe variant of ArrayList   in which all mutative operations like add , set are implemented by creating a fresh copy of the underlying array.
It guaranteed not to throw ConcurrentModificationException.
It permits all elements including null. It is introduced in jdk 1.5 .


Q33  How HashMap works in Java ?

We are repeating this question , as it is one of the most important question for java developer.HashMap works on the principle of Hashing . please find the detailed answer here hashmap internal working in java .

Q34 How remove(key) method works in HashMap ?

This is the new question which is getting popular among java interviewers . We have shared the detailed explanation here how remove method works internally in java.

Q35 What is BlockingQueue in Java Collections Framework? 

BlockingQueue implements the java.util.Queue interface . BlockingQueue supports  operations that wait for the queue to become non-empty when retrieving an element , and wait  for space to become available in the queue when storing an element .
It does not accept null elements.
Blocking queues are primarily designed for the producer-consumer problems.
BlockingQueue implementations are thread-safe and can also be used in inter-thread communications.
This concurrent Collection class was added in jdk 1.5


Q36 How TreeMap works in Java ?

TreeMap internally uses Red-Black tree to sort the elements in natural order. Please find the detailed answers here internal implementation of TreeMap in java .

Q37 All the questions related to HashSet class can be found here ,  frequently asked HashSet interview questions

Q38 What is the difference between Fail- fast iterator and Fail-safe iterator ? 

This is one  of the most popular interview question for the higher experienced java developers .
Main differences between Fail-fast and Fail-safe iterators are :
a. Fail-fast throw ConcurrentModificationException while Fail-safe does not.
b. Fail-fast does not clone the original collection list of objects while Fail-safe creates a copy of the original collection list of objects.
The difference is explained in detail here fail-safe vs fail-fast iterator in java.


Q39 How ConcurrentHashMap works internally in Java?

The detailed answer is already explained here  internal implementation of concurrenthashmap 

Q40 How do you use a custom object as key in Collection  classes like HashMap ?

If one is using the custom object as key then one needs to override equals() and hashCode() method
and one also need to fulfill the contract.
If you want to store the custom object in the SortedCollections like SortedMap then one needs to make sure that equals() method is consistent to the compareTo() method. If inconsistent , then collection will not follow their contracts ,that is , Sets may allow duplicate elements.


Q41 What is hash-collision in Hashtable ? How it was handled in Java?

In Hashtable , if two different keys have the same hash value then it lead to hash -collision. A bucket of type linkedlist used to hold the different keys of same hash value.

Q42 Explain the importance of hashCode() and equals() method ? Explain the contract also ?

HashMap object uses Key object hashCode() method and equals() method to find out the index to put the key-value pair. If we want to get value from the HashMap same both methods are used . Somehow, if both methods are not implemented correctly , it will result in two keys producing the same hashCode() and equals() output. The problem will arise that HashMap will treat both output same instead of different and overwrite the most recent key-value pair with the previous key-value pair.
Similarly all the collection classes that does not allow the duplicate values use hashCode() and equals() method to find the duplicate elements.So it is very important to implement them correctly.

Contract of hashCode() and equals() method

a.  If  object1.equals(object2) , then  object1.hashCode() == object2.hashCode() should always be true.

b. If object1.hashCode() == object2.hashCode() is true does not guarantee object1.equals(object2)

Q43 What is EnumSet in Java ?

EnumSet  is a specialized Set implementation for use with enum types. All of the elements in an enum set must come from a single enum type that is specified explicitly  or implicitly , when the set is created.
The iterator never throws ConcurrentModificationException and is weakly consistent.
Advantage over HashSet:
All basic operations of EnumSet execute in constant time . It is most likely to be much faster than HashSet counterparts.
It is a part of Java Collections Framework since jdk 1.5.

Q44 What are concurrentCollectionClasses?

In jdk1.5 , Java Api developers had introduced new package called java.util.concurrent that have thread-safe collection classes as they allow collections to be modified while iterating . The iterator is fail-fast that is it will throw ConcurrentModificationException.
Some examples of concurrentCollectionClasses are :
a. CopyOnWriteArrayList
b. ConcurrentHashMap

Q45 How do you convert a given Collection to SynchronizedCollection ?

One line code :    Collections.synchronizedCollection(Collection collectionObj) will convert a given collection to synchronized collection.

Q46  What is IdentityHashMap ?

IdentityHashMap

IdentityHashMap is a class present in java.util package. It implements the Map interface with a hash table , using reference equality instead of object equality when comparing keys and values.In other words , in IdentityHashMap two keys k1 and k2 are considered equal if only if (k1==k2).
IdentityHashMap is not synchronized.
Iterators returned by the iterator() method are fail-fast , hence , will throw ConcurrentModificationException.


Q47 What is  WeakHashMap ? 


WeakHashMap :

WeakHashMap is a class present in java.util package similar to IdentityHashMap. It is a Hashtable based implementation of Map interface with weak keys. An entry in 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.
It permits null keys and null values.
Like most collection classes this class is not synchronized.A synchronized WeakHashMap may be constructed using the Collections.synchronizedMap() method.
Iterators returned by the iterator() method are fail-fast , hence , will throw ConcurrentModificationException.

Q48 How will you make Collections readOnly ?

We can make the Collection readOnly by using the following lines code:

General : Collections.unmodifiableCollection(Collection c)

Collections.unmodifiableMap(Map m)
Collections.unmodifiableList(List l)
Collections.unmodifiableSet(Set s)

Q49  What is UnsupportedOperationException?

This exception is thrown to indicate that the requested operation is not supported.
Example of UnsupportedOperationException:
In other words, if you call add() or remove() method on the readOnly collection . We know readOnly collection can not be modified . Hence , UnsupportedOperationException will be thrown.

Q50 Suppose there is an Employee class. We add Employee class objects to the ArrayList. Mention the steps need to be taken , if I want to sort the objects in ArrayList using the employeeId attribute present  in Employee class. 

a. Implement the Comparable interface for the Employee class and now to compare the objects by employeeId we will override the emp1.compareTo(emp2)
b. We will now call Collections class sort method and pass the list as argument , that is ,
     Collections.sort(empList)  

If you want to add more java collections interview questions  and answers or in case you have any doubts related to the Java Collections framework , then please mention in the comments.