Search

Thursday, April 30, 2015

5 Difference between ArrayList and LinkedList in Java with Example

One of the start up java interview questions on Collections topic is difference between ArrayList and LinkedList , interviewer may also ask  to write examples . We already discussed some other  basic interview questions like difference between array and arraylist , difference between arraylist and vector . In this post difference between arraylist and linkedlist , apart from the differences , we will also discuss the similarities , examples and when to prefer arraylist over linkedlist.

Difference between ArrayList and LinkedList in Java

1. Implementation :  ArrayList is the resizable array implementation of list interface , while LinkedList is the Doubly-linked list implementation of the list interface.


2. Performance  :  Performance of ArrayList and LinkedList depends on the type of operation

a. get(int index) or search operation :  ArrayList get(int index) operation runs in constant time i.e O(1)  while LinkedList get(int index) operation run time is O(n) .

The reason behind ArrayList being faster than LinkedList is that ArrayList uses index based system for its elements as it internally uses array data structure , on the other hand ,
LinkedList does not provide index based access for its elements as it iterates either from the beginning or end (whichever is closer) to retrieve the node at the specified element index.

b. insert() or add(Object) operation :  Insertions in LinkedList are generally fast as compare to ArrayList.

In LinkedList adding or insertion is O(1) operation . While in ArrayList, if array is full i.e worst case,  there is extra cost of  resizing array and copying elements to the new array , which makes runtime of add operation in ArrayList O(n) , otherwise it is O(1) .

c. remove(int) operation :  Remove operation in LinkedList is generally same as ArrayList i.e. O(n).
In LinkedList , there are two overloaded remove methods. one is remove() without any parameter which removes the head of the list and runs in constant time O(1) .
The other overloaded remove method in LinkedList is remove(int) or remove(Object) which removes the Object or int passed as parameter . This method traverses the LinkedList until it found the Object and unlink it from the original list . Hence this method run time is O(n).

While in ArrayList remove(int) method involves copying elements from old array to new updated array , hence its run time is O(n).

3.  Reverse  Iterator :  LinkedList can be iterated in reverse direction using descendingIterator() while there is no descendingIterator() in ArrayList , so we need to write our own code to iterate over the ArrayList in reverse direction.

4. Initial Capacity :  If the constructor  is not overloaded , then ArrayList creates an empty list of initial capacity 10 , while LinkedList  only constructs the empty list without any initial capacity.

5. Memory Overhead :  Memory overhead in LinkedList is more as compared to ArrayList as node in LinkedList needs to maintain the addresses of next and previous node. While in ArrayList  each index only holds the actual object(data).


Example of ArrayList and LinkedList :




import java.util.ArrayList;
import java.util.LinkedList;
public class ArrayListLinkedListExample { public static void main(String[] args) { 
 
           
  
        ArrayList<String> arrlistobj = new ArrayList<String>();
arrlistobj.add("1. Alive is awesome");
arrlistobj.add("2. Love yourself");
System.out.println("ArrayList object output :"+ arrlistobj);
 
         
 
        LinkedList llobj = new LinkedList();
llobj.add("1. Alive is awesome");
llobj.add("2. Love yourself");
System.out.println("LinkedList object output :"+llobj);  
 
 }
}


Output: 
ArrayList object output :[1. Alive is awesome, 2. Love yourself]
LinkedList object output :[1. Alive is awesome, 2. Love yourself]


Similarities between ArrayList and LinkedList :

1. Not synchronized :  Both ArrayList and LinkedList are not synchronized ,  and can be made synchronized explicitly using Collections.synchronizedList() method.

2. clone() operation :  Both ArrayList and LinkedList returns a shallow copy of the original object ,i.e.  the elements themselves are not cloned.

3. Iterators : The iterators returned by ArrayList and LinkedList class's iterator and listIterator methods are fail-fast. Fail fast iterators throw ConcurrentModificationException . We have already discussed the difference between fail-fast and fail-safe iterators.

difference between arraylist and linkedlist in java

4. Insertion Order : As ArrayList and LinkedList are the implementation of List interface,so, they both inherit properties of List . They both preserves the order of the elements in the way they are added to the ArrayList or LinkedList object.






When to Use ArrayList and LinkedList :

In real world applications , you will more frequently use ArrayList than LinkedList. But in a very specific situations LinkedList can be preferred.

1. ArrayList is preferred when there are more get(int) or search operations need to be performed as every search operation runtime is O(1).

2. If application requires more insert(int) , delete(int) operations then the get(int) operations then LinkedList is preferred as they do not need to maintain back and forth like arraylist  to preserve continues indices.


Recap : Difference between ArrayList and LinkedList in Java 





 ArrayList LinkedList
ImplementationResizable Array Douby-LinkedList 
ReverseIteratorNoYes , descendingIterator()
Initial Capacity10Constructs empty list 
get(int) operationFast Slow in comparision
add(int) operationSlow in comparisionFast
Memory OverheadNoYes





References : Oracle ArrayList docs  , Oracle LinkedList docs

So we have covered  difference between arraylist and linkedlist in java .In case you have any other doubt  please mention in the comments .

Wednesday, April 29, 2015

What Is Headless/htmlunitdriver? How To Execute WebDriver Test In It?

What Is HtmlUnit Driver or Headless browser driver?
HtmlUnit Driver or mostly It Is known as Headless browser driver Is based on HtmlUnit. HtmlUnit Driver Is same as Firefox or Chrome or IE driver Instance but HtmlUnit driver do not have GUI so you can not see your test execution on your screen. It Is something like virtual browser Instance. Generally we are using Firefox driver or chrome driver or IE driver Instance to run our
WebDriver automation tests. But from all these driver Instances, Headless driver Instance Is most lightweight and fastest version to execute test using selenium.

Also you can learn how to execute webdriver test in FIREFOX, CHROME and IE browsers.

Advantages of using HtmlUnit Driver
There are few advantages as bellow of using HtmlUnit driver.
  • It Is not using any GUI to test so your tests will run In background without any visual Interruption.
  • Execution Is faster compared to all other driver Instances.
  • It Is platform Independent as It Is pure Java solution. It Is using Rhino javascript engine.
  • You can also select other browser versions to run your tests through HtmlUnit driver.
WebDriver test Example using HtmlUnit Driver
I have created simple Google search example which will print page title, search on google and then print all google search result strings In console. 

When you run bellow test, You will notice that any browser will not open, test will be executed virtually and you will see results directly In your eclipse execution console.


package Testing_Pack;

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
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;

public class htmlDriver {

HtmlUnitDriver driver;
String pagetitle;

@BeforeTest
public void setup() throws Exception {
//Initializing HtmlUnitDriver.
driver = new HtmlUnitDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

//Opening URL In HtmlUnitDriver.
driver.get("http://www.google.com");
}

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

@Test
public void googleSearch() {

//Get and print page title before search.
pagetitle = driver.getTitle();
System.out.println("Page title before search : "+pagetitle);

//Search with Hello World on google.
WebElement Searchbox = driver.findElement(By.xpath("//input[@name='q']"));
Searchbox.sendKeys("Hello World");
Searchbox.submit();

//Get and print page title after search.
pagetitle = driver.getTitle();
System.out.println("Page title after search : "+pagetitle);

//Get list of search result strings.
List<WebElement> allSearchResults=driver.findElements(By.cssSelector("ol li h3>a"));

//Iterate the above list to get all the search titles & links from that page.
for(WebElement eachResult : allSearchResults) {
System.out.println("Title : "+eachResult.getText()+", Link : "+eachResult.getAttribute("href"));
}
}
}

When execution completed, You will see result In console as bellow. There will be some warning messages like "com.gargoylesoftware.htmlunit.DefaultCssErrorHandler error" In console. We will see how to remove those warnings In my next post.


Sunday, April 26, 2015

How To Delete Specific/All Cookies In Selenium WebDriver Test

Earlier we learnt how to extract all cookies of current domain In THIS POST and add new cookie for that specific domain In previous post In selenium WebDriver test. Cookies plays very Important role In any website and you must know how to add new cookie or delete specific or all cookies If you
are test engineer. Now supposing you have a test scenario where you have to delete specific cookie or you have to delete all cookies for that domain.

Manually you can do It very easily. Same way, selenium WebDriver has also cookie class which contains function deleteCookieNamed() to delete specific cookie and .deleteAllCookies(); to delete all cookies of domain under test.

Syntax for deleting specific cookie Is as bellow.
driver.manage().deleteCookieNamed("testCookie2");
where  testCookie2 Is name of cookie.

Syntax for deleting all cookie Is as bellow.
driver.manage().deleteAllCookies();

Bellow given example will show you how to delete specific cookie by Its name or delete all cookies.

package Testing_Pack;

import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class deleteCookies {
WebDriver driver;

@BeforeTest
public void setup() throws Exception {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("your website name");
}

@Test
public void deleteCookie(){

//Add 2 test cookies for your domain.
Cookie cookie1 = new Cookie("testCookie1", "WSfed-ffsd-234DFGe-YUTYU");
Cookie cookie2 = new Cookie("testCookie2", "xxCDFSS-234DDs-423SS2-34EE");
driver.manage().addCookie(cookie1);
driver.manage().addCookie(cookie2);

//Get and print all cookies for google domain after adding cookies manually.
Set<Cookie> totalCookies1 = driver.manage().getCookies();
System.out.println("Total Number Of cookies : " +totalCookies1.size());

for (Cookie currentCookie : totalCookies1) {
System.out.println(String.format("%s -> %s -> %s", "Domain Name : "+currentCookie.getDomain(), "Cookie Name : "+currentCookie.getName(), "Cookie Value : "+currentCookie.getValue()));
}

//Deleting specific testCookie2 cookie.
System.out.println();
driver.manage().deleteCookieNamed("testCookie2");

//Get and print all cookies for google domain after deleting cookie manually.
Set<Cookie> totalCookies2 = driver.manage().getCookies();
System.out.println("Total Number Of cookies after deleting one cookie : " +totalCookies2.size());

for (Cookie currentCookie : totalCookies2) {
System.out.println(String.format("%s -> %s -> %s", "Domain Name : "+currentCookie.getDomain(), "Cookie Name : "+currentCookie.getName(), "Cookie Value : "+currentCookie.getValue()));
}

//Deleting all cookies.
System.out.println();
driver.manage().deleteAllCookies();

//Print number of cookies after deleting all cookies.
Set<Cookie> totalCookies3 = driver.manage().getCookies();
System.out.println("Total Number Of cookies after delete all cookies : " +totalCookies3.size());

}
}

Above example will add two test cookies Initially then It will delete specific cookie and at last It will delete all cookies. This Is the way to play with cookies In selenium WebDriver.

Wednesday, April 22, 2015

How To Add New Cookie When Executing Selenium WebDriver Test

Earlier we learnt how to extract and print current domain cookie during test execution using selenium WebDriver In previous post. Sometimes you have a requirement like you have to add new cookie for website under test during selenium WebDriver test execution for some kind of testing
purpose. Is It possible?

Yes, Selenium WebDriver has Inbuilt class named Cookie which contains many useful functions to play with cookie of website under test. You can create new cookie with your desired name and value and then you can use addCookie method to add new cookie In browser for your test domain. Syntax to add new cookie Is as bellow.


//Set cookie value and then add It for current domain.


Cookie name = new Cookie("testCookie", "WSfed-ffsd-234DFGe-YUTYU");


driver.manage().addCookie(name);


Full example to add new cookie and then print It In console to verify that new added cookie Is proper or not Is as bellow.

Note : Add URL of your website under test In bellow given example.

package Testing_Pack;

import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class addCookies {
WebDriver driver;

@BeforeTest
public void setup() throws Exception {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("Your test site URL");
}

@Test
public void addCookie(){
//Set cookie value and then add It for current domain.
Cookie name = new Cookie("testCookie", "WSfed-ffsd-234DFGe-YUTYU");
driver.manage().addCookie(name);

//Get all cookies and print them.
Set<Cookie> totalCookies = driver.manage().getCookies();
System.out.println("Total Number Of cookies : " +totalCookies.size());

for (Cookie currentCookie : totalCookies) {
System.out.println(String.format("%s -> %s -> %s", "Domain Name : "+currentCookie.getDomain(), "Cookie Name : "+currentCookie.getName(), "Cookie Value : "+currentCookie.getValue()));
}
}
}

It will add new cookie for your test domain and then all cookies will be printed In console. Read next post to know how to delete cookie.

Tuesday, April 21, 2015

Singleton Design Pattern with Example and Program Code : Design pattern Interview Question

In this post we are going to learn about the singleton design pattern . It is the most used design pattern in web applications . So if you write design pattern in your CV , then make sure you are familiarized with Singleton
Pattern . For experienced people ,the most common question asked by the interviewer is to write down the code of the Singleton Pattern . Let us discuss that first .

Points to remember while creating a singleton class

Suppose we are creating a singleton class JavaHungry . It means only one  and only one instance of JavaHungry class we  can have at any point of execution in the application code  

*   We  should create a static variable so that it can hold one single instance of our class .
  
         private static JavaHungrySingleton  uniqueInstance ;

*   We should declare the constructor private so that  only Class itself can instantiate the object . Outside
     classes will not be able to see  the class constructor .

private   JavaHungrySingleton(){}

*  Then the main work  to write the method which returns the instance of the class , let the name of the    
    method be  getInstance() .

   Here in this method implementation we created the class JavaHungrySingleton .

  The return type should be of the class object . But there is possibility that two threads simultaneously try to
  access the method and we might end up with two different class objects , thats why method is     synchronized . In other words , By adding synchronized keyword to the method , we force every thread
  to wait for its turn before it can enter the method .  So that , two threads do not enter the method at the    
  same time .
   So we have set up the framework for the singleton method ,which  upto now  looks like

public static synchronized  JavaHungrySingleton   getInstance()
{
1. // some code
}

    Now we need to write  code for the method , that is line 1 //some code .

    So to achieve uniqueinstance , first and foremost important thing to check whether the object of the class
    is already in existence or not . We make sure , by putting condition

Pseudo code to achieve singleton 

   if  uniqueinstance is NULL
   
                  then create the object of the class
   else
                      return uniqueinstance ;

    What  above code is trying to achieve is to make sure there should be atmost one and only one instance of     the  class at any given time .      

        So , code in the method will be look like this
 
if (uniqueInstance ==null )
{
uniqueInstance=new JavaHungrySingleton();
}
return uniqueInstance ;


Interviewer may ask the Class diagram of the Singleton class you created , so below is the class diagram of the JavaHungrySingleton class .


singleton design pattern in java code with example





















So  all the code summed up in the below JavaHungrySingleton Class


public class JavaHungrySingleton
{

private static JavaHungrySingleton uniqueInstance;

private JavaHungrySingleton(){}

public static synchronized JavaHungrySingleton getInstance()
{
if (uniqueInstance ==null )
{
uniqueInstance=new JavaHungrySingleton();
}
return uniqueInstance ;
}

// other useful methods here
}


Now after writing the code , interviewer may asked to write the code using early initialization . To do that ,first we need to understand the difference between lazy initialization and early initialization .

Lazy Initialization :    We create the object of the class only when it is about to use in the program code .
                                    We are calling it lazy because we wait till the last moment to have an object.

Early Initialization :  In this we create the object when the class is getting loaded into the JVM . Eager
                                   intialization is helpful if our application always create and use the Singleton class .



//Code for the Early initialization will be :


public class JavaHungrySingleton
{

private static JavaHungrySingleton uniqueInstance = new JavaHungrySingleton();

private JavaHungrySingleton(){}

public static JavaHungrySingleton getInstance()
{
return uniqueInstance ;
}

// other useful methods here
}


There is third way to achieve singleton pattern while removing some overhead from the getInstance() method of the JavaHungrySingleton class . 
For 6-7 years or above  experience , interviewer may ask about the double checked locking .
In double checked locking  first we check if the object is created , if not then we create one using synchronized block.

Below  is the best  Optimized code for the Singleton pattern 


public class JavaHungrySingleton
{

private static volatile JavaHungrySingleton uniqueInstance;

private JavaHungrySingleton(){}

public static JavaHungrySingleton getInstance()
{
if (uniqueInstance ==null )
{
synchronized(JavaHungrySingleton.class)
{
if (uniqueInstance ==null )
{
uniqueInstance=new JavaHungrySingleton();
}
}
}
return uniqueInstance ;
}

// other useful methods here
}
      
If you have any doubts for singletondesign pattern ,mentioned it below in the comments .

Sunday, April 19, 2015

How To Extract Domain Cookie In Selenium WebDriver Test

You must know what Is cookies before learning how to extract or manage cookies In selenium WebDriver. Cookies are small text files created by website when you access It to remember some data for you to use It In future. Cookies contains domain name for which It Is created, Cookie name
and Its value. It also contains validity duration of cookie. As per testing point of view, sometimes you need to extract cookies. Bellow given example will show you how to extract and print cookies In selenium WebDriver test.

WebDriver has cookie class which contains many different functions using which we can get the cookies and Its different parameters. Few of the functions I have used In bellow given example like

  • getDomain() - To get domain name of cookie.
  • getName() - To get name of cookie.
  • getValue() - To get value of cookie.
  • getExpiry() - To get expiry date of cookie.
Run below given example In your eclipse IDE. It will retrieve above details of cookie for google domain. 

package Testing_Pack;

import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class extractCookies {
WebDriver driver;

@BeforeTest
public void setup() throws Exception {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://www.google.com");
}

@Test
public void extrctCookie(){
//Get and extract all cookies of google domain and print cookie parameters.
Set<Cookie> totalCookies = driver.manage().getCookies();
System.out.println("Total Number Of cookies : " +totalCookies.size());

for (Cookie currentCookie : totalCookies) {
System.out.println(String.format("%s -> %s -> %s -> %s", "Domain Name : "+currentCookie.getDomain(), "Cookie Name : "+currentCookie.getName(), "Cookie Value : "+currentCookie.getValue(), "Cookie Expiry : "+currentCookie.getExpiry()));
}
}
}

At the end of execution, You will get cookie detail In console. You can change domain name In above example to get cookie detail In selenium WebDriver test. Next post will show you how to add new cookie.

Wednesday, April 15, 2015

Data Driven Test Using CSV File In Selenium WebDriver

Earlier we learnt how to perform data driven testing using Java Excel API to read data from excel file In THIS POST. We have also used Apache POI API to read data from excel file In data driven framework creation. Steps to create data driven framework are given on THIS PAGE. Now let's
read data from CSV file to perform data driven testing In selenium WebDriver. Bellow given steps will show you how to read data from from CSV file.

Download required files
We need opencsv-3.2.jar file to read data from CSV file and I have prepared sample CSV data file (Detail.csv) to use It In bellow given example.

  1. DOWNLOAD and extract zip folder to get both above files. 
  2. Add "opencsv-3.2.jar" file In your project's build path In eclipse. You can learn how to add external jar files In project's build path In THIS POST.
  3. Copy paste "Detail.csv" file In D: drive.
"Detail.csv" file have some data and we will use that data In out test. Main thing to learn here Is how to read that data from CSV file.

Now run bellow given example In Eclipse. It will read data from CSV file and use It In webdriver test case to fill form fields.

package Testing_Pack;

import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.opencsv.CSVReader;

public class CSVRead {

//Provide CSV file path. It Is In D: Drive.
String CSV_PATH="D:\\Detail.csv";
WebDriver driver;


@BeforeTest
public void setup() throws Exception {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html");
}

@Test
public void csvDataRead() throws IOException{

CSVReader reader = new CSVReader(new FileReader(CSV_PATH));
String [] csvCell;
//while loop will be executed till the last line In CSV.
while ((csvCell = reader.readNext()) != null) {
String FName = csvCell[0];
String LName = csvCell[1];
String Email = csvCell[2];
String Mob = csvCell[3];
String company = csvCell[4];
driver.findElement(By.xpath("//input[@name='FirstName']")).sendKeys(FName);
driver.findElement(By.xpath("//input[@name='LastName']")).sendKeys(LName);
driver.findElement(By.xpath("//input[@name='EmailID']")).sendKeys(Email);
driver.findElement(By.xpath("//input[@name='MobNo']")).sendKeys(Mob);
driver.findElement(By.xpath("//input[@name='Company']")).sendKeys(company);
driver.findElement(By.xpath("//input[@value='Submit']")).click();
driver.switchTo().alert().accept();
}
}
}

Friday, April 10, 2015

Difference Between String , StringBuilder and StringBuffer Classes with Example : Java

Today we are going to understand the difference between String , StringBuilder and StringBuffer . As you will find that there are minor differences between the above mentioned classes.

String

String is immutable  ( once created can not be changed )object  . The object created as a String is stored in the  Constant String Pool  .
Every immutable object in Java is thread safe ,that implies String is also thread safe . String can not be used by two threads simultaneously.
String  once assigned can not be changed.

String  demo = " hello " ;
// The above object is stored in constant string pool and its value can not be modified.


demo="Bye" ;     //new "Bye" string is created in constant pool and referenced by the demo variable           
 // "hello" string still exists in string constant pool and its value is not overrided but we lost reference to the  "hello"string 

StringBuffer

StringBuffer is mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap . StringBuffer  has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe .

Due to this it does not allow  two threads to simultaneously access the same method . Each method can be accessed by one thread at a time .

But being thread safe has disadvantages too as the performance of the StringBuffer hits due to thread safe property . Thus  StringBuilder is faster than the StringBuffer when calling the same methods of each class.

StringBuffer value can be changed , it means it can be assigned to the new value . Nowadays its a most common interview question ,the differences between the above classes .
String Buffer can be converted to the string by using
toString() method.

StringBuffer demo1 = new StringBuffer("Hello") ;
// The above object stored in heap and its value can be changed .
demo1=new StringBuffer("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuffer

StringBuilder

StringBuilder  is same as the StringBuffer , that is it stores the object in heap and it can also be modified . The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread safe. 
StringBuilder is fast as it is not thread safe . 


StringBuilder demo2= new StringBuilder("Hello");
// The above object too is stored in the heap and its value can be modified
demo2=new StringBuilder("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuilder


----------------------------------------------------------------------------------
                                    String                    StringBuffer         StringBuilder
----------------------------------------------------------------------------------                
Storage Area | Constant String Pool           Heap                       Heap
Modifiable     |  No (immutable)            Yes( mutable )          Yes( mutable )
Thread Safe   |           Yes                                  Yes                              No
 Performance |         Fast                                Very slow                    Fast
-----------------------------------------------------------------------------------


Please mention in the comments in case you have any doubts related to the post: difference between string, stringbuffer  and stringbuilder.

Thursday, April 9, 2015

How To Create and Run Selenium Test In Maven Project From Command Prompt

Earlier we learnt how to DOWNLOAD AND CONFIGURE MAVEN In Windows, CREATE MAVEN PROJECT and IMPORT MAVEN PROJECT IN ECLIPSE. All three previous steps should be executed by you before writing selenium test In maven project. Once you complete all three previous steps, You are ready to create and run selenium test In maven project.

As you know, Maven manages local jar files repository It self and download required jar files from central repository based on your project dependency configuration In POM.xml file. You can read more about maven on THIS PAGE.

Step 1 : Set Selenium WebDriver and TestNG dependencies
We will create and run our selenium test using testng so we need to set required jar files of selenium and testng In our project's build path. As you know, We have not set required jar files In our project's build path till now. And also we do not need to worry about It as this task will be done by maven Itself. Only we need to set testng and selenium webdriver dependencies In POM.xml file with their latest versions.

Update MavenProject's POM.xml file with bellow given xml code. Selenium adn TestNG version may change In future so you need to updated them accordingly In bellow given file.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.demopack</groupId>
<artifactId>MavenProject</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>MavenProject</name>
<url>http://maven.apache.org</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.8</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.44.0</version>
</dependency>
</dependencies>
</project>

Step 2 : Compile project to download required jar files In local repository
Now we need to compile project to download required dependency jar files. Follow steps given bellow.
  1. Open command prompt.
  2. Set MavenProject folder as working directory In command prompt.
  3. Run mvn compile command In command prompt as bellow. It will compile project and download required jar files of selenium and testng from maven central repository to local repository folder called M2. It can take 10 to 20 minutes If you are downloading It first time. For me, All files are already available In local repository so maven not downloaded any jar file.


Step 3 : Adding required jar files under project's build path from command prompt
You not need to add required jar files manually under project's build path. Run mvn eclipse:eclipse command In command prompt as bellow. Selenium WebDriver and TestNG Jar files will be added automatically under project's build path and It will show message BUILD SUCCESS.


Now If you check your project's build path, all selenium and TestNG jar files will be there.

Step 4 : Create selenium webdriver test cases
First of all delete existing AppTest.java file from src/test/java package and create two java files as bellow under same package.

GoogleTest.java
package com.demopack;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class GoogleTest {
WebDriver driver;

@BeforeTest
public void StartBrowser_NavURL() {
driver = new FirefoxDriver();
driver.manage().window().maximize();
}

@AfterTest
public void CloseBrowser() {
driver.quit();
}

@Test
public void testToCompareDoubles() {
driver.get("http://www.google.com");
}
}

BingTest.java
package com.demopack;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class BingTest {
WebDriver driver;

@BeforeTest
public void StartBrowser_NavURL() {
driver = new FirefoxDriver();
driver.manage().window().maximize();
}

@AfterTest
public void CloseBrowser() {
driver.quit();
}

@Test
public void testToCompareDoubles() {
driver.get("http://www.bing.com");
}
}


Step 5 : Run Maven-Selenium WebDriver tests from command prompt
For running selenium test cases, run mvn package command In command prompt. It will validate and compile maven project and then run selenium webdriver test cases.

At the end of test execution, Refresh "MavenProject" project folder and expand target folder. Go to surefire-reports -> Open index.html file. It will open testng execution report as shown bellow.


This way we can create and run selenium test cases In maven project using testng and generate testng reports.

Tuesday, April 7, 2015

How to parse String to Date in Java using JodaTime Example

In this Java tutorial we will learn how to parse String to Date using Joda-Time library, for example, we will convert date String "04-12-2014" to java.util.Date object which represent this date. Before Java 8 introduced its new Date and Time API,  Joda was only reliable, safe and easy way to deal with date and time intricacies in Java. Java's own Date and Time was not that great, starting from JDK 1.1 when they made java.util.Date a mutable object and when they introduced Calendar in Java 1.2. It is one of the most criticized feature of Java on communities along with checked exception and object cloning. Even though Java 8 has corrected its mistake with an excellent, shiny new API, which address all past issue, Joda date and time library still has a role to play in Java systems. First and foremost reason is because most of the large banks and clients are still running on Java 1.6 and will likely take another 5 to 6 year to adopt Java 8, Joda is the only friend you can trust to deal with date and time nightmares. One of the most common task in Java is to parse String to Dates and even though Java provides a utility class called SimpleDateFormat, its not safe to use in multi-threaded environment until you know how to use thread confinement to make SimpleDateFormat thread-safe. Many beginners either create new instance of SimpleDateFormat each time they have to convert String to Date or commit classical mistake of storing it in an instance or static variable, only to face mysterious issues later. Since most of the Joda Time classes are Immutable, you can use them easily and safely in concurrent application.
Read more »

Sunday, April 5, 2015

How To Import Maven Project In Eclipse For Selenium Test

We have created new project with name "MavenProject" from command prompt during previous post. Now we needs to Import maven project In eclipse and then we can create and run selenium test In It. We will go step by step to Import project In eclipse as bellow.

Step 1 : Make "MavenProject" compatible to Import In eclipse
Any project needs .classpath and .project files under project folder to Import It In eclipse. If you noticed, our maven project do not have any such file. To create both these files, You need to set project folder as working directory In command prompt and then run mvn eclipse:eclipse command as bellow.


It will create .classpath and .project files under project folder as bellow.


Now your project Is compatible to Import In Eclipse.

Step 2: Open Eclipse and Import Project
Steps to Import maven project In eclipse.

Right click on project explorer and go to Import -> Import. It will open Import popup.


Explore General folder and select Existing Project into Workspace from It as bellow and then click on Next button.


On next screen, click on Browse button. It will open Browse For Folder popup. Select MavenProject project folder from It and click on OK button.


It will set root directory to project folder path and so project In grid as bellow.


Click on Finish button. It will Import maven project In Eclipse. Project structure will looks like bellow In eclipse.



Now maven project Is Imported In eclipse successfully. Developers use main folder to write code. We will use only test folder to create our selenium webdriver example test. Next post will describe you how to create and run selenium test In maven project.

Thursday, April 2, 2015

Anatomy of a Parabolic Short: Day Trading Technique


Hey folks,

Here's a Day Trade i made today in my personal account. It was a very slow day in the market but while running my INTRA DAY scans i saw this trade setup and here's how i played it. I rarely short stocks in a bull market but this one was a rare exception.

I like to use BOLLINGER BANDS to help spot potential OverSold and/or OverBought stocks to Buy or Selll(short).

Note: this trade for experienced traders only. Rookies, please stay away from this type of trade setups until you get some more screen time under your belt.

I entered the trade in 3 separate pieces and averaged entry was $21.85-ish while holding 13,000 shares. This trade was good for a quick $2000.00 gain... coulda, woulda, shoulda been much much bigger with a lil more patience but as you already know, i am the "impatient trader". 
My stop loss was 10 cents above the $22.00 round number. 

Hope it helps!







DateSymbolSubjectAction
4/2/2015 3:01:56 PM ETGSM Bought to Cover 100 GSM @ $21.67Executed
4/2/2015 3:01:56 PM ETGSM Bought to Cover 1400 GSM @ $21.6699Executed
4/2/2015 3:01:56 PM ETGSM Bought to Cover 300 GSM @ $21.668Executed
4/2/2015 3:01:56 PM ETGSM Bought to Cover 100 GSM @ $21.67Executed
4/2/2015 3:01:56 PM ETGSM Bought to Cover 300 GSM @ $21.67Executed
4/2/2015 3:01:56 PM ETGSM Bought to Cover 100 GSM @ $21.67Executed
4/2/2015 3:01:56 PM ETGSM Bought to Cover 400 GSM @ $21.6699Executed
4/2/2015 3:01:56 PM ETGSM Bought to Cover 100 GSM @ $21.66Executed
4/2/2015 3:01:56 PM ETGSM Bought to Cover 100 GSM @ $21.67Executed
4/2/2015 3:01:56 PM ETGSM Bought to Cover 100 GSM @ $21.67Executed
4/2/2015 3:01:23 PM ETGSM Bought to Cover 16 GSM @ $21.7Executed
4/2/2015 3:01:12 PM ETGSM Bought to Cover 600 GSM @ $21.7Executed
4/2/2015 3:01:11 PM ETGSM Bought to Cover 4500 GSM @ $21.7Executed
4/2/2015 3:01:11 PM ETGSM Bought to Cover 2420 GSM @ $21.7Executed
4/2/2015 3:01:11 PM ETGSM Bought to Cover 300 GSM @ $21.7Executed
4/2/2015 3:01:11 PM ETGSM Bought to Cover 800 GSM @ $21.7Executed
4/2/2015 3:01:10 PM ETGSM Bought to Cover 100 GSM @ $21.7Executed
4/2/2015 3:00:35 PM ETGSM Bought to Cover 100 GSM @ $21.628Executed
4/2/2015 3:00:35 PM ETGSM Bought to Cover 100 GSM @ $21.63Executed
4/2/2015 3:00:35 PM ETGSM Bought to Cover 51 GSM @ $21.62Executed
4/2/2015 3:00:35 PM ETGSM Bought to Cover 100 GSM @ $21.63Executed
4/2/2015 3:00:35 PM ETGSM Bought to Cover 100 GSM @ $21.63Executed
4/2/2015 3:00:35 PM ETGSM Bought to Cover 100 GSM @ $21.63Executed
4/2/2015 3:00:35 PM ETGSM Bought to Cover 153 GSM @ $21.63Executed
4/2/2015 3:00:35 PM ETGSM Bought to Cover 100 GSM @ $21.63Executed
4/2/2015 3:00:35 PM ETGSM Bought to Cover 100 GSM @ $21.63Executed
4/2/2015 3:00:35 PM ETGSM Bought to Cover 6 GSM @ $21.63Executed
4/2/2015 3:00:35 PM ETGSM Bought to Cover 100 GSM @ $21.65Executed
4/2/2015 3:00:35 PM ETGSM Bought to Cover 54 GSM @ $21.65Executed
4/2/2015 3:00:35 PM ETGSM Bought to Cover 100 GSM @ $21.63Executed
4/2/2015 3:00:35 PM ETGSM Bought to Cover 100 GSM @ $21.65Executed
4/2/2015 2:11:31 PM ETGSM Sold Short 100 GSM @ $21.93Executed
4/2/2015 2:11:31 PM ETGSM Sold Short 500 GSM @ $21.9316Executed
4/2/2015 2:11:31 PM ETGSM Sold Short 100 GSM @ $21.93Executed
4/2/2015 2:11:31 PM ETGSM Sold Short 65 GSM @ $21.93Executed
4/2/2015 2:11:31 PM ETGSM Sold Short 100 GSM @ $21.93Executed
4/2/2015 2:11:31 PM ETGSM Sold Short 100 GSM @ $21.93Executed
4/2/2015 2:11:31 PM ETGSM Sold Short 100 GSM @ $21.93Executed
4/2/2015 2:11:31 PM ETGSM Sold Short 100 GSM @ $21.93Executed
4/2/2015 2:11:31 PM ETGSM Sold Short 100 GSM @ $21.93Executed
4/2/2015 2:11:31 PM ETGSM Sold Short 100 GSM @ $21.93Executed
4/2/2015 2:11:31 PM ETGSM Sold Short 403 GSM @ $21.93Executed
4/2/2015 2:11:31 PM ETGSM Sold Short 100 GSM @ $21.93Executed
4/2/2015 2:11:31 PM ETGSM Sold Short 92 GSM @ $21.93Executed
4/2/2015 2:11:31 PM ETGSM Sold Short 100 GSM @ $21.93Executed
4/2/2015 2:11:31 PM ETGSM Sold Short 46 GSM @ $21.93Executed
4/2/2015 2:11:31 PM ETGSM Sold Short 54 GSM @ $21.93Executed
4/2/2015 2:11:31 PM ETGSM Sold Short 100 GSM @ $21.93Executed
4/2/2015 2:11:31 PM ETGSM Sold Short 100 GSM @ $21.93Executed
4/2/2015 2:11:31 PM ETGSM Sold Short 100 GSM @ $21.93Executed
4/2/2015 2:11:31 PM ETGSM Sold Short 40 GSM @ $21.93Executed
4/2/2015 2:11:31 PM ETGSM Sold Short 100 GSM @ $21.93Executed
4/2/2015 2:11:31 PM ETGSM Sold Short 200 GSM @ $21.93Executed
4/2/2015 2:11:31 PM ETGSM Sold Short 100 GSM @ $21.93Executed
4/2/2015 2:11:31 PM ETGSM Sold Short 100 GSM @ $21.93Executed
4/2/2015 2:07:51 PM ETGSM Sold Short 1800 GSM @ $21.86Executed
4/2/2015 2:07:51 PM ETGSM Sold Short 100 GSM @ $21.86Executed
4/2/2015 2:07:51 PM ETGSM Sold Short 400 GSM @ $21.8666Executed
4/2/2015 2:07:51 PM ETGSM Sold Short 2700 GSM @ $21.8666Executed
4/2/2015 2:05:37 PM ETGSM Sold Short 100 GSM @ $21.77Executed
4/2/2015 2:05:37 PM ETGSM Sold Short 100 GSM @ $21.77Executed
4/2/2015 2:05:37 PM ETGSM Sold Short 100 GSM @ $21.77Executed
4/2/2015 2:05:37 PM ETGSM Sold Short 400 GSM @ $21.7601Executed
4/2/2015 2:05:37 PM ETGSM Sold Short 100 GSM @ $21.76Executed
4/2/2015 2:05:37 PM ETGSM Sold Short 115 GSM @ $21.76Executed
4/2/2015 2:05:37 PM ETGSM Sold Short 100 GSM @ $21.76Executed
4/2/2015 2:05:37 PM ETGSM Sold Short 200 GSM @ $21.76Executed
4/2/2015 2:05:37 PM ETGSM Sold Short 100 GSM @ $21.76Executed
4/2/2015 2:05:37 PM ETGSM Sold Short 100 GSM @ $21.75Executed
4/2/2015 2:05:37 PM ETGSM Sold Short 100 GSM @ $21.75Executed
4/2/2015 2:05:37 PM ETGSM Sold Short 285 GSM @ $21.74Executed
4/2/2015 2:05:37 PM ETGSM Sold Short 100 GSM @ $21.75Executed
4/2/2015 2:05:37 PM ETGSM Sold Short 2200 GSM @ $21.75Executed
4/2/2015 2:05:37 PM ETGSM Sold Short 800 GSM @ $21.75Executed
4/2/2015 2:05:37 PM ETGSM Sold Short 100 GSM @ $21.76