There is no easy way to convert an array to list in Java, but you can easily convert a list into array by calling toArray() method, which List inherit from Collection interface. If you solely rely on core JDK, then only way to convert an array to list is looping over array and populating list one element at a time. But if you can use open source libraries like Google Guava or Apache Commons lang then there is many utility classes to convert list to array and vice-versa, as shown in this tutorial. If you are working on Java application, you will often need to convert between list and array. A list is nothing but a dynamic array which knows how to re-size itself when it gets full or get close to full. List uses load factor to decide when to re-size, default value of its is 0.75. When they re-size, list usually double their slots e.g. goes from 16 to 32 etc. You can find these nifty details in their implementation classes e.g. ArrayList is one of the popular list in Java which provides order and random access. BTW, if you want to truly master Java Collection framework, then you must read Java Generics and Collection book, written by Maurice Naftaline and one of the must read book to become expert on Java Collections framework.
Read more »
Search
Monday, August 31, 2015
Sunday, August 30, 2015
5 Difference between Iterator and ListIterator in Java with Example
In this tutorial we will learn about the difference between Iterator and ListIterator . We will also look at the examples of Iterator and ListIterator one by one. We have already discussed different type of iterators i.e fail-fast iterator and fail-safe iterator.
Difference between Iterator and ListIterator in Java with Example
1. Traversal Direction : ListIterator allows the programmers to iterate the list objects in both directions i.e forward as well as backward direction using previous() and next() method.
Iterator can be used to iterate the list,map and set object in one direction i.e forward.
2. Set and Map implemented Objects Traversal : ListIterator can be used to traverse List object only . But Iterator can be used to traverse Map, List and Set implemented objects.
3. Add or Set operation at any index : According to ListIterator Oracle docs,
ListIterator can modify the list during iteration using add(E e) , remove() or set(E e).
Iterator can not add the element during traversal but they can remove the element from the underlying collection during the iteration as they only consist of remove() method. There is no add(E e) and set(E e) method in Iterator.
4. Determine Iterator's current position : ListIterator can obtain the iterator's current position in the list. Iterator's current position during traversal can not be determined using Iterator.
5. Retrieve Index of the element : ListIterator can obtain the index of the elements using previousIndex(E e) or nextIndex(E e) methods. We can not obtain the index using Iterator as there is no such methods present.
Example of Iterator and ListIterator
Output :
Similarities between Iterator and ListIterator in Java
1. Interfaces : Both Iterator and ListIterator are interfaces . ListIterator extends Iterator interface.
2. Collection Framework : Both Iterator and ListIterator are member of the Java Collection Framework.
3. Traversal : Both are used to iterate over the collection of objects .
4. Interfaces added to jdk : Both interfaces are added to the jdk in java 1.2
Recap : Difference between Iterator and ListIterator in Java with Example
In case you have any questions regarding the difference between Iterator and ListIterator in Java with example , please feel free to mention in the comments.
Iterator can be used to iterate the list,map and set object in one direction i.e forward.
2. Set and Map implemented Objects Traversal : ListIterator can be used to traverse List object only . But Iterator can be used to traverse Map, List and Set implemented objects.
for example
// ListIterator object is created
ListIterator listIteratorObject = List.listIterator();
// Iterator object is created
Iterator iteratorObject = List.iterator();
3. Add or Set operation at any index : According to ListIterator Oracle docs,
ListIterator can modify the list during iteration using add(E e) , remove() or set(E e).
Iterator can not add the element during traversal but they can remove the element from the underlying collection during the iteration as they only consist of remove() method. There is no add(E e) and set(E e) method in Iterator.
4. Determine Iterator's current position : ListIterator can obtain the iterator's current position in the list. Iterator's current position during traversal can not be determined using Iterator.
5. Retrieve Index of the element : ListIterator can obtain the index of the elements using previousIndex(E e) or nextIndex(E e) methods. We can not obtain the index using Iterator as there is no such methods present.
Example of Iterator and ListIterator
import java.util.Iterator;import java.util.ListIterator;public class IteratorListIteratorExample {public static void main(String[] args) {
ListlistObject = new ArrayList ();
listObject.add("Alive is awesome");
listObject.add("Love yourself");
ListIterator listIteratorObject = listObject.listIterator();
System.out.println("ListIterator object output in forward direction:");
System.out.println("");
while( listIteratorObject.hasNext() )
{
System.out.println(listIteratorObject.next());
}
System.out.println("ListIterator object output in backward direction:");
System.out.println("");
while( listIteratorObject.hasPrevious() )
{
System.out.println(listIteratorObject.previous());
}
List iteratorListObject = new ArrayList();
iteratorListObject.add("Facebook");
iteratorListObject.add("Google");
iteratorListObject.add("Apple");
Iterator javaHungryIterator = iteratorListObject.iterator();
System.out.println("Iterator object output in forward direction:");
while( javaHungryIterator.hasNext() )
{
System.out.println(javaHungryIterator.next());
}
}
}
Output :
ListIterator object output in forward direction:
Alive is awesome
Love yourself
ListIterator object output in backward direction:
Love yourself
Alive is awesomeIterator object output in forward direction:
Apple
Similarities between Iterator and ListIterator in Java
1. Interfaces : Both Iterator and ListIterator are interfaces . ListIterator extends Iterator interface.

3. Traversal : Both are used to iterate over the collection of objects .
4. Interfaces added to jdk : Both interfaces are added to the jdk in java 1.2
Recap : Difference between Iterator and ListIterator in Java with Example
ListIterator | Iterator | |
---|---|---|
Traversal Direction | Both , forward and backward | Forward |
Objects traversal | List only | Map, Set and List |
Add and Set operations | Allows both operations | Not possible |
Iterator's current position | Yes , can be determined | Not possible. |
Retrieve Index | Yes | Not possible |
In case you have any questions regarding the difference between Iterator and ListIterator in Java with example , please feel free to mention in the comments.
What Is The Use of "final" Keyword In Java
Interviewer can ask you question "What is final keyword in java". "final" is a keyword which is reserved in java. It restrict the user. "final" keyword In Java can be used with different three contexts in java like variable, method and class. If define an entity which may only be assigned once. Now let's try to understand how to use final keyword in java with practical examples for variable, method and class.
final variableOnce you initialize value to final variable, You can not change it latter on anywhere. It will stay as it is. In bellow given example, WHEELS is final variable and initialized with 2. Then i am trying to change it from 2 to 4 but it is showing me compilation error.
public class FinalKeyword {
final int WHEELS = 2; //final variable initialized.
void bikeWheels() {
WHEELS = 4; //This is not allowed. Shows you compile time error.
}
public static void main(String[] args) {
FinalKeyword fk = new FinalKeyword();
fk.bikeWheels();
}
}
In short, We can not change value of final variable.
final method
If method is declared with final keyword, It is called final method. You can not override final methods in sub class. So here final keyword will helps you to restrict method overriding. Example is as bellow. Here COLLEGENAME() is final method in parent class and then i am trying to override it in child class but it is showing me compile time error.
public class College {
final void COLLEGENAME(){ //Method declared as final in parent class
System.out.println("abc");
}
}
public class Department extends College{
void COLLEGENAME(){//It will show compile time error because it will not allow to override final methods.
System.out.println("xyz");
}
public static void main(String args[]){
Department dep= new Department();
dep.COLLEGENAME();
}
}
final class
If class is declared with final keyword then class is final class and any other class can not extend it. Here, WILDANIMALS is final class and i am trying to extend it in sub class Cow but it is showing me error.
final class WILDANIMALS {
}
//It will show compile time error as WILDANIMALS is final class. You can not extend it.
public class Cow extends WILDANIMALS{
}
This way we can restrict class extension too using final keyword.
Points to remember about final class
- final keyword can be used with variable, method or class to make them final.
- Local final variable must be initialized during declaration or inside constructor. Otherwise it will show you an error.
- We can not declare constructor as final. VIEW MORE about constructor in java.
- By default all variables declared in interface are implicitly final. VIEW MORE about interface in java.
- Value of final variable can not be changed.
- We can not override final method.
- Class can not be extended to final class. VIEW POST on inheritance to know more about class extend.
- final variable which is not initialized during declaration is called blank final variable and you must need to initialize it in constructor.
<< PREVIOUS || NEXT >>
Saturday, August 29, 2015
How to randomize elements in List in Java using shuffle method
java.util.Collections class provides shuffle() method which can be used to randomize object stored in a List in Java. Since List is an ordered collection and maintains the order on which objects are inserted into it, you may need to randomize elements if you need them in different order. Collections.shuffle() method uses default randomness to randomize element but you also has an overloaded version of shuffle() to provide an instance of java.util.Random object, which can be used to randomize elements. Since this method except a List, you can also pass it to LinkedList, Vector, CopyOnWriteArrayList and others, which doesn't implement RandomAccess method. In such cases, this method convert list to array before shuffling to avoid quadratic performance by shuffling sequential access list. Once shuffling is done it also converts back array to list. Shuffling has many usage e.g. shuffling deck of cards in a poker game simulation. You can also use shuffling to roll dice if you are developing any board game which requires dice e.g. Ludo.
Read more »
Wednesday, August 26, 2015
Handle SSL Certificate Error In Google Chrome When Run Test In Selenium
You already know how to execute selenium webdriver test In Google chrome browser as we learnt It In THIS POST. You are also well aware about how to handle SSL Certificate Error In Mozilla Firefox browser by creating custom profile as described In THIS POST and In IE browser using driver.navigate() method as described In THIS POST. Now supposing you wants to run your test In google chrome browser and need to handle SSL Certificate Error. Any Idea How to do It?
Handling SSL certificate error In google chrome browser on selenium WebDriver test execution Is so simple and easy. Here we can use desired capabilities to get and accept SSL certificate on run-time using bellow given syntax.
//Set chrome browser's capabilities to to accept SSL certificate on runtime.
DesiredCapabilities capability = DesiredCapabilities.chrome();
capability.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
Now If you will launch Google Chrome browser using newly set capability and open URL where SSL certificate error display then It will accept SSL certificate automatically and launch site URL without any error.
Practical example to show how to handle SSL certificate error Is as bellow. Execute bellow given example In eclipse (If you have any URL where SSL certificate error appear) and observe result.
package Testing_Pack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
public class SSLErrorInChrome {
public static void main(String[] args) {
//Set chrome browser's capabilities to to accept SSL certificate on runtime.
DesiredCapabilities capability = DesiredCapabilities.chrome();
capability.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver(capability);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//Enter the URL of site where you facing SSL error.
driver.get("Enter site URL");
}
}
It will handle certificate related error and run your test smoothly. I have used above method In many of my sites and works fine for me.
Tuesday, August 25, 2015
2 ways to parse String to int in Java
Java provides Integer.parseInt() method to parse a String to an int value, but that's not the only way to convert a numeric String to int in Java. There is in fact a better way, which take advantage of parsing logic of parseInt() method as well as caching offered by Flyweight design pattern, which makes it more efficient and useful. Yes, you guessed it right, I am talking about Integer.valueOf() method, which implements Flyweight design pattern and maintains a cached pool of frequently used int values e.g. from -128 to 127. So every time you pass a numeric String which is in range of -128 to 127, Integer.valueOf() doesn't create a new Integer object but return the same value from cached pool. Only drawback is that Integer.valueOf() returns an Integer object and not an int primitive value like parseInt() method, but given auto-boxing is available in Java from JDK 5 onward, which automatically convert an Integer object to int value in Java. BTW, if you are learning Java and want to master fundamentals, I suggest you to take a look at Head First Java 2nd Edition, they explains the concept in the easiest way possible but also brings out important details.
Read more »
Saturday, August 22, 2015
Similarities And Difference Between Abstract Class And Interface
Earlier we have learnt about interface in THIS POST and abstract class THIS POST. Now let's try to understand similarities difference between abstract class and interface. Interviewer can ask you this question when you will go for selenium webdriver with java interview. There are few similarities and differences between interface and abstract class as bellow.
Similarities- Interface can not be instantiated. Same way, you can not instantiate abstract class.
- That means you can not create object of interface or abstract class.
Difference
Differences between interface and abstract class are as bellow.
Interface | Abstract Class |
We can use interface keyword to declare interface. | We can use abstract keyword to declare abstract class. |
Interface can hold only abstract methods(without implementation). | Abstract class can hold abstract(without implementation) as well as non abstract methods. |
Interface can be implemented using implements keyword. | Abstract class can be extended using extends keyword. |
We can achieve multiple inheritance using interface as we can implement multiple interfaces to any class. | Abstract class doesn't support multiple inheritance as we can not extend more than one class. |
Interface can not hold main method, static methods or constructor. | Abstract class can hold main method, static methods or constructor. |
Also it can hold only static and final variables and mandatory to initialize them. | It can hold static, non static, final, non final variables and also it is not mandatory to initialize them. |
We can achieve 100% abstraction using interface as all methods are abstract by default. It can not hold concrete methods. | We can achieve partial(0% to 100%) abstraction using abstract class as it can hold abstract as well concrete methods too. |
When you add a new method in existing interface it breaks all its implementation and you need to provide an implementation in all clients which is not good. | By using abstract class you can provide default implementation in super class by creating concrete method. It is not required to provide its implementation in sub class. |
These are the difference between abstract class and interface in java which can helps you to choose abstract class or interface.
Difference between HashSet and CopyOnWriteArraySet with Example
I have already shared how HashSet works internally in java . Both HashSet and CopyOnWriteArraySet does not allow duplicates . In this post we will learn about the differences , similarities between HashSet and CopyOnWriteArraySet.
Read Also : WebServices Interview Questions in Java
Difference between HashSet and CopyOnWriteArraySet in Java
1. Synchronization : HashSet is not synchronized . CopyOnWriteArraySet is synchronized. Synchronization means at a time only one thread can access the object.
2. Performance : HashSet is faster as it is not synchronized. That means many threads can execute the same piece of code simultaneously. In comparison , CopyOnWriteArraySet is slower.
3. Fail-fast vs Fail-safe : Iterators returned by HahSet's iterator and listiterator methods are fail-fast. CopyOnWriteArraySet uses fail-safe iterator . We have already shared the fail-fast vs fail-safe iterators in java with example
4. ConcurrentModificationException : HashSet can throw ConcurrentModificationException while CopyOnWriteArraySet can not .
5. Added in java version : HashSet class was added in java version 1.2 , while CopyOnWriteArraySet class was added in java version 1.5 (or java 5) .
6. Package : HashSet class is present in java.util package , while CopyOnWriteArraySet class is present in java.util.concurrent package.
Example of ArraySet and CopyOnWriteArraySet in Java
Output : HashSet object output :[Alive is awesome, Love yourself]
CopyOnWriteArraySet object output :[Alive is awesome, Love yourself]
Similarities between HashSet and CopyOnWriteArraySet
1. Permit null values : Both HashSet and CopyOnWriteArraySet permits null.
2. Java Collections Framework : Both classes are part of the Java Collections Framework.
3. Duplicate elements : Both classes does not allow to store duplicate elements.
When to prefer CopyOnWriteArraySet over HashSet
CopyOnWriteArraySet is a thread-safe variant of HashSet in which all mutative operations (add , set and so on) are implemented by making a fresh copy of the underlying array.
So, if your code involves multi-threading tasks then prefer CopyOnWriteArraySet over HashSet.
Otherwise , always use HashSet .
Recap : Difference between HashSet and CopyOnWriteArraySet in Java
If you have any other questions or doubts regarding the difference between HashSet and CopyOnWriteArraySet in Java , please mention in comments.
Read Also : WebServices Interview Questions in Java
Difference between HashSet and CopyOnWriteArraySet in Java
1. Synchronization : HashSet is not synchronized . CopyOnWriteArraySet is synchronized. Synchronization means at a time only one thread can access the object.
2. Performance : HashSet is faster as it is not synchronized. That means many threads can execute the same piece of code simultaneously. In comparison , CopyOnWriteArraySet is slower.
3. Fail-fast vs Fail-safe : Iterators returned by HahSet's iterator and listiterator methods are fail-fast. CopyOnWriteArraySet uses fail-safe iterator . We have already shared the fail-fast vs fail-safe iterators in java with example
4. ConcurrentModificationException : HashSet can throw ConcurrentModificationException while CopyOnWriteArraySet can not .
5. Added in java version : HashSet class was added in java version 1.2 , while CopyOnWriteArraySet class was added in java version 1.5 (or java 5) .
6. Package : HashSet class is present in java.util package , while CopyOnWriteArraySet class is present in java.util.concurrent package.
Example of ArraySet and CopyOnWriteArraySet in Java
import java.util.HashSet;import java.util.concurrent.CopyOnWriteArraySet;public class HashSetCopyOnWriteArraySetExample { public static void main(String[] args) {
HashSet<String> hsobj = new HashSet<String>();
hsobj.add("Alive is awesome");
hsobj.add("Love yourself");
System.out.println("HashSet object output :"+ hsobj);
CopyOnWriteArraySet<String> coponwrtobj =
new CopyOnWriteArraySet<String>();coponwrtobj.add("Alive is awesome");
coponwrtobj.add("Love yourself");
System.out.println("CopyOnWriteArraySet object output :"+ coponwrtobj);
}
}
Output : HashSet object output :[Alive is awesome, Love yourself]
CopyOnWriteArraySet object output :[Alive is awesome, Love yourself]
Similarities between HashSet and CopyOnWriteArraySet
1. Permit null values : Both HashSet and CopyOnWriteArraySet permits null.
2. Java Collections Framework : Both classes are part of the Java Collections Framework.
3. Duplicate elements : Both classes does not allow to store duplicate elements.
When to prefer CopyOnWriteArraySet over HashSet
CopyOnWriteArraySet is a thread-safe variant of HashSet in which all mutative operations (add , set and so on) are implemented by making a fresh copy of the underlying array.
So, if your code involves multi-threading tasks then prefer CopyOnWriteArraySet over HashSet.
Otherwise , always use HashSet .
Recap : Difference between HashSet and CopyOnWriteArraySet in Java
HashSet | CopyOnWriteArraySet | |
---|---|---|
Synchronized | No | Yes |
Thread-Safe | No | Yes |
Throws ConcurrentModificationException | Yes | No |
Iterator type | Fail fast iterator | Fail safe iterator |
Performance | Fast | Slow in comparision |
Added | Java 1.2 | Java 1.5 |
If you have any other questions or doubts regarding the difference between HashSet and CopyOnWriteArraySet in Java , please mention in comments.
Difference between Public, Private and Protected modifier in Java?
In Java, you have got something called access modifier, which specifies accessibility of class, methods and variables. There are four access modifier in Java namely public, private, protected and the default access modifier, also known as package level modifier. Difference between these access modifier comes in their ability to restrict access to a class, method or variables, public is the least restrictive access modifier while package is the most restrictive access modifier, package and protected lies in between. Another key difference between public, protected, package and private modifier comes from the point where you can apply them, for example you cannot use private or protected modifier with a top level class but you can use public modifier there. default modifier is little bit special, when you do not specify any of the public, protected and private modifier, which is also the keywords, then Java automatically apply a default modifier (no it doesn't use default keyword), which means the said class, method or member will only be accessible inside the package it has declared. Any class, which is outside the said package cannot access that element. Good thing about these concept is that, difference between public, protected and private in Java is also one of the frequently asked Java interview question. If you are looking for a Java development position and preparing for one then you can also take help from the wonderful book Java Interview Exposed by Wrox. It is one of the rare complete guide for a Java developer and tells which topic is important from interview point of view.
Read more »
Wednesday, August 19, 2015
How to reverse Integer in Java - LeetCode Solution
LeetCode has a problem to reverse digits of an integer number without using any library method like reverse() method of StringBuffer. In LeetCode, you can solve this problem with many different languages e.g. Java, C, C++, C#, Python, Ruby and even JavaScript. BTW, in article, we will learn how to solve this problem in Java. Before approaching solution let's first read the problem statement :
Reverse digits of an integer.
Example 1: x = 123, return 321
Example 2: x = -123, return -321
Problem looks simple but its not simple there are many things you need to consider in order to produce a solution which is accepted by LeetCode, which has thousands of test cases to test your solution. For example, you need to consider not just about positive integer but also about negative integer. Remember, positive integer can also be written using + sign, so you need to handle that as well. If the integer's last digit is 0, what should the output be? i.e. cases such as 10, 100. If return type of method is integer than you can simply return 1, its perfectly Ok, but if return type of method is String then you may need to return 001 or 0001. For purpose of this solution, we expect our method to return integer, so 1 is fine. By the way, if you are solving LeetCode problems as part of your interview preparation then you can also see Programming Interviews Exposed and Cracking the Coding Interview, two of the most useful books for preparing programming job interviews. You will learn more in short time.
Read more »
Reverse digits of an integer.
Example 1: x = 123, return 321
Example 2: x = -123, return -321
Problem looks simple but its not simple there are many things you need to consider in order to produce a solution which is accepted by LeetCode, which has thousands of test cases to test your solution. For example, you need to consider not just about positive integer but also about negative integer. Remember, positive integer can also be written using + sign, so you need to handle that as well. If the integer's last digit is 0, what should the output be? i.e. cases such as 10, 100. If return type of method is integer than you can simply return 1, its perfectly Ok, but if return type of method is String then you may need to return 001 or 0001. For purpose of this solution, we expect our method to return integer, so 1 is fine. By the way, if you are solving LeetCode problems as part of your interview preparation then you can also see Programming Interviews Exposed and Cracking the Coding Interview, two of the most useful books for preparing programming job interviews. You will learn more in short time.
Tuesday, August 18, 2015
Fire-IE-Selenium Tool To Find XPath, CSS Path Or Any Other Locator For IE Only WebSites
There are thousands of websites which are allowed to access only via Internet Explorer browser. Such IE only websites are not allowed to access through any other browsers like Firefox or google chrome so you can access such sites In Internet Explorer browser only. Supposing you need to automate such IE only website using selenium WebDriver. Is there any challenge?
Earlier In THIS POST, we learnt how to run selenium webdriver test In IE browser. Biggest challenge to automate such IE Only websites Is to find XPath or any other element locator of web page elements as IE browser do not have any add-on or extension which can provide us XPath or CSSPath directly. Generally we are using Firebug-FirePath Firefox add-on combination (As described In THIS POST) or Element locator for WebDriver Firefox add-on (As described In THIS POST) to get XPath of element. But these Firefox addons are useless as website Is accessible only In IE browser.
Download Fire-IEBrowser1.4.xlsm
There Is one tool called "fire-ie-selenium" which can help us to get element locators for IE only websites. It Is Fire-IEBrowser1.4.xlsm file using which we can get XPath or CSSselector of any element. To get this tool,
- Go to THIS PAGE
- Download Fire-IEBrowser1.4.zip file.
- Extract zip folder. You will get Fire-IEBrowser1.4.xlsm file from unzipped folder.
Using Fire-IEBrowser1.4.xlsm To Get XPath Or CssSelector
Let's take simple example of Google website to get XPath and CssSelector path of google search box and google search button.
Note : Tool Is being crashed with some websites and there Is not any online support for this tool. So use It If works with your website.
- Open Fire-IEBrowser1.4.xlsm file.
- Click on Options button. It will open Microsoft Office Security Options dialog as shown In bellow Image.
- Select Enable this content radio option from dialog and click on OK button.
- It will open FIRE IE BROWSER - WEB ELEMENT DETAILS dialog with Proceed button as shown In bellow Image. Click on Proceed button.
- It will open FIRE - HTML window as shown In bellow Image.
- There will be URL text field with LOAD button. Enter www.google.com In URL text box and click on LOAD button as shown In bellow Image. It will open Google WebSite Home page.
- Right click on Google Search textbox as shown In above Image. It will Open Object Description dialog. Enter "Google Search textbox" In text box and click on OK button as shown In above Image. It will save XPath, CSS Path and other details of Google Search text box In Fire-IEBrowser1.4.xlsm file's sheet.
- Perform above step for Google Search button and save It with name "Google Search button".
- Close FIRE - HTML window by right clicking at top of FIRE - HTML window and selecting Close as shown bellow Image. It will close FIRE - HTML window.
Now your Fire-IEBrowser1.4.xlsm file's sheet will looks like bellow.
You can see In above Image, Both element's Name, Tag Name, XPath, X-Path-Relative, OuterHTML, CSSPath and CSSSubPath are stored In sheet. Same way you can get all these detail of any element and use In Selenium WebDriver test script for IE only or any WebSite.
Monday, August 17, 2015
19 Java Method Overloading and Overriding Interview Questions and Answers
Method overloading and overriding is one of the tricky concept to master and that's why its one of the most popular topic in Java Interviews. You will often see questions like what is difference between overloading and overriding? or can you overload method in same class? during first few rounds of interview, mostly at telephonic round. Since its part of object oriented fundamentals its also good to know as much about these concepts as possible. In this article, I am sharing some of the basic but frequently asked questions which are solely based upon overloading and overriding concept and their implementation in Java programming language. By going through these questions, You will not only do well on interviews but also it will improve your understanding of Java and OOP fundamentals. BTW, if you are seriously preparing for Java interviews, just preparing this topic will not be enough and you need to prepare other important topics as well e.g. Java Collection framework, multi-threading, JVM internals and garbage collections etc. If you are in hurry, I would suggest you to take a look at Java Programming Interview Exposed by Wrox publication, one of the better book on Java interviews.
Read more »
Sunday, August 16, 2015
What Is Method Overloading In Java?
Method Overloading
Many peoples get confused between method overloading and method overriding in java. Earlier we learnt about method overriding in THIS POST. Method overloading concept is totally different than method overriding. If interviewer asks you question about method overloading then your answer should be like this "When class have two or more methods with same name but different parameters, it is called method overloading". Lets try to understand method overloading concept with example.
Method Overloading Example
We can achieve method overloading by changing number of arguments or by changing data types of arguments for same name methods in single class.
Method overloading by changing number of arguments
In bellow given example you can see that we have created two overloaded methods. 1st sum method will accept 2 arguments and 2nd sum method will accept 3 arguments to perform sum operation. This is called method overloading by changing number of arguments.
public class OverloadingByArgument {
void Sum(int i, int j) {
System.out.println(i + j);
}
void Sum(int i, int j, int k) {
System.out.println(i + j + k);
}
public static void main(String args[]) {
OverloadingByArgument ol = new OverloadingByArgument();
ol.Sum(10, 10, 10); //It will call Sum(int i, int j, int k)
ol.Sum(20, 20);//It will call Sum(int i, int j)
}
}
OutPut
30
40
Method overloading by changing data types of arguments
You can also overload method by changing data types of argument. Here number of arguments can be same or different as per requirement. In bellow given example, Class have two sum methods with same number of arguments but different datatypes. 1st sum method will be called when you wants to sum two integer values and 2nd sum method will be called when you wants to sum two double values. You can use any other datatypes too.
public class OverloadingByDataTypes {
void Sum(int i, int j) {
System.out.println(i + j);
}
void Sum(double i, double j) {
System.out.println(i + j);
}
public static void main(String args[]) {
OverloadingByDataTypes ol = new OverloadingByDataTypes();
ol.Sum(10.75, 10.5); //It will call Sum(double i, double j)
ol.Sum(20, 20);//It will call Sum(int i, int j)
}
}
OutPut
21.25
40
Advantage of Method Overloading
Using method overloading, We can create multiple methods with same name in same class to perform same action in different ways (using different number of arguments and it's datatypes). It will increases the readability of the program. We can overload static methods too. view more java tutorials on THIS PAGE.
Saturday, August 15, 2015
How LinkedHashMap Works Internally in Java
Please go through how HashMap works internally in java first before reading further about the internal working of LinkedHashMap.
Interviewer : What is LinkedHashMap ?
LinkedHashMap is the Hashtable (synchronized HashMap) and linkedlist implementation of the Map interface , with predictable iteration order.
Read Also : HashSet Interview questions
Interviewer :Why do we need LinkedHashMap when we already had TreeMap and HashMap ?
TreeMap and HashMap classes were added in java 1.2 , while LinkedHashMap was added to jdk in java version 1.4 .
HashMap provides constant time performance for basic operations like (add, remove and contains) method but elements are unordered. In TreeMap elements are naturally sorted but there is increased cost associated with it. Performance of the basic operations (get, remove or put) in TreeMap is slower in comparison i.e log(n) time.
So, LinkedHashMap addition removes the chaotic ordering provided by HashMap, without incurring the increased cost associated with TreeMap.
Internal Working of LinkedHashMap in Java
According to Oracle docs ,
We have already shared the internal working of HashMap . HashMap maintains a simple linked list while running through all of its entries.
Interviewer : How LinkedHashMap insertion order is maintained ?
The order is maintained based on the keys were inserted into the map .
Interviewer : What happens if we insert a key which is already present in the LinkedHashMap ? Does the order change ?
Insertion order of the LinkedHashMap does not get affected if a key is re-inserted into the LinkedHashMap object.
It first checks containsKey() method before invoking put() method . If containsKey(K) returns true then the key is not added to the LinkedHashMap.
Interviewer : What is the time complexity of the add , remove and contains operations in LinkedHashMap ?
Time complexity of the add, remove and contains operations is constant time i.e O(1) .
Interviewer : Does LinkedHashMap Iterator behaves like fail fast iterator or fail-safe iterator ?
LinkedHashMap iterator behaves like fail-fast iterator. As expected it will throw ConcurrentModificationException. We have already shared fail safe and fail fast iterator explanation.
Interviewer : Can you write an simple example which proves that LinkedHashMap behaves like fail fast iterator ?
LinkedHashMap Example :
Interviewer : What is LinkedHashMap ?
LinkedHashMap is the Hashtable (synchronized HashMap) and linkedlist implementation of the Map interface , with predictable iteration order.
Read Also : HashSet Interview questions
Interviewer :Why do we need LinkedHashMap when we already had TreeMap and HashMap ?
TreeMap and HashMap classes were added in java 1.2 , while LinkedHashMap was added to jdk in java version 1.4 .
HashMap provides constant time performance for basic operations like (add, remove and contains) method but elements are unordered. In TreeMap elements are naturally sorted but there is increased cost associated with it. Performance of the basic operations (get, remove or put) in TreeMap is slower in comparison i.e log(n) time.
So, LinkedHashMap addition removes the chaotic ordering provided by HashMap, without incurring the increased cost associated with TreeMap.
Internal Working of LinkedHashMap in Java
According to Oracle docs ,
LinkedHashMap implementation differs from HashMap in that it maintains a doubly linked list running through all of its entries.
We have already shared the internal working of HashMap . HashMap maintains a simple linked list while running through all of its entries.
Interviewer : How LinkedHashMap insertion order is maintained ?
The order is maintained based on the keys were inserted into the map .
Interviewer : What happens if we insert a key which is already present in the LinkedHashMap ? Does the order change ?
Insertion order of the LinkedHashMap does not get affected if a key is re-inserted into the LinkedHashMap object.
It first checks containsKey() method before invoking put() method . If containsKey(K) returns true then the key is not added to the LinkedHashMap.
Interviewer : What is the time complexity of the add , remove and contains operations in LinkedHashMap ?
Time complexity of the add, remove and contains operations is constant time i.e O(1) .
Interviewer : Does LinkedHashMap Iterator behaves like fail fast iterator or fail-safe iterator ?
LinkedHashMap iterator behaves like fail-fast iterator. As expected it will throw ConcurrentModificationException. We have already shared fail safe and fail fast iterator explanation.
Interviewer : Can you write an simple example which proves that LinkedHashMap behaves like fail fast iterator ?
LinkedHashMap Example :
import java.util.LinkedHashMap;
import java.util.Iterator;
public class LinkedHashMapExample
{
public static void main(String[] args)
{
LinkedHashMap<String,String> premiumPhone = new LinkedHashMap<String,String>();
premiumPhone.put("Apple", "iPhone6");
premiumPhone.put("HTC", "HTC one");
premiumPhone.put("Samsung","S6");
Iteratoriterator = premiumPhone.keySet().iterator();
while (iterator.hasNext())
{
System.out.println(premiumPhone.get(iterator.next()));
premiumPhone.put("Sony", "Xperia Z");
}
}
}
Output :
iPhone
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
at java.util.HashMap$KeyIterator.next(Unknown Source)
at LinkedHashMapExample.main(LinkedHashMapExample.java:20)
Please do mention in the comments in case you have any questions regarding LinkedHashMap .
Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger in Java
Problem : You are getting Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger error in your Java application, which is using Log4j Logger either directly or indirectly via some popular Java framework like Spring, Struts or Hibernate.
Read more »
Thursday, August 13, 2015
How to swap two Integers without using temporary variable in Java?
One of the oldest trick question from programming interview is, How do you swap two integers without using temp variable? This was first asked to me on a C, C++ interview and then several times on various Java interviews. Beauty of this question lies both on trick to think about how you can swap two numbers with out third variable, but also problems associated with each approach. If a programmer can think about integer overflow and consider that in its solution then it creates a very good impression in the eye of interviewers. Ok, so let's come to the point, suppose you have tow integers i = 10 and j = 20, how will you swap them without using any variable so that j = 10 and i = 20? Though this is journal problem and solution work more or less in every other programming language, you need to do this using Java programming constructs. You can swap numbers by performing some mathematical operations e.g. addition and subtraction and multiplication and division, but they face problem of integer overflow. There is a neat trick of swapping number using XOR bitwise operator which proves to be ultimate solution. We will explore and understand each of these three solutions in detail here, and if you are hungry for more programming questions and solutions, you can always take a look at Cracking the Coding Interview: 150 Programming Questions and Solutions, one of the best book to prepare for programming job interviews.
Read more »
Wednesday, August 12, 2015
How To Handle SSL Certificate Error In IE Browser For Selenium WebDriver Test
Earlier we learnt how to handle SSL certificate error by creating custom profile In selenium WebDriver test when you run It In Firefox browser as described In THIS POST. IE browser do not have any such feature to create and run test In custom profile. So you need to do something different for IE browser to resolve certificate related error when you run WebDriver test.
As you know, we can resolve error "Enable protected mode for all zones" as described In THIS POST and Set IE browser Zoom Level To 100% Error as described In previous post. Now let's see how to resolved SSL certificate error In IE browser for selenium WebDriver test.
When you see SSL certificate error In IE browser, Your screen will looks like bellow.
There Is one option link with text "Continue to this website (not recommended)." If somehow we can click on this link then original site page will be loaded and our test script can go further for execution. If you view link In HTML mode using F12 then you will realize that link has ID called "overridelink". We can click on that link using driver.navigate() method with Javascript as bellow.
//To click on "Continue to this website (not recommended)." link to load original website.
driver.navigate().to("javascript:document.getElementById('overridelink').click()");
This solution Is worked for me In many website's tests. Full example demonstration Is as bellow.
package Testing_Pack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class SSLErrorInIE {
public static void main(String[] args) {
// Set path of IEDriverServer.exe
// Note : IEDriverServer.exe should be In D: drive.
System.setProperty("webdriver.ie.driver", "D://IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("URL of SSL error site");
//To click on "Continue to this website (not recommended)." link to load original website.
driver.navigate().to("javascript:document.getElementById('overridelink').click()");
}
}
This way we can resolve SSL certificate error In IE browser. View THIS ARTICLE to know how to handle SSL cretificate error in google chrome browser.
Sunday, August 9, 2015
What Is An Abstract Class In Java?
What Is An Abstract Class?
If you will go to attend an interview for selenium WebDriver with java , 90% Interviewer will ask you this question. Your answer should be like this : An abstract class is a class that is declared with abstract keyword. If class contains any abstract method then you must have to declare your class as abstract class. Also abstract classes can be subclassed, but they cannot be instantiated. That means you can not create object of abstract class. It may or may not have abstract methods. it can have concrete methods too so that it does not provide 100% abstraction.
Earlier we learnt interface in THIS POST. It is 100% abstraction. View THIS POST to know difference between abstract class and interface.
Bellow given class has abstract method so it is declared as abstract class.
//abstract class
public abstract class Animal {
//concrete method
public void eat(String food) {
// do something with food....
}
// abstract method
public abstract void makeNoise();
}
Let's try to understand abstract class and abstract methods in detail.
What Is Abstraction in Java?
Abstraction is process of hiding implementation details from user. User can use only functionality but can not see how it is implemented. Example : Calling a friend is best example of abstraction. Here you can talk with each other but you don't know about internal implementation of your phone and it's network using which you can talk. It is called abstraction.
What Is Abstract Method?
If any method is declared with abstract keyword then it is called abstract method. Abstract method can not have a body. Actual implementation of abstract method will be done by it's child class. If any class extends abstract class then that subclass must have to implement all the abstract methods declared by it's super class(abstract class).
Example of abstract class with simple and concrete methods is as bellow.
Animal.javapackage abstraction;
//abstract class
public abstract class Animal {
// concrete method. Sub class can use it if needed.
public void eat(String food) {
// do something with food....
}
// concrete method. Sub class can use it if needed.
public static void sleep(int hours) {
// do something with sleep....
}
// abstract method. Sub classes must have to implement it if extend this class.
public abstract void makeNoise();
}
Bellow given classes are sub classes of Animal class so both of them have implemented abstract method of Animal abstract class. But they do not need to implement concrete methods of super class. They can declare and implement their own concrete methods independently.
Dog.java
package abstraction;
public class Dog {
// abstract method of super class is implemented in sub class.
public void makeNoise() {
System.out.println("Bark! Bark!");
}
// Concrete method
public void payingBall() {
System.out.println("Dog is playing with ball");
}
}
Cow.java
package abstraction;
public class Cow extends Animal {
// abstract method of super class is implemented in sub class.
public void makeNoise() {
System.out.println("Moo! Moo!");
}
// Concrete method
public void milking() {
System.out.println("Cow is milking");
}
}
When And Why To Use Abstract Class?
If you see at above example, Abstract class is not only template for it's child classes but it has it's own functionality too. Like eat(String food), sleep(int hours). Both these methods are concrete but child class can use them if required.
You can use abstract class as parent class for sub classes
- When you expect to implement same method in all sub classes with different implementation detail.
- When you expect to implement methods in super class(abstract class) which can be used by its sub classes if needed.
- When you expect to implement independent method in sub class which do not have any relation or use with its super class.
Points to Remember About Abstract Class
- If class is declared with abstract keyword then it is called abstract class.
- If class has abstract method, you must have to declare class as abstract class.
- In abstract class, You can only declare abstract methods but you can not define abstract methods.
- Sub classes of abstract class must have to implement all abstract methods of super abstract class.
- You can not instantiate(Can not create object of) abstract class.
- Abstract classes can have concrete methods, constructors and Member variables too.
Tuesday, August 4, 2015
How To Find Broken Links/Images From Page Using Selenium WebDriver Example
If you remember, Earlier we learnt how to extract all links from page In THIS POST. Extracting all links from page Is not useful If you don't know all the links are working fine or some of them are broken links or supposing there are few broken Images links. How to find these broken links or broken Images from page using selenium WebDriver? This Is part of testing In which you need to
check status of links/Images -> 1) Link URLs are opening targeted page 2) Images display properly on page or not. If links are Incorrect then It will not work.Finding each and every link from page and verifying It manually will take lots of your time. You will find many broken link checker tools online. You can perform same task using selenium WebDriver. Lets see example on finding broken links from single page.
In bellow given example, First of all I have calculated total number of links on page. Then extracted all links one by one and check Its response code by calling getResponseCode function. I have used apache Interface HttpResponse to get the response code of URL. If It Is 200, that means link URL Is not broken and working fine. But If response code Is 404 or 505 that means link or Image IS broken.
In bellow given example, I have used test page where one link and Img URL Is broken to show you practically how It will differentiate those links from valid links. Execute bellow given selenium WebDriver test example In your eclipse and verify result In console. Console result will show you status of link URL If It Is broken or not.
package Testing_Pack;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class BrokenlinksTest {
public static void main(String[] args) throws IOException {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2013/09/testing.html");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//Find total No of links on page and print In console.
List<WebElement> total_links = driver.findElements(By.tagName("a"));
System.out.println("Total Number of links found on page = " + total_links.size());
//for loop to open all links one by one to check response code.
boolean isValid = false;
for (int i = 0; i < total_links.size(); i++) {
String url = total_links.get(i).getAttribute("href");
if (url != null) {
//Call getResponseCode function for each URL to check response code.
isValid = getResponseCode(url);
//Print message based on value of isValid which Is returned by getResponseCode function.
if (isValid) {
System.out.println("Valid Link:" + url);
System.out.println("----------XXXX-----------XXXX----------XXXX-----------XXXX----------");
System.out.println();
} else {
System.out.println("Broken Link ------> " + url);
System.out.println("----------XXXX-----------XXXX----------XXXX-----------XXXX----------");
System.out.println();
}
} else {
//If <a> tag do not contain href attribute and value then print this message
System.out.println("String null");
System.out.println("----------XXXX-----------XXXX----------XXXX-----------XXXX----------");
System.out.println();
continue;
}
}
driver.close();
}
//Function to get response code of link URL.
//Link URL Is valid If found response code = 200.
//Link URL Is Invalid If found response code = 404 or 505.
public static boolean getResponseCode(String chkurl) {
boolean validResponse = false;
try {
//Get response code of URL
HttpResponse urlresp = new DefaultHttpClient().execute(new HttpGet(chkurl));
int resp_Code = urlresp.getStatusLine().getStatusCode();
System.out.println("Response Code Is : "+resp_Code);
if ((resp_Code == 404) || (resp_Code == 505)) {
validResponse = false;
} else {
validResponse = true;
}
} catch (Exception e) {
}
return validResponse;
}
}
Console output for above example execution will looks like bellow.
This way you can find broken links or Images from any page using selenium WebDriver.
<< PREVIOUS || NEXT >>
How to load data from CSV file in Java - Example
You can load data from a CSV file in Java program by using BufferedReader class from java.io package. You can read the file line by line and convert each line into an object representing that data. Actually there are couple of ways to read or parse CSV file in Java e.g. you can use a third party library like Apache commons CSV or you can use Scanner class, but in this example we will use traditional way of loading CSV file using BufferedReader.
Read more »
Subscribe to:
Posts (Atom)