0% found this document useful (0 votes)
28 views74 pages

Interview Questionsandanswers

The document discusses criteria for automating tests, such as how often a test needs to be executed, how much time it will save, how important it is to the business, and how likely it is to catch defects. It also discusses what types of tests should not be automated, like usability testing. Finally, it covers pros and cons of UI testing and reasons for automating tests.

Uploaded by

gkwveer.veer16
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views74 pages

Interview Questionsandanswers

The document discusses criteria for automating tests, such as how often a test needs to be executed, how much time it will save, how important it is to the business, and how likely it is to catch defects. It also discusses what types of tests should not be automated, like usability testing. Finally, it covers pros and cons of UI testing and reasons for automating tests.

Uploaded by

gkwveer.veer16
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

What Criteria Do You Consider For Automating A Test?

I would consider the following points to help me decide if a test should be


automated:

❖ How often does the test need to be executed? i.e. is that going to be a regression test?
Sometimes the test will need to be executed once, but with a large set of data
❖ How much time does automating this test will save me so that I can use my time in
exploratory testing
❖ How important is the test to the business; i.e. is the test scenario a typical user journey
through the application
❖ How complex is it to automate the test and how likely is it that the complexity doesn’t
cause many false positives which increases results analysis time?
❖ How likely is it that this test catches a defect?
❖ How likely is it that a feature or functionality will break and what is the impact of it to
the business? If it is high impact, then it should be automated to ensure it passes from
release to release

What Kind Of Tests Should NOT Be Automated?

This interview question is similar to previous question but focuses on which


tests Not to be automated and left for manual testing. Possible answers can be:

❖ Usability Testing – at times this can be an impossible task to perform by automation as


the computer cannot efficiently judge if the system is of any use to its users
❖ Tests that only need to be executed once – unless the same test needs to be executed for a
large dataset then it makes sense to automate
❖ Tests without predictable results – test automation should give us confidence in the
results of the tests. If there are intermittent failures then the tests cannot be reliable and
cannot be dependent on
❖ Tests that need to be verified visually
❖ Tests that need to be executed quickly. At first, writing an automated test takes longer. If
we want a quick check, we should test manually, however, if that test is a good one which
should be run regularly, then it should be automated in time

What Are Pros And Cons Of Automating Tests At UI Layer?

Pros

❖ UI automated tests execute in a way that simulates user interacting with the system. So it
is very good for validating user journeys and flows
❖ Can cover end-to-end flows that communicate with 3rd party systems
❖ Because tests are run against the system, they can be demoed to the customer who can
understand what tests are run
❖ Can catch high severity or show stopper bugs
❖ Can check UI functionality where it is not possible to test otherwise

Cons

▪ UI automated tests can be very brittle (i.e. fail due to UI changes even though functionality
hasn’t changed)
▪ Slow feedback to the team. Execution is slow as you have to wait for the system to launch
and connections with 3rd party system can take a long time
▪ Limitation on what can be checked from the UI. There are some information that are not
present from the UI
▪ Because tests are slow from UI, we can’t have a lot of tests running against the UI
▪ Can be time consuming to construct automated test scripts for the UI
▪ Usually have to depend on a 3rd party tool or vendor for UI testing

Why Would You Want To Automate A Test? Is It To:


▪ Increase test coverage?
▪ Improve quality?
▪ Save time for exploratory testing?
▪ Find more bugs?
▪ Replace manual testers?

What are the differences between open source tools, vendor tools, and in-house tools?

❖ Open source tools are free to use frameworks and applications. Engineers build the tool,
and have the source code available for free on the internet for other engineers to use.

❖ Vendor tools are developed by companies that come with licenses to use, and often cost
money. Because they are developed by an outside source, technical support is often
available for use. Example vendor tools include WinRunner, SilkTest, Rational Robot,
QA Director, QTP, LR, QC, RFT, and RPT.

❖ An in-house tool is a tool that a company builds for their own use, rather than purchasing
vendor tools or using open source tools.

How do you choose which automation tool is best for your specific scenario?
In order to choose the proper automation testing tool, you must consider:

● the scope of the project


● the limitation of the tool
● how much the tool costs
● the tool’s usability and convenience
● the testing environment
● compatibility

1. What Is Selenium WebDriver/Selenium 2?


❖ Selenium WebDriver Is well designed object oriented API which Is developed to
automate web and mobile applications testing process. WebDriver API Is bigger than
Selenium RC but its Architecture Is simple and easy to understand compared
Selenium RC API.

❖ We can automate our web application testing process using selenium webdriver.
❖ We can say It advanced version of selenium RC because some limitations of selenium
RC has been overcome In selenium WebDriver.
❖ WebDriver Is designed to provide better support for dynamic changing
pages. ​Example: ​Web page elements changing without reloading the page. In this
case WebDriver works better.
❖ Selenium Webdriver Is more faster that Selenium RC as It Is directly Interacting with
web browsers and mimic the behavior of a real user. ​Example : ​User clicks on button
of web page or moving mouse on main menu to get the sub menu list. WebDriver
works Same.
❖ All popular browser vendors are active participants In selenium WebDriver's
development and all of them have their own engineers team to Improve this
framework.

2. Tell Me WebDriver Supported Browsers?


Answer​: ​Selenium WebDriver API has a many different drivers to test your web
application In different browsers. List of Webdriver browser drivers are as bellow​.
❖ Firefox Driver​ - For Mozilla Firefox browser
❖ Internet Explorer Driver​ - For Internet Explorer browser
❖ Chrome Driver​ - For Google Chrome browser
❖ HtmlUnit Driver​ - GUI-Less(Headless) browser for Java programs
❖ Opera Driver​ - For Opera browser

3. Tell Me WebDriver Supported Mobile Testing Drivers?

Answer​: We can get support of mobile application testing using Selenium webdriver. Selenium
WebDriver supports bellow given drivers to test mobile application.
❖ AndroidDriver
❖ OperaMobileDriver
❖ IPhoneDriver

​4 :​ ​Which Programming Languages Supported By Selenium WebDriver To Write Test


Cases?
Answer​ : ​Selenium WebDriver Is very wast API and It support many different languages to
write test cases for your software web application. List of WebDriver supported languages are as
bellow.
❖ Java
❖ C#
❖ Python
❖ Ruby
❖ Perl
❖ PHP

5 :​ ​Which Different Element Locators Supported By Selenium WebDriver?


Answer​: Selenium WebDriver supports bellow given element locators.

❖ XPath Locator
❖ CSSSelector Locator
❖ ClassName Locator
❖ ID Locator
❖ Name Locator
❖ LinkText Locator
❖ PartialLinkText Locator
❖ TagName Locator

6​: ​Does Selenium WebDriver Support Record And Playback Facility?


Answer​ : No. WebDriver do not have any record and playback facility. But you can record your
tests In one of the selenium version called Selenium IDE and then you can export your recorded
tests In webdriver compatible format as per your preferred language.

8 :​ ​Which Operating systems support Selenium WebDriver?


Answer​ : At present, Mainly bellow given operating systems support Selenium
WebDriver.

❖ Windows ​- Windows XP, Windows 7, Windows 8 and Windows 8.1


❖ Apple OS X
❖ Linux ​- Ubuntu. Other versions of linux should support too.

9.​ ​Selenium WebDriver Is Paid Or Open Source Tool? Why you prefer to use It?​

Answer​ : All versions of selenium tool are open source. You can use any version of selenium In free of
charge.

I choose to use It because


❖ Open Source.
❖ It has multi-browser support.
❖ Multi-OS support.
❖ Multi types of locators support. So If one not works, We can use another type.
❖ Web as well mobile application testing support.
❖ Many testers are using selenium WebDriver to automate their testing process. So getting
solution of any complex Issue very easily on Internet.
❖ It Is extendable and flexible.
❖ Continues support from WebDriver's development team to Improve the API and resolve
current Issues.
10. ​Which OpenSource Framework Is Supported In WebDriver With Java?
Answer​ : Bellow given 2 java frameworks are supported by selenium WebDriver.

● JUnit
● TestNG

11 :​ ​Can you tell me the syntax to open/launch Firefox browser In WebDriver?


Answer​ : We can open new Mozilla Firefox browser Instance using bellow given
syntax.

WebDriver driver = new FirefoxDriver();

12 :​ ​What Is XPath and what Is use of It In WebDriver?


Answer : ​In Selenium WebDriver, XPath is used to locate the elements. Using XPath, We can
navigate through elements and attributes In an XML document to locate webpage elements like
buttons, text box, links, Images etc..

13 :​ ​Which tool you are using to find the XPath of any element?
Answer​ : ​I am using Mozilla Firefox AddOns FireBug and FirePath to find the XPath of web
elements.
14. ​What is the difference between absolute XPath and relative XPath?

Absolute XPath​ : ​Absolute XPath Is the full path starting from root node and ends
with desired descendant element's node. It will start using single forward slash(/) as bellow.
Example Of Absolute XPath​ :

/html/body/div[3]/div[2]/div[2]/div[2]/div[2]/div[2]/div[2]/div/div[4]/div[1]/d
iv/div/div/div[1]/div/div/div/div[1]/div[2]/form/table/tbody/tr[1]/td/input

Above XPath Is absolute XPath of calc result box given on ​THIS PAGE​. It starts top node html
and ends with input node.

Relative XPath​ : ​Instead of starting from root node, Relative XPath starts from any In
between node or current element's node(last node of element). It will start using double forward
slash(//) as​ bellow.
Example Of Relative XPath​ :
//input[@id='Resultbox']

15 :​ ​How To Handle Dynamic Changing IDs In XPath.


Example : //div[@id='post-body-3647323225296998740']/div[1]/form[1]/input[1]
In this XPath "3647323225296998740" Is changing every time when reloading the page. How to
handle this situation?
Answer​ : ​There are many different alternatives In such case.

Alternative ​ : Look for any other attribute which Is not changing every time In that div node like
name, class etc. So If this div node has class attribute then we can write xpath as bellow.

//div[@class='post-body entry-content']/div[1]/form[1]/input[1]

Alternative 2​ : You can use absolute xpath(full xpath) where you not need to give any attribute names
In xpath.

/html/body/div[3]/div[2]/div[2]/div[2]/div[2]/div[2]/div[2]/div/div[4]/div[1]/d
iv/div/div/div[1]/div/div/div/div[1]/div[2]/div[1]/form[1]/input[1]

Alternative 3​ : Use starts-with function. In this xpath's ID attribute, "post-body-" part remain same
every time. So you can use xpath as bellow.

//div[starts-with(@id,'post-body-')]/div[1]/form[1]/input[1]

Alternative 4​ : ​Use contains function. Same way you can use contains function as bellow.

div[contains(@id,'post-body-')]/div[1]/form[1]/input[1]

16 :​ ​How to press ENTER key button on text box In selenium webdriver?


Answer​ : ​To press ENTER key using selenium WebDriver, We need to use
selenium Enum Keys with Its constant ENTER as bellow.

driver.findElement(By.xpath("//input[@id='gbqfq']")).sendKeys(Keys.ENTER);

17 :​ ​How many types of waits available In selenium WebDriver


Answer​ : ​There are two types of waits available In selenium WebDriver.
1. Implicit Wait
2. Explicit Wait

18 :​ ​What Is Implicit Wait In Selenium WebDriver?


Answer​ : ​Sometimes, Elements are taking time to be appear on page. Using Implicit wait In
webdriver test case, We can poll the DOM for certain amount of time when some element or
elements are not available Immediately on webpage.
Implicit Wait Example​ :

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

19 :​ ​What Is Explicit Wait In Selenium WebDriver?


Answer​ : ​Using explicit wait code In selenium webdriver, You can define to wait for a certain
condition to occur before proceeding further test code execution.

Explicit Wait Example​ :

WebDriverWait wait = new WebDriverWait(driver, 20);


wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@id='gbqfq

Above code will wait for 20 seconds for targeted element to be displayed and
enabled or we can say clickable.

20 :​ ​I wants to pause my test execution for fix 10 seconds at specific point. How can I do It?
Answer​ : ​You can use ​java.lang.Thread.sleep(long milliseconds)​ method to pause the test
execution for specific time. If you wants to pause your test execution for 10 seconds then you
can use bellow given syntax In your test.

Thread.sleep(10000);

21 :​ ​How does selenium RC drive the browser?​


Answer​ :​When browser loaded In Selenium RC, It ‘injected’ javascript functions into the browser
and then It Is using javascript to drive the browser for application under test.

22 :​ ​How does the selenium WebDriver drive the browser?


Answer​ : ​Selenium webdriver works like real user Interacting with web page and Its elements.
It Is using each browser's native support to make direct calls with browser for your application
under test. There Is not any Intermediate thing In selenium webdriver to Interact with web
browsers.

23 :​ ​Do you need Selenium Server to run your tests In selenium WebDriver?
Answer​ : ​It depends. If you are using only selenium webdriver API to run your tests and you
are running your all your tests on same machine then you do not need selenium server because In
this case, webdriver can directly Interact with browser using browser's native support.

You need selenium server with webdriver when you have to perform bellow given operations
with selenium webdriver.

❖ When you are using remote or virtual machine to run your webdriver tests and that machine
have specific browser version that is not on your current machine.

❖ When you are using selenium-grid to distribute your webdriver's test execution on different
remote or virtual machines.

24 :​ ​Bellow given syntax will work to navigate to specified URL In WebDriver? Why?

driver.get("​www.google.com​");

Answer​ : ​No​. It will not work and show you an exception like : "Exception in thread "main"
org.openqa.selenium.WebDriverException: f.QueryInterface is not a function" when you run your
test.

You need to provide ​http://​ protocol with URL In ​driver.get​ method as bellow.

driver.get("http://www.google.com");

Now It will work​.

25 :​ ​Tell me a reason behind bellow given WebDriver exception and how will you resolve
It?
"Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate
element"
Answer​ : You will get this exception when WebDriver Is not able to locate element on the page
using whatever locator you have used In your test. To resolved this Issue, I will check bellow
given things.
● First of all I will check that I have placed Implicit wait code In my test or not. If you have
not placed Implicit timeout In your test and any element Is taking some time to appear on page
then you can get this exception. So I will add bellow given line at beginning of my test case code
to wait for 15 seconds for element to be present on page. In 70% cases, this step will resolved
Issue.
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

Another reason behind this Issue Is element's ID Is generated dynamically every time when
reloading the page. If I have used element's ID as an element locator or used It In xpath to locate
the element then I need to verify that ID of element remains same every time or It Is changing? If
It Is changing every time then I have to use alternative element locating method. In 20% cases,
This step will resolve your Issue.

If Implicit wait Is already added and element locator Is fine then you need to verify that how
much time It(element) Is taking to appear on page. If It Is taking more than 15 seconds then you
have to ​put explicit wait condition with 20 or more seconds wait period as bellow. In 5 to 10%
cases, This step will resolve your Issue.​

WebDriverWait wait = new WebDriverWait(driver, 25);


wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#submitButto
n")));

26 :​ ​Can we automate desktop application's testing using selenium WebDriver?


Answer​ : No. This Is the biggest disadvantage of selenium WebDriver API. We can
automate only web and mobile application's testing using selenium WebDriver.

27 :​ ​Can you tell me the alternative driver.get() method to open URL In browser?
Answer​ : We can use anyone from bellow given two methods to open URL In web
browser In selenium webdriver.
1. driver.get()
2. driver.navigate().to()

28 :​ ​Can you tell me a difference between driver.get() and driver.navigate() methods?


Answer​ : Main and mostly used functions of both methods are as bellow.

driver.get()

❖ driver.get() method Is generally used for Open URL.


❖ It will wait till the whole page gets loaded.

driver.navigate()
❖ driver.navigate() method Is generally used for navigate to URL, navigate back, navigate
forward, refresh the page.
❖ It will just navigate to the page but wait not wait till the whole page gets loaded.

29 :​ ​WebDriver has built In Object Repository. Correct me If I am wrong.


Answer​ : No. WebDriver do not have any built In object repository till now. But
yes, I am using java .properties file In my framework to store all required
element objects In my tests.

30 :​ ​Can you tell me syntax to set browser window size to 800(Width) X 600(Height)?
Answer​ : We can set browser window size using ​setSize ​method of selenium
webdriver. To set size at 800 X 600, Use bellow given syntax In your test case.

driver.manage().window().setSize(new Dimension(500,500));

31 :​ ​Can you tell me the names of different projects of selenium?


Answer​ : At present, Selenium has four different projects as bellow.
❖ Selenium IDE​ : It Is Firefox add-on which allows you to record and playback your tests In
Firefox browser.
❖ Selenium RC​ : It Is web application automation tool which allows you to write your tests In
many different programming languages.
❖ Selenium WebDriver​ : It Is well designed object oriented API developed to automate web and
mobile application testing process. You can write your tests In different languages too In
selenium webdriver.
❖ Selenium Grid​ : Grid allows you to execute your tests In parallel by distributing them on
different machines having different browser/OS combinations.

32 :​ ​I wants to use java language to create tests with Selenium WebDriver. Can you tell me
how to get latest version of WebDriver?
Answer​ : You can download language specific latest released client drivers for
selenium WebDriver at ​http://docs.seleniumhq.org​ official website. For java
language, You will get bunch of jar files In zip folder. And then you can add all
those jar files In your project's java build path as a referenced libraries to get
support of webdriver API.

33 :​ ​Can you tell me the usage of "submit" method In selenium WebDriver?


Answer​ : We can use submit method to submit the forms In selenium WebDriver.
Example : Submitting registration form, submitting LogIn
form, submitting Contact Us form ect.. After filling all required fields, We can call
submit method to submit the form.

34 :​ ​Do you have faced any Issue with "submit" method any time?
Answer​ : Yes, I have faced Issue like submit method was not working to submit
the form. In this case, Submit button of form was located outside the opening
<form> and closing </form> tags. In this case submit method will not works to
submit the form.

Also If submit button Is located Inside opening ​<form>​ and closing​</form>​ tags
but that button's ​type ​tag's attribute Isn't ​submit ​then submit method will not
work. It(​type ​tag's attribute) should be always submit.

35 :​ ​What Is the syntax to type value In prompt dialog box's Input field using selenium
WebDriver?
Answer​ : Prompt dialog Is just like confirmation alert dialog but ​with option of
Input text box​ as bellow.

To Input value In that text box of prompt dialog, You can use bellow given syntax.

driver.switchTo().alert().sendKeys("Jhon");

36 :​ ​When I am running tests In Firefox Browser using selenium webdriver, It Is not


showing me any bookmarks, addons, saved passwords etc. In that browser. Do you know
why?

Answer​ : Yes. It Is because all those bookmarks, addons, passwords etc.. are
saved In your regular browser's profile folder so when you launch browser
manually, It will use existing profile settings so
It will show you all those stuffs. But when you run your tests In selenium
webdriver, It Is opening new browser Instance with blank/new profile. So It will
not show you bookmarks and all those things In that browser Instance.
You can create custom firefox profile and then you can use It In selenium
webdriver test. In your custom profile, you can set all required bookmarks,
addons etc..

37 :​ ​Arrange bellow given drivers In fastest to slowest sequence?


Firefox Driver, HtmlUnit Driver, Internet Explorer Driver.

Answer​ : HTMLUnit Driver Is faster than all other drivers because It Is not using
any UI to execute test cases. Internet Explorer driver Is slower than Firefox and
HtmlUnit driver. So, Fastest to slowest driver sequence Is as bellow.
1. HtmlUnit Driver
2. Firefox Driver
3. Internet Explorer Driver

38 :​ ​What Is Ajax?
Answer​ : ​Asynchronous JavaScript and XML​ Is full form of AJAX which Is used
for creating dynamic web pages very fast. Using ajax, We can update page behind
the scene by exchanging small amounts of data with server asynchronously. That
means, Using ajax we can update page data Without reloading page.

39 :​ ​How to handle Ajax In selenium WebDriver?


Answer​ : Generally we are using ​Implicit wait​ In selenium WebDriver to wait for
some element to be present on page. But Ajax call can not be handled using only
Implicit wait In your test because page not get reloaded when ajax call sent and
received from server and we can not assume how much time It will take to
receive ajax call from server.

To handle ajax call In selenium WebDriver, We needs to use


webdriver's FluentWait method or Explicit Waits which can wait for specific
amount of time with specific condition. You can get different Explicit Waits
examples links on ​THIS PAGE​.

40 :​ ​On Google search page, I wants to search for some words without clicking on Google
Search button. Is It possible In WebDriver? How?
Answer​ : Yes we can do It using WebDriver ​sendKeys​ method where we do not
need to use Google Search button. Syntax Is as bellow.
driver.findElement(By.xpath("//input[@id='gbqfq']")).sendKeys("Search
Syntax",Keys.ENTER);

In above syntax, ​//input[@id='gbqfq']​ Is xPath of Google search text field. First It


will enter "Search Syntax" text In text box and then It will press Enter key on
same text box to search for words on Google.

41​ : ​What kind of testings are possible using selenium WebDriver? We can use It for any
other purpose except testing activity?
Answer​ : Generally we are using selenium WebDriver for functional and
regression testing of software web applications. We can also use It for data entry
kind of work like submitting online forms using different data

42​ : ​Give me any five different xPath syntax to locate bellow given Input element.

<input id="fk-top-search-box" class="search-bar-text fk-font-13 ac_input"


type="text" autofocus="autofocus" value="" name="q" />

//input[@id='fk-top-search-box']
//input[contains(@name,'q')]
//input[starts-with(@class, "search-bar-text")]
//input[@id='fk-top-search-box' or @name='q']
//input[starts-with(@id, 'fk-top-search-box') and
contains(@class,'fk-font-13')]

43​ : ​Can you tell me two drawbacks of xPath locators as compared to cssSelector locator?
Answer​ : Two main disadvantage of xPath locator as compared to cssSelector
locator are as bellow.

It Is slower than cssSelector locator.

xPath which works In one browser may not work In other browser because some browsers (Ex.
IE) reads only Lower-cased tag name and Attribute Name. So If used It In upper case then It will
work In Firefox browser but will not work In IE browser. Every browser reads xPath In different
way. In sort, do not use xPath locators In your test cases If you have to perform cross browser
testing using selenium WebDriver.
44 .​Why xPath locator Is much more popular than all other locator types In WebDriver?
Answer​ : xPath locators are so much popular In selenium webdriver test case
development because

It Is very easy to learn and understand for any new user.


There are many functions to build xPath In different ways like contains, starts-with etc.. So If one Is
not possible you will have always another option to build xPath of any element.
Presently many tools and add-ons are available to find xpath of any element.

45​ : ​Give me WebDriver's API name using which we can perform drag and drop
operation.
Answer​ : That API's name Is ​Advanced User Interactions API​ using which we
can perform drag and drop operation. Same API can help us to perform some
other operations too like moveToElement,
doubleClick, clickAndHold, moveToElement, etc..

46​ : ​Can we perform drag and drop operation In Selenium WebDriver? Tell me a syntax
to drag X element and drop It On Y element.

Answer​ : Yes, We can perform drag and drop operation using selenium

webdriver's ​Advanced User Interactions API.​ Syntax Is like bellow.

new Actions(driver).dragAndDrop(X, Y).build().perform();

47​ : ​Do you have faced any technical challenges with Selenium WebDriver test
automation?
Answer​ : Yes, I have faced bellow given technical challenges during selenium
webdriver test cases development and running.
❖ Sometimes (Not always), Some elements like text box, buttons etc. are
taking more time(more than given Implicit wait time) to appear on page or
to get enabled on page. In such situation, If I have used only Implicit wait
then my test case can run fine on first run but It may fail to find element
on second run. So we need provide special treatment for such elements so
that webdriver script wait for element to be present or get enabled on page
during test execution. We can use Explicit wait to handle this situation.
❖ Handling dynamic changing ID to locate element Is tricky. If element's ID Is
changing every time when you reload the page and you have to use that ID
In XPath to locate element then you have to use functions
like starts-with(@id,'post-body-') or contains(@id,'post-body-') In XPath.

Clicking on sub menus which are getting rendered on mouse hover of main menu
Is some what tricky. You need to use webdriver's Actions class to perform mouse
hover operation.
If you have to execute your test cases In multiple browsers then one test case can
run successfully In Firefox browser but same test case may fail In IE browser due
to the timing related Issues (nosuchelement exception) because test execution In
Firefox browser Is faster than IE browser. You can resolve this Issue by Increasing
Implicit wait time when you run your test In IE browser.

❖ Above Issue can arise due to the unsupported XPath In IE browser. In this case, You need to
you ​OTHER ELEMENT LOCATING METHODS​ (ID, Name, CSSSelector etc.)to locate element.

❖ Handling JQuery elements like moving pricing slider, date picker, drag and
drop etc.. Is tricky. You should have knowledge of webdriver's Advanced
User Interactions API to perform all these actions. You can find few
example links for working with JQuery Items on ​THIS PAGE​.

❖ Working with ​multiple Windows​, Frames, and some tasks like ​Extracting
data from web table​, ​Extracting data from dynamic web
table​, ​Extracting all Links from page​, ​Extracting all text box from
page​ are also tricky and time consuming during test case preparation.

❖ There Is not any direct command to upload or download files from web
page using selenium webdriver. For downloading files usign selenium
webdriver, You need to create and set Firefox browser profile with
webdriver test case.

❖ Webdriver do not have any built In object repository facility. You can do It
using java .properties file to create object repository as described In ​THIS
EXAMPLE​.

❖ Webdriver do not have any built In framework or facility using which we


can achieve bellow given tasks directly : 1. Capturing screenshots, 2.
generating test execution log, 3. reading data from files, 4. Generating test
result reports, Manage test case execution sequence. To achieve all these
tasks, We have to use external services with webdriver like Log4J to
generate log, Apache POI API to read data from excel files, Testng XSLT
reports to generate test result reports. TestNG to manage test case
execution, .properties file to create object repository. All these tasks are
very time consuming. ​ON THIS PAGE​, I have described how to create data
driven framework step by step for selenium webdriver. That framework
contains all above functionality.
❖ You can share other webdriver technical challenges which you have faced
by commenting bellow so that your experience can help to others too.

48​ : ​Can you tell me a syntax to close current webdriver Instance and to close all opened
webdriver Instances?

Answer​ :
Yes, To close current WebDriver Instance, We can use Close() method as bellow.
driver.close();

If there are opened multiple webdriver Instances and wants to close all of them
then we can use webdriver's quit() method as bellow.

driver.quit();

49​ : ​Is It possible to execute javascript directly during test execution? If Yes then tell me
how to generate alert by executing javascript In webdriver script?

Answer​ :
Yes, we can execute javascript during webdriver test execution. To generate alert,
You can write bellow given code In your script.

JavascriptExecutor javascript = (JavascriptExecutor) driver;


javascript.executeScript("alert('Javascript Executed.');");

50​ : ​Give me a syntax to read javascript alert message string, clicking on OK button and
clicking on Cancel button.

Answer​ :
We can read alert message string as bellow.

String alrtmsg = driver.switchTo().alert().getText();

We can click on OK button of alert as bellow.


driver.switchTo().alert().accept();

We can click on Cancel button of alert as bellow.

driver.switchTo().alert().dismiss();

51​ : ​Tell me a scenario which we can not automate In selenium WebDriver.

Answer​ :
1. Bitmap comparison Is not possible using selenium webdriver.
2. Automating captcha Is not possible. (Few peoples says we can
automate captcha but I am telling you If you can automate any captcha then It Is
not a captcha).
3. We can not read bar code using selenium webdriver.

52 :​What Is JUnit?

Answer​ : Java developers use JUnit as​ ​unit testing framework to write repeatable tests for java
programming language. It Is very simple and open source framework and we can use It In selenium
webdriver test scripts creation to manage them In well manner.

53​ : Which Is the latest version of JUnit.

Answer​ : Current latest version of JUnit Is 4.12-beta-2. This can change In future.
To check latest released version of JUnit, You can ​Visit JUnit Official WebSite​.
54​ : Tell me different JUnit annotations and Its usage.

Answer​ : JUnit has bellow given different annotations.

❖ @Test​ : @Test annotation Is useful to Identify method as a Test method.


❖ @Before​ : @Before annotation method will be executed before each and every @Test
method.
❖ @After​ : @After annotation method will be executed after each and every @Test method.
❖ @BeforeClass​ : @BeforeClass annotation method will be executed before all @Test methods
In a class(Means before first @Test method).
❖ @AfterClass​ : @AfterClass annotation method will be executed after all @Test method In a
class(Means after last @Test method).
❖ @Ignore​ : @Ignore annotation Is useful to exclude @Test method from execution. ​VIEW
EXAMPLE
❖ @Test(timeout=1000)​ : You can set @Test method execution timeout. This @Test method
fails Immediately when Its execution time cross 1000 milliseconds.
55​ : ​Write sample JUnit @Test method that passes when expected ArithmeticException
thrown.

Answer​ : Sample JUnit @Test to pass on expected ArithmeticException Is as


bellow.
@Test(expected = ArithmeticException.class)
public void excOnDivision() {
int i = 5/0;
}
56​ : ​Write sample JUnit @Test method that fails when unexpected ArithmeticException
thrown.

Answer​ : Sample JUnit @Test to fail on unexpected ArithmeticException Is as


bellow.
@Test
public void excOnDivision() {
int i = 5/0;
}

57​ : ​What are the advantages of TestNG over JUnit.

Answer​ : Advantages of TestNG over JUnit JUnit are as bellow.

❖ TestNG Annotations are simple and Easy to understand.


❖ Easy to parameterize the test cases In TestNG.
❖ Easy to run test cases In parallel.
❖ Can generate Interactive XSLT test execution reports using TestNG.

58​ : ​Tell me main features of JUnit.

Answer​ : JUnit features are as bellow.


● JUnit Is unit testing framework. So It helps developers to create and run
unit test cases very easily.
● There are many different annotations available In JUnit. Using all those
annotations, we can Identify and configure webdriver test case very easily.
● JUnit supports many different assertions using which we can compare
webdriver test's expected and actual result.
● We can create test suite for multiple test cases to run all of them In one go
using JUnit.
● We can generate webdriver test execution HTML reports using JUnit.
59​ : ​What are different assertions supported by JUnit?

Answer​ : List of JUnit assertions as bellow.


1. assertEquals
2. assertFalse
3. assertTrue
4. assertNull
5. assertNotNull
6. assertSame
7. assertNotSame
8. assertArrayEquals

60 : ​How to create and run JUnit test suite for selenium WebDriver?​
Answer​ : For creating JUnit test suite, we have to create test cases class files and
one separate test suite file. Then we can write syntax like bellow In test suite file
to run test suite.

@RunWith(Suite.class)
@SuiteClasses({ ​junittest1.class​, ​junittest2.class​ })
public class junittestsuite {
}

61​ ​: For what purpose, assertTrue and assertFalse assertions are used?

Answer​ : In selenium webdriver test, We need to assert Boolean conditions true


and false. We can assert both these conditions using assertTrue and assertFalse
JUnit assertions.
62​ : ​Can you give me example of JUnit assertEquals assertion?

Answer​ : Example of JUnit assertEquals assertion Is as bellow. It assert that values of actTotal
and expTotal are equal or not.

public void sumExample() {


int val1 = 10;
int val2 = 20;
int expTotal = 35;
int actTotal = 0;
actTotal = val1 + val2;
​assertEquals​(actTotal, expTotal);
}

63​ : ​What Is TestNG?

Answer​ : TestNG Is Open Source(Freeware) framework which Is Inspired from


NUnit and JUnit with Introducing few new features and functionality compared to
NUnit and JUnit to make It easy to use and more powerful.

We can use TestNg with selenium webdriver to configure and run test cases very
easily, easy to understand, read and manage test cases, and to generate HTML or
XSLT test reports.

64​ : ​Can you describe major features of TestNG?

Answer​ : TestNG has many major features like support of @DataProvider


annotation to perform data driven testing, can set test case execution
dependency, test case grouping, generate HTML and XSLT test execution report
etc.. ​VIEW MORE FEATURES​ with detailed description.

65​ : ​Describe the similarities and difference between JUnit and TestNG unit testing
frameworks.

Answer​ : You can find all the similarities and difference between JUnit and
TestNG framework on ​THIS PAGE​.

66​ : ​How to Install TestNG In Eclipse? How do you verify that TestNg Is Installed
properly In Eclipse?
Answer​ : To Install TestNG In Eclipse, We have to follow steps as described
on ​THIS PAGE​.

67​ : ​What are different annotations supported by TestNG ?

Answer​ : TestNG supports many different annotations to configure Selenium


WebDriver test. You can see mostly used annotations list with detailed
description and practical example link on ​THIS PAGE​.

68​ : ​What Is the usage of testng.xml file?

Answer​ : In selenium WebDriver, We are using testng.xml file to configure our


whole test suite In single file. Few of the tasks which we can specify In testng.xml
file are as bellow.

● We can define test suite using set of test cases to run them from single
place.
● Can Include or exclude test methods from test execution.
● Can specify a group to Include or exclude.
● Can pass parameter to use In test case.
● Can specify group dependencies.
● Can configure parallel test execution.
● Can define listeners.

69​ : ​How to pass parameter with testng.xml file to use It In test case?

Answer​ : We can define parameter In testng.xml file using syntax like bellow.

<parameter name="browser" value="FFX" />

Here, name attribute defines parameter name and value defines value of that
parameter. Then we can use that parameter In selenium webdriver test case
using bellow given syntax.

@Parameters ({"browser"})
70​ : ​I have a test case with two @Test methods. I wants to exclude one @Test method from
execution. Can I do It? How?

Answer​ : Yes you need to specify @Test method exclusion In testng.xml file as
bellow.

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >


<suite name="Test Exclusion Suite">
<test name="Exclusion Test" >
<classes>
<class name="Your Test Class Name">
<methods>
<​exclude name="Your Test Method Name To Exclude"​/>
</methods>
</class>
</classes>
</test>
</suite>

You need to provide @Test method name In exclude tag to exclude It from
execution.

71​ : ​Tell me syntax to skip @Test method from execution.

Answer​ : You can use bellow given syntax Inside @Test method to skip It from
test execution.

throw new SkipException("Test Check_Checkbox Is Skipped");

It will throw skip exception and @Test method will be sipped Immediately from
execution. You can ​VIEW FULL EXAMPLE​ on how to skip @Test method from
execution.

72​ : ​Arrange bellow give testng.xml tags from parent to child.

<test>
<suite>
<class>
</methods>
</classes>

Answer​ : Parent to child arrangement for above testng tags Is as bellow.

<suite>
<test>
</classes>
<class>
</methods>

73​ : ​How to set priority of @Test method? What Is Its usage?

Answer​ : In your test case, you can set priority for TestNG @Test annotated
methods as bellow.
@Test(priority=0)

Using priority, We can control @Test method execution manner as per our
requirement. That
means @Test method with priority = 0 will be executed 1st and @Test method
with priority = 1 will be executed 2nd and so on. ​VIEW PRACTICAL EXAMPLE​ to
know how to use It.

74​ : ​Tell me any 5 assertions of TestNG which we can use In selenium webdriver.

Answer​ : There are many different assertions available In TestNG but generally I
am using bellow given assertions In my test cases.

❖ assertEquals
❖ assertNotEquals
❖ assertTrue
❖ assertFalse
❖ assertNull
❖ assertNotNull

75​ : ​Can you tell me usage of TestNG Soft Assertion?​

Answer​ : Using TestNG soft assertion, We can continue our test execution even if
assertion fails. That means on failure of soft assertion, remaining part of @Test
method will be executed and assertion failure will be reportedat the end of @Test
method. ​VIEW PRACTICAL EXAMPLE​.

76​ : ​How to write regular expression In testng.xml file to search @Test methods containing
"product" keyword.
Answer​ : Regular expression to find @Test methods containing keyword
"product" Is as bellow.
<methods>
​<include name=".*product.*"/>
</methods>

77​ : ​Which time unit we provide In time test? minutes? seconds? milliseconds? or hours?
Give Example.

Answer​ : Time unit we provide on @Test method level or test suite level Is In
milliseconds.You can ​VIEW FULL EXAMPLE​ to know how to set time out.

78​ : ​What Is the syntax to get value from text box and store It In variable.

Answer​ : Most of the time, String In text box will be stored as value. So we need
to access value attribute(getAttribute) of that text box as shown In bellow
example.

String Result =
driver.findElement(By.xpath("//input[@id='Resultbox']")).getAttribute(“value”)

79​ : ​What Is the difference between findelement and findElements ?

Answer​ : findElement Is useful to locate and return single element from page
while findElements Is useful to locate and return multiple elements from web
page.

80​ : ​Tell me looks like XPath of sibling Input element which Is after Div in the DOM.

Answer​ : XPath for above scenario will be something like bellow.


//div/following-sibling::input

81​ : ​Tell me looks like CSSSelector path of sibling Input element which Is after Div in the
DOM.

Answer​ : CSSSelecor path will looks like bellow.


css=div + input
82​ : ​What Is Parallelism In TestNG?

Answer​ : In general software term, Parallelism means executing two part of


program simultaneously or executing program simultaneously or we can
say multithreaded or parallel mode. TestNG has same feature using which we can
start multiple threads simultaneously In parallel mode and test methods will be
executed In them. ​VIEW PARALLELISM EXAMPLE​.

83​ : ​What are the benefits of parallelism over normal execution?

Answer​ : Using parallelism facility of TestNG In selenium webdriver,


● Your test execution time will be reduced as multiple tests will be executed
simultaneously.
● Using parallelism, We can verify multithreaded code In application.

84​ : ​I wants to run test cases/classes In parallel. Using which attribute and value I can do
It?

Answer​ : You have to use ​parallel = classes​ attribute In testng.xml to run


tests parallel. ​VIEW EXAMPLE​.

85​ : ​What Is dependency test In TestNG?


Answer​ : Dependency Is very good feature of testng using which we can set test
method as dependent test method of any other single or multiple or group of test
methods. That means depends-on method will be executed first and then
dependent test method will be executed. If depends-on test method will fail then
execution of dependent test method will be skipped automatically. TestNG
dependency feature will works only If depends-on test method Is part of same
class or part of Inherited base class.

86​ : ​What Is the syntax to set test method dependency on multiple test methods​.

Answer​ : We can set test method's dependency on multiple test methods as


bellow.

@Test(​dependsOnMethods={"Login","checkMail"}​)
public void LogOut() {
System.out.println("LogOut Test code.");
}
87​ : ​What Is the syntax to set test method disabled.

Answer​ : We can use attribute ​enabled = false​ with @Test annotation to set test method disabled.
Syntax Is as bellow.

@Test(​enabled = false​)
public void LogOut() {
System.out.println("LogOut Test code.");
}

88​ : ​In XPath, I wants to do partial match on attribute value from beginning. Tell me two
functions using which I can do It.

Answer​ : We can use bellow given two functions with XPath to find element using
attribute value from beginning.
1. contains()
2. starts-with()

89​ : ​I have used findElements In my test case. It Is returning NoSuchElementException


when not element found. Correct me If I am wrong.

Answer​ : It Is Incorrect. findElements will never return NoSuchElementException.


It will return just an empty list.

90​ : ​My Firefox browser Is not Installed at usual place. How can I tell FirefoxDriver to use
It?

Answer​ : If Firefox browsers Is Installed at some different place than the usual
place then you needs to provide the actual path of Firefox.exe file as bellow.

System.setProperty("webdriver.firefox.bin","C:\\Program Files\\Mozilla
Firefox\\Firefox.exe");
driver =new FirefoxDriver();

91​ : ​What versions of Internet Explorer are supported by selenium WebDriver?

Answer​ : Till date, Selenium WebDriver supports IE 6, 7, 8, 9, 10 and 11 with


appropriate combinations of Windows 7, Vista or XP.

92​ : ​Tell me the class name using which we can generate Action chain.
Answer​ : The WebDriver class name Using which we can generate Action chain Is
"​Actions​". ​VIEW USAGE OF ACTIONS CLASS​ with practical example on how to
generate series of actions to drag and drop element.

93​ : ​Do you know method name using which we can builds up the actions chain?​

Answer​ : Method name of Actions class to build up actions chain Is


"build()". ​THIS EXAMPLE​ will show you how to build drag and drop element by
x,y pixel actions using build() method.

94​ : ​When we can use Actions class In Selenium WebDriver test case?
Answer​ : Few of the examples are bellow where can use actions class to perform
operations In web application.
❖ Drag and drop element
❖ Drag and drop by x,y pixel offset
❖ Selecting JQuery selectable Items
❖ Moving JQuery slider
❖ Re-sizing JQuery re-sizable element
❖ Selecting date from JQuery date picker

95​ : ​Can we capture screenshot In Selenium WebDriver? How?


Answer​ : We can use selenium webdriver TakesScreenshot method to capture
screenshot. Java File class will be used to store screenshot In your system's local
drive

96​ : ​Selenium WebDriver has any built In method using which we can read data from
excel file?
Answer​ : No, Selenium webdriver do not have any built In functionality using
which we can read data from excel file.

97​ : ​Tell me any 5 webdriver common exceptions which you faced during test case
execution.
Answer​ : WebDriver's different 5 exceptions are as bellow.
1. TimeoutException​ - This exception will be thrown when command
execution does not complete In given time.
2. NoSuchElementException​ - WebDriver will throw this exception
when element could not be found on page.
3. NoAlertPresentException​ - This exception will be generated when
webdriver ties to switch to alert popup but there Is not any alert present
on page.
4. ElementNotSelectableException​ - It will be thrown when
webdriver Is trying to select unselectable element.
5. ElementNotVisibleException​ - Thrown when webdriver Is not able
to Interact with element which Is available In DOM but It Is hidden.
6. StaleElementReferenceException

98​ : ​Tell me different ways to type text In text box In selenium test.

Answer​ : We can type text In text box of web page using bellow given ways In
selenium test.

1.Using .SendKeys() method


driver.findElement(By.xpath("//input[@id='fname']")).sendKeys("Using
sendKeys");

2. Using JavascriptExecutor

((JavascriptExecutor)driver).executeScript("document.getElementById('fname').va
lue='Using JavascriptExecutor'");

3. Using Java Robot class ​VIEW EXAMPLE

driver.findElement(By.xpath("//input[@id='fname']")).click();
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_U);
robot.keyPress(KeyEvent.VK_S);
robot.keyPress(KeyEvent.VK_I);
robot.keyPress(KeyEvent.VK_N);
robot.keyPress(KeyEvent.VK_G);
robot.keyPress(KeyEvent.VK_SPACE);
robot.keyPress(KeyEvent.VK_R);
robot.keyPress(KeyEvent.VK_O);
robot.keyPress(KeyEvent.VK_B);
robot.keyPress(KeyEvent.VK_O);
robot.keyPress(KeyEvent.VK_T);

99​ : ​Tell me different ways to verify element present or not on page.​

Answer​ : We can check If element Is present or not using bellow given 2 simple ways.
1. Using .size() method

Boolean elePresent = driver.findElements( By.id("ID of element") ).size() != 0;


If above syntax return "false" means element Is not present on page and "true" means element Is
present on page.

2. Using .isEmpty() method

Boolean elePresent = driver.findElements(By.id("ID of element")).isEmpty();


If this returns "true" means element Is not present on page and "false" means element Is present on
page.

100​ : ​Why we need to customize Firefox browser profile In webdriver test?

Answer​ : Webdriver launch fresh browser Instance when we run tests In Firefox
browser using selenium webdriver. Fresh browser Instance do not have any
Installed add-ons, saved passwords, bookmarks and any other user preferences.
So we need to create custom profile of Firefox browser to get any of this thing In
Webdriver launched browser.

101​ : ​How to customize Firefox browser profile for webdriver test?

Answer​ : You can do It In two different ways.


1. You can create your desired firefox browser profile before running
test and then you can use It In your selenium webdriver test. ​VIEW
EXAMPLE​.
2. You can customize your firefox browser profile run time before
launching webdriver's Firefox browser Instance. ​VIEW EXAMPLE​.
102​ : ​What is Difference between getAttribute() and getText()?

Answer​ :
● getAttribute() method Is useful to read element's attribute value like id,
name, type etc. ​VIEW EXAMPLE​.
● getText() method Is useful to read text from element or alert. ​VIEW
EXAMPLE​.

103​: ​What is the difference between WebDriver and Remote WebDriver?

Answer​ : Simple answer for this questions Is as bellow.


● WebDriver​ : Webdriver Is an Interface or we can say tool using which we
can create automated test cases for web application and then run on different
browsers like IE, Google chrome, Firefox etc.. We can create test cases In
different languages. ​VIEW MORE DETAIL​.
● Remote WebDriver​ : Remote WebDriver Is useful to run test cases In
same machine or remote machines using selenium Grid.

104​ : ​I have total 200 test cases. I wants to execute only 20 test cases out of them. Can I do
It In selenium WebDriver? How?

Answer​ : Yes. If you are using TestNG with selenium webdriver then you can do
Is using grouping approach as described In ​THIS PAGE​. Create separate group
for those 20 test cases and configure testng.xml file accordingly to run only those
20 test cases.

Also If you are using data driven framework then you can configure It In excel
file. You can configure such data driven framework at your own by following
steps given on ​THIS PAGE​.

105​: ​Can you tell me three different ways to refresh page. Do not use .refresh() method.

Answer​ : We can refresh browser In many different ways. Three of them are as
bellow.

driver.get(driver.getCurrentUrl());

driver.navigate().to(driver.getCurrentUrl());
driver.findElement(By.xpath("//h1[@class='title']")).sendKeys(Keys.F5);

106​ : ​I wants to set size and position of my browser window. Do you know how to do it in
selenium webdriver?

Answer​ : We can use ​setSize​ function to set size of window and setPosition
function to set position of browser window.

107​ : ​Is there any way to get size and position of browser window in selenium webdriver?
Answer​ : Yes.. We can get it using webdriver functions getSize and getPosition.
108​ : ​I wants to scroll my page by 300 pixel. Tell me how can i do it?
Answer​ : We can use ​javascript executor with window.scrollBy(x,y)​ to scroll
page in x or y directions.

109: ​How to handle internationalization through web driver?


Answer : ​FirefoxProfile profile = new FirefoxProfile();
profile.set Preference("intl.accept_languages","jp");
Web driver driver = new FirefoxDriver(profile);
driver.get(google.com) will open google in Japanese Lang

110 : ​How can we get the font size, font color, ​ ​font type used for a particular text on a web
page using Selenium web driver?
driver.findelement(By.Xpath("Xpath ").getcssvalue("font-size);
driver.findelement(By.Xpath("Xpath ").getcssvalue("font-colour);
driver.findelement(By.Xpath("Xpath ").getcssvalue("font-type);
driver.findelement(By.Xpath("Xpath ").getcssvalue("background-colour);

111. ​How to prepare Customized html Report using​ ​TestNG in hybrid framework.
Below are the 3 ways:
• Junit: with the help of ANT.
• TestNG: using inbuilt default.html to get the HTML report. Also XST reports from ANT,
Selenium, TestNG combination.
• Using our own customized reports using XSL jar for converting XML content to HTML.
112 : ​How to handle Ajax popup window?
By using getWindowHandles() and obj.switchTo.window(windowid) we can handle popups
using explicit wait and driver.swtchT0.window("name") commands for your
requirements.

113: ​How to handle autocomplete box in web driver?


driver.findElement(By.id("your searchBox")).sendKeys("your partial keyword");
Thread.sleep(3000);
List <WebElement> listItems = driver.findElements(By.xpath("your list item locator"));
listItems.get(0).click();
driver.findElement(By.id("your searchButton")).click()

114: ​How to get the name of browser using Web Driver?


public class JsExecute
{
WebDriver driver;
JavascriptExecutor js;
@Before
public void setUp() throws Exception
{
driver=new FirefoxDriver();
driver.get("http://www.google.com");
}
@Test
public void test()
{
JavascriptExecutor js = (JavascriptExecutor) driver;
System.out.println(js.executeScript("return navigator.appCodeName"));
}}
OR
String s = (String) ((JavascriptExecutor) driver).executeScript("return
navigator.userAgent;");
System.out.println("Browser name : " + s);

115: ​Is there a way to click hidden LINK in web driver?


String Block1 = driver.findElement(By.id("element ID"));
JavascriptExecutor js1=(JavascriptExecutor)driver;
js1.executeScript("$("+Block1+").css({'display':'block'});");

116: ​“Suppose developer changed the existing image to new image with same xpath. Is test case
pass or fail?"
Answer : Pass

117 : ​How to work with dynamic web table?


Answer : ​You can get the total number of <tr> tags within a <td> tag by giving the xpath of the
<td> element by using this function -
List<WebElement> ele = driver.findElements(By.xpath("Xpath of the table"));
Now you can use a for each loop to loop through each of the <tr> tags in the above list
and then read each value by using getText() method.

118: ​In frame if no frame Id as well as no frame name then which attribute
I should consider throughout our script.
You can go like this.....driver.findElements(By.xpath("//iframe"))...
Then it will return List of frames then switch to each and every frame and search for the locator
which you want then break the loop

119: ​What is object repository?


It is collection of object names their properties, attributes and their values .It
maye be excel, XML,property file or text file

120: ​Differences between jxl and ApachePOI.


● jxl does not support XLSX files
● jxl exerts less load on memory as compared to ApachePOI
● jxl doesn't support rich text formatting while ApachePOI does.
● jxl has not been maintained properly while ApachePOI is more up to date.
● Sample code on Apache POI is easily available as compare to jxl.

121 : ​How to ZIP files in Selenium with an Example?


// Sample Function to make zip of reports
public static void zip(String filepath){
try
{
File inputFolder=new File('Mention file path her");
File outputFolder=new File("Reports.zip");
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new
FileOutputStream(outputFolder)));
BufferedInputStream in = null;
byte[] data = new byte[1000];
String files[] = inputFolder.list();
for (int j=0; j<files.length; i++)
{
in = new BufferedInputStream(new FileInputStream
(inputFolder.getPath() + "/" + files[j]), 1000);
out.putNextEntry(new ZipEntry(files[j]));
int totalcount;
while((totalcount= in.read(data,0,1000)) != -1)
{
out.write(data, 0, totalcount);
}
out.closeEntry();
}
out.flush();
out.close();
}
catch(Exception e)
{
e.printStackTrace();
return "Fail - " + e.getMessage();
}
}

122: ​What is the difference between single and double slash in Xpath?
/
1.It starts selection from the document node
2. It Allows you to create 'absolute' path expressions
3. e.g “/html/body/p” matches all the paragraph elements
//
1. It starts selection matching anywhere in the document
2. It Allows you to create 'relative' path expressions
3. e.g“//p” matches all the paragraph elements

What is WebDriverBackedSelenium ?
Ans- WebDriverBackedSelenium is a kind of class name where we can create an object for it as
below:
1 Selenium wbdriver= new WebDriverBackedSelenium(WebDriver object name, "URL path of website")
The main use of this is when we want to write code using both WebDriver and Selenium RC , we
must use above created object to use selenium commands.
How to check if an element is visible on the web page ?
Ans- use isDisplayed() method. The return type of the method is boolean. So if it return true then
element is visible else not visible.
driver.findElement(By.xpath(​"xpath of elemnt"​)).isDisplayed();

How to check if a text is highlighted on the page ?


Ans- To identify weather color for a field is different or not-
String color = driver.findElement(By.xpath("//a[text()='Shop']")).getCssValue("color");
2
3 String backcolor = driver.findElement(By.xpath("//a[text()='Shop']")).getCssValue("background-color");
4
5 System.out.println(color);
6
7 System.out.println(backcolor);

Which is the super interface of webdriver ?


Ans- SearchContext.
How do you take screen shot without using EventFiringWebDriver ?
Ans-
File srcFile = ((TakeScreenshot)driver).getScreenshotAs(OutputType.FILE); //now we can do anything with this
1
screenshot
2
3
like copy this to any folder-
4
5
FileUtils.copyFile(srcFile,new File(“folder name where u want to copy/file_name.png”));
How to press Shift+Tab ?
Ans-
String press = Keys.chord(Keys.SHIFT,Keys.ENTER);

webelement.sendKeys(press);

How do you accommodate project specific methods in your framework ?


Ans- 1st go through all the manual test cases and identify the steps which are repeating. Note
down such steps and make them as methods and write into ProjectSpecificLibrary.
What are different components of your framework ?
Ans- Library- Assertion, ConfigLibrary, GenericLibrary, ProjectSpecificLibrary, Modules.
Drivers folder, Jars folder, excel file.
What are the browsers supported by Selenium IDE ?
Ans- Mozilla FireFox only. Its an Firefox add on.
Ques 22) What are the limitations of Selenium IDE ?
Ans-
a) It does not supports looping or conditional statements. Tester has to use native languages to
write logic in the test case.
b) It does not supports test reporting, you have to use selenium RC with some external reporting
plugin like TestNG or JUint to get test execution report.
c) Error handling is also not supported depending on the native language for this.
d) Only support in Mozilla FireFox only. Its an Firefox add on.
How to check all checkboxes in a page ?
Ans-
List&lt;webElement&gt; chkBox = driver.findElements(By.xpath(“//htmltag[@attbute='checkbox']”));
2
3
for(int i=0; i&lt;=chkBox.size(); i++){
4
5
chkBox.get(i).click();
6
7
}

Count the number of links in a page.


Ans- use the locator By.tagName and find the elements for the tag //a then use loop to count the
number of elements found.
1 Syntax- int count = 0;
2
3 List&lt;webElement&gt; link = driver.findElements(By.tagName(“a”));
4
5 System.out.println(link.size()); // this will print the number of links in a page.

Write a java program for swapping of two numbers ?


Ans-
1 public class Swapping{
2
3 public static void main(String[] args){
4
5 Scanner in = new Scanner(System.in);
6
7 System.out.println(“enter the 1st num”);
8
9 int a = in.nextInt();
10
11 System.out.println(“enter the 2nd num”);
12
13 int b = in.nextInt();
14
15 System.out.println(“before swapping a=”+a+” and b= ”+b);
16
17 int x = a;
18
19 a = b;
20
21 b = x;
22
23 System.out.println(“After swapping a=”+a+” and b= ”+b);
24
25 }
26
27 }

Write a java program for factorial of a given number.


Ans-
public class Factorial{

public static void main(String args[]){

Scanner in = new Scanner(System.in);

System.out.println(​“​enter the num for which u want the factorial​”​);

int num = in.nextInt();

for(int i=num-1; i&gt;0; i-- ){

num = num*i;

System.out.println(num);

write a code to make use of assert if my username is incorrect.


Ans-
try{
Assert.assertEquals(expUserName, actUserName);

}catch(Exception e){

Syste.out.println(​“​name is invalid​”​);

What is testing strategy ?


Ans- A Test Strategy document is a high level document and normally developed by project
manager. This document defines “Software Testing Approach” to achieve testing objectives. The
Test Strategy is normally derived from the Business Requirement Specification document.

How to configure selenium webdriver in eclipse?

In eclipse, I created java projects and added JUnit or TestNG classes. In the project reference, I added JUnit or
TestNG jar file. In the test class, I used webdriver in setup, test and teardown methods. Sometimes, I used webdriver
in beforeclass, beforemethod, aftermethod, afterclass sections.

What are the prerequisites to run selenium webdriver?

Depending on the programming language, reference files should be added to the test solutions in C# or test projects
in Java. For example, in C#, I added webdriver dlls and in Java, I added Selenium-client-driver.jar file. And also, we
should have programming IDE like visual studio or eclipse to run webdriver.

6. What are the advantages of selenium webdriver?

Selenium WebDriver is very flexible to use with Java, .Net, Python, Ruby or html languages. QA engineers who have
good coding skills can use it very effectively.

7. What are the disadvantages of selenium webdriver over selenium 1.0?

Since selenium web driver requires coding skills, QA engineers should have some knowledge of program
development in Java, .Net, or other languages.

How to convert selenium 1.0 tests to webdriver tests?

We can use WebDriverBackedSelenium to run Selenium 1.0 tests in webdriver.

WebDriver​ driver ​=​ ​new​ ​FirefoxDriver​();

Selenium​ selenium ​=​ ​new​ ​WebDriverBackedSelenium​(​driver​,​ ​"http://www.yoursite.com"​);

What is webdriver backed selenium?

WebDriver backed Selenium is API that enables running Selenium 1.0 tests in web driver.

if a Selenium function requires a pattern argument, what five prefixes might that argument have?

* which translates to “match anything,” i.e., nothing, a single character, or many characters.

[ ] (character class) which translates to “match any single character found inside the square brackets.” A dash
(hyphen) can be used as a shorthand to specify a range of characters (which are contiguous in the ASCII character
set). A few examples will make the functionality of a character class clear:
[aeiou] matches any lowercase vowel

[0-9] matches any digit

[a-zA-Z0-9] matches any alphanumeric character

What is the regular expression sequence that loosely translates to "anything or nothing?"

* which translates to “match anything,” i.e., nothing, a single character, or many characters.

What is the globbing sequence that loosely translates to "anything or nothing?

glob: label

32. What does a character class for all alphabetic characters and digits look like in regular expressions?

[a-zA-Z0-9] matches any alphanumeric character

33. What does a character class for all alphabetic characters and digits look like in globbing?

regexp: *[a-zA-Z0-9]

What are desiredcapabilities?


Desired Capabilities help to set properties for the Web Driver. A typical use case would be
to
set the path for the Firefox Driver if your local installation doesn't correspond to the default
settings.
https://code.google.com/p/selenium/wiki/DesiredCapabilities

4. Difference between Selenium RC and Selenium Web driver.


Difference between Selenium RC and Selenium Web driver.

Selenium RC Selenium Web driver


Selenium RC’s architecture is way Web Driver’s architecture is simpler
more complicated. than Selenium RC’s.

Selenium RC is slower since it uses a Web Driver is faster than Selenium RC


JavaScript program called Selenium since it speaks directly to the browser
Core.This Selenium Core is the one that uses the browser’s own engine to
directly controls the browser, not you. control it.
Selenium Core, just like other Web Driver interacts with page
JavaScript codes, can access disabled elements in a more realistic way.
elements.
Selenium RC’s API is more matured but Web Driver’s API is simpler than
contains redundancies and often Selenium RC’s. It does not contain
confusing commands. redundant and confusing commands.
Selenium RC cannot support the Web Driver can support the headless
headless HtmlUnit browser. It needs a HtmlUnit browser.
real, visible browser to operate on.
Selenium RC Has Built-In Test Result Web Driver has no built-in command
Generator. Selenium RC automatically that automatically generates a Test
generates an HTML file of test results. Results File.
Selenium RC needs the help of the RC web Driver directly talks to the
Server in order to do so. browser
Selenium RC can support new It cannot readily support new browsers
browsers

5. Difference between Web driver listener and TestNG Listener.


TestNG and Web driver Listener have different interfaces to implement and call them. They
both
modify respective behaviour. You can use Listeners in Annotation. Below 2 URL gives the
detailed list of listener and their interfaces.

What is the difference between thread.Sleep() and selenium. Set Speed ("2000")?
If the application is taking time to load the page then we use selenium.waitforpageload(" ").
This command is doesn’t wait upto the given time whenever the page load is completed.
If the application is taking time to refresh the page, then we use Thread. Sleep ( ).it is a
standard wait it simply wait to the given time.
selenium.setSpeed
1. Takes a single argument in string format
Ex: selenium.setSpeed("2000") - will wait for 2 seconds
2. Runs each command in after setSpeed delay by the number of milliseconds mentioned in
set Speed.
thread.sleep
1. Takes a single argument in integer format
ex: thread. Sleep(2000) - will wait for 2 seconds
3. Waits for only once at the command given at sleep.

11. In what situation selenium finding element get fails?


-->Element loading issue
-->Dynamic id of web element

How to overcome same origin policy through web driver?


Proxy server.
DesiredCapabilities capability=new DesiredCapabilities.firefox();
capability.setCapability(CapabilityType.PROXY,"your desire proxy")
WebDriver driver=new FirefoxDriver(capability);

Difference between flex and flash application​.


In flash there is no code just based on creativity(design) we will complete the
work(time consuming process) whereas flex contain some small functions
which is integrated with mxml,PHP..(no tool is there to develop
flex we want to use the properties of css and style sheet)

How to get text from captcha image??


driver.findElement(By.xpath(".//*[@id='SkipCaptcha']")).click();
String attr = ie.findElement(By.xpath(".//*[@id='SkipCaptcha']")).getAttribute("value");
System.out.println("The value of the attribute 'Name' is " + attr);

Is there a way to click hidden LINK in web driver?


String Block1 = driver.findElement(By.id("element ID"));
JavascriptExecutor js1=(JavascriptExecutor)driver;
js1.executeScript("$("+Block1+").css({'display':'block'});");

1) Explain how you can insert a break point in Selenium IDE ?

In Selenium IDE to insert a break point

● Select “Toggle break point” by right click on the command in Selenium IDE
● Press “B” on the keyboard and select the command in Selenium IDE
● Multiple break points can be set in Selenium IDE

2) Explain in Selenium IDE how can you debug the tests?


● Insert a break point from the location from where you want to execute test step by
step
● Run the test case
● At the given break point execution will be paused
● To continue with the next statement click on the blue button
● Click on the “Run” button to continue executing all the commands at a time

3) What is Selenese and what are the types of Selenese ?

Selenese is a selenium set of command which are used for running the test

There are three types of Selenese


● Actions: It is used for performing the operations and interactions with the target
elements
● Assertions: It is used as a check points
● Accessors: It is used for storing the values in a variable

4) Explain what are the limitations of Selenium IDE?

The limitations of Selenium IDE

● Exceptional handling is not present


● Selenium IDE uses only HTML languages
● External databases reading is not possible with IDE
● Reading from the external files like .txt, .xls is not possible
● Conditional or branching statements execution like if,else, select statements is not
possible
● 5) What are the two modes of views in Selenium IDE ?
● Either Selenium IDE can be opened as a pop up window or in side bar

6) In selenium IDE what are the element locators that can be used to locate elements on
web page?

In selenium there are mainly 4 locators that are used

● X-path locators
● Css locators
● Html id
● Html name

7) In Selenium IDE how you can generate random numbers and dates for test data ?

In Selenium IDE you can generate random numbers by using Java Script
type

css=input#s

javascript{Math.random()}

And for date

type

css=input#s

javascript{new Date()}

8) How you can convert any Selenium IDE tests from Selenese to another language?

You can use the format option of Selenium IDE to convert tests into another programming
language

9) Using Selenium IDE is it possible to get data from a particular html table cell ?

You can use the “storeTable” command

Example store text from cell 0,2 from an html table

storeTable

Css=#table 0.2

textFromCell

10) Explain what can cause a Selenium IDE test to fail?


● When a locator has changed and Selenium IDE cannot locate the element
● When element Selenium IDE waiting to access did not appear on the web page and
the operation timed out
● When element Selenium IDE was trying to access was not created
11) Explain how you can debug the tests in Selenium IDE ?
● Insert a break point from the location where you want to execute step by step
● Run the test case
● At the given break point execution will be paused
● To continues with the next step click on the Blue button
● To run commands at a time click on run button
12) From Selenium IDE how you can execute a single line?
From Selenium IDE single line command can be executed in two ways

● Select “Execute this command” by right clicking on the command in Selenium IDE
● Press “X” key on the keyboard after selecting the command in Selenium IDE
13) In which format does source view shows your script in Selenium IDE ?

In Selenium IDE source view shows your script in XML format

14) Explain how you can insert a start point in Selenium IDE?

In two ways selenium IDE can be set

● Press “S” key on the keyboard and select the command in Selenium IDE
● In Seleniun IDE right click on the command and the select “Set / Clear Start Point”
● 15) What if you have written your own element locator and how would you test it?
● To test the locator one can use “Find Button” of Selenium IDE, as you click on it, you
would see on screen an element being highlighted provided your element locator is
right or or else an error message will be displayed.
● 16) What is regular expressions? How you can use regular expressions in
Selenium ?
● A regular expression is a special text string used for describing a search pattern. In
Selenium IDE regular expression can be used with the keyword- ​regexp: ​as a prefix
to the value and patterns needs to be included for the expected values.
● 17) What are core extension ?
● If you want to “extend” the defualt functionality provided by Selenium Function
Library , you can create a Core Extension. They are also called “User Extension”. You
can even download ready-made Core Extension created by other Selenium
enthusiats.
● 18) How will you handle working with multiple windows in Selenium ?
● We can use the command ​selectWindow t​ o switch between windows. This command
uses the title of Windows to identify which window to switch to.
● 19) How will you verify the specific position of an web element
● You can use verifyElementPositionLeft & verifyElementPositionTop. It does a pixel
comparison of the position of the element from the Left and Top of page respectively
● 20) How can you retrive the message in an alert box ?
● You can use the storeAlert command which will fetch the message of the alert pop up
and store it in a variable.

What is Selenium and what is composed of?

Selenium is a suite of tools for automated web testing. It is composed of

● Selenium IDE (Integrated Development Environment) : I​ t is a tool for recording


and playing back. It is a firefox plugin
● WebDriver and RC:​ It provide the APIs for a variety of languages like Java, .NET,
PHP, etc. With most of the browsers Webdriver and RC works.
● Grid: ​With the help of Grid you can distribute tests on multiple machines so that test
can be run parallel which helps in cutting down the time required for running in browser test
suites

4) List out the test types that are supported by Selenium?

For web based application testing selenium can be used

The test types can be supported are

a) Functional

b) Regression

For post release validation with continuous integration automation tool could be used

a) Jenkins

b) Hudson

c) Quick Build

d) CruiseCont

5) Explain what is assertion in Selenium and what are the types of assertion?

Assertion is used as a verification point. It verifies that the state of the application conforms
to what is expected. The types of assertion are “assert” , “verify” and “waifFor”.

10) What is the difference between verify and assert commands?


Assert:​ Assert allows to check whether an element is on the page or not. The test will stop
on the step failed, if the asserted element is not available. In other words, the test will
terminated at the point where check fails.
Verify:​ Verify command will check whether the element is on the page, if it is not then the
test will carry on executing. In verification, all the commands are going to run guaranteed
even if any of test fails.
16) What is the difference between setSpeed() and sleep() methods?

Both will delay the speed of execution.

Thread.sleep () : It will stop the current (java) thread for the specified period of time. Its done
only once

● It takes a single argument in integer format

Ex: thread.sleep(2000)- It will wait for 2 seconds

● It waits only once at the command given at sleep

SetSpeed () : For specific amount of time it will stop the execution for every selenium
command.

Explain what is Datadriven framework and Keyword driven?


Datadriven framework:​ In this framework, the test data is separated and kept outside the
Test Scripts, while test case logic resides in Test Scripts. Test data is read from the external
files ( Excel Files) and are loaded into the variables inside the Test Script. Variables are used
for both for input values and for verification values.
Keyworddriven framework:​ The keyword driven frameworks requires the development of
data tables and keywords, independent of the test automation. In a keyword driven test, the
functionality of the application under test is documented in a table as well as step by step
instructions for each test.

1) What is Selenium IDE ?


A) Selenium IDE (Integrated Development Environment) is an ideal tool used to develop selenium
test scripts... It is the only flavor of selenium which allows us to record user actions on browser
window... Here, the scripts are recorded in 'Selenese'(a set of selenium commands like Click,
assertTextPresent, storeText, etc,.).. It is not only a time-saver but also an excellent way of
learning Selenium scripts syntax... It is a Firefox add-0n...

2) How to install Selenium IDE ?


A) click here for detailed steps
I use seleniumhq.org site to download any software regarding selenium.. Here, if we click on
the version number of selenium ide it starts downloading the add-ons, just we have to click on
'install now' button and restart the firefox browser.. With-in 5 minutes we can install selenium
ide...

3) How do you open/start selenium-ide after installation ?


A) First launch/open firefox browser and then click on 'Tools' tab in the menu bar.. You can see an
option called 'selenium ide' , click on it, a small window will be opened where you can start recording
scripts...
4) Features of selenium IDE
​click here for detailed features of selenium ide
❖ Its main feature is record and playback..
❖ Debugging features by setting breakpoints, startpoints, pause..
❖ Identifies element using id, name, xpath etc..
❖ Auto complete for all common selenium commands..
❖ It has an option of asserting title of every page automatically..
❖ Support for selenium user-extensions.js file..
❖ Option to run single test or multiple tests(suite).
❖ It has a feature of exporting testcase/suite into different formats like C#, Java, Ruby,
Python.

5) Advantages and disadvantages of selenium IDE..


Advantages :
❖ Freeware..
❖ Easy to install..
❖ It is the only flavor of selenium that allows us to record user actions on browser
window..
❖ Scripts recorded in IDE can be coverted into other languages like Java, C#, Python and
Ruby..
❖ It is not only a time saver but also an excellent way of learning scripts syntax..
❖ We can insert comments in the middle of the script for better understanding and
debugging..
❖ Context menu, which allows us to pick from a list of assertions and verifications for the
selected location..
❖ Disadvantages​:
❖ Main disadvantage of IDE is that it runs only in firefox browser..
❖ Selenium IDE can execute scripts created in selenese only.
❖ Cannot upload files..
❖ It does not directly support loops and conditions..
❖ Reading from external files like .txt, .xls is not possible..

6) What are the selenium locators and what is the tool you use to identify element ?
A) Selenium locators are the way of finding HTML element on the page to perform Selenium
actions... We use​firebug​(for firefox) to identify elements as it is more popular and powerful web
development tool.. It inspects HTML and modify style and layout in real-time.. We can edit,
debug and monitor CSS, HTML and Javascript live in any web page.. ​((click here to download
firebug))
-->​For Internet Explorer we can choose ​debugbar​.. It views HTML DOM tree, we can view and
edit tab attributes..
((click here to download debugbar))

7) How do you locate elements in IDE ?


A) I will focus on the unique attribute values like id, name or other structural information that is
stable enough to withstand frequent changes to the web application.. I strongly recommend CSS
selectors as locating strategy.. They are considerably faster than xpath and can find the most
complicated objects in any HTML document.

8) What is selenese ?
A) Selenium set of commands that run our test is called Selenese.. A sequence of these
commands is a test script.. There are three types of selenese..
1. Actions : They perform some operations like clicking a link or typing text in text
box or selecting an option from drop-down box etc..
2. Assertions : They verify that the state of application conforms to what is
expected.. Ex: 'verify that this checkbox is checked', 'make sure that the page title is X'..
3. Accessors : Checks the state of application and store the results in a variable.. Ex:
storeText, storeTitle, etc..

9) How do you add check points or verification points ?


A) They are called as Assertions in selenium.. 'assert', 'verify' and 'waitFor' are the commands
used to add check points..
Ex: assertText, verifyElementPresent, waitForTextPresent, etc..

10) Name some commands that you use frequently in IDE ?


A) Open, click, type, select, assertText, assertTitle, assertTextPresent, verifyText,
verifyTextPresent, veriftTitle, waitForText, waitForTextPresent, waitForTitle, store,
storeText, storeTitle, check, uncheck, pause, mouseover, etc..

11) What is the difference between assert and verify ?


A) When an 'assert' fails, the test is aborted where as when 'verify' fails, the test will continue
execution logging the failure..
'assert' is used when the expected value is mandatory to continue with next set of steps..
However 'verify' is used when the expected value is optional to continue with the next set of
steps..

12) Difference between waitFor and pause commands ?


A) 'waitFor' command waits for some condition to become true..
For example, 'waitForPageToLoad(20000)'-- it will wait upto 20 thousand milliseconds to load
required page.. If the page is loaded before 20,000ms then it jumps to next step to execute.. If
the page is not loaded before 20,000ms then it stops the execution due to time-out error..
--> pause ​command stops the execution of the test until the specified time..
Ex: pause(10000)-- It stops the execution of test for 1o thousand milliseconds.. After
completing 10,000ms it jumps to next command to execute.. I prefer 'waitFor' command than
'pause'.
13) How do you export tests from Selenium IDE to RC ?
A) First i will open the test in IDE, which should be exported to RC.. There after i'l select 'File' from
the menu bar.. when we mouseover on 'Export Test Case As' in the file menu, we could see different
languages like C#, Java, Python and Ruby.. Select the language you want to export your test and
provide the name to save it.

8. How to insert a start point in Selenium IDE?


Start point Selenium IDE can be set in two ways

1. Right click on the command in Selenium IDE and select “Set / Clear Start Point”
2. Select the command in Selenium IDE and press “S” key on the keyboard
3. You can have only one start point
4. If you have already set one start point and you selected other command as start point. Then the
first start point will be removed and the new start point will be set

9. How to insert a comment in Selenium IDE?


Comments in Selenium IDE can be set in two ways

1. Right click on the command in Selenium IDE and select “Inert New Comment”
2. If you want to comment an existing line. You need to follow the below mentioned steps.
a. Select the source tab in IDE
b. Select the line which you want to comment
c. Assume that if you want to comment a open command you need to write like below mentioned code
<tr>

<!–

<td>open&l/td>
<td>/node/304/edit&l/td>
<td></td>
–>

</tr>

10. How to insert a break point in Selenium IDE?


Break point can be set in two ways in Selenium IDE

1. Right click on the command in Selenium IDE and select “Toggle Break Point”
2. Select the command in Selenium IDE and press “B” key on the keyboard
3. If you want to clear the break point once again Spress “B” key on the keyboard
4. You can set multiple break points in Selenium IDE

12. How to export the tests from Selenium IDE to Selenium RC in different languages?
From selenium IDE the test cases can be exported into the languages

1. .Net
2. Java
3. Perl
4. Python
5. PHP
6. Ruby
The below mentioned steps can explain how to export the test cases
1. Open the test case from Selenium IDE
2. Select File -> Export Test Case As

Which is the command used for displaying the values of a variable into the output console
or log?
The command used for displaying the values of a variable into the output console or log – echo

If you want to display a constant string. The below mentioned command can be used
echo <constant string>
ex: echo “The sample message”
If you want to display the value of a variable it can be written like below
echo ${<variable name>>
ex: echo ${var1}

Note: Here var1 is the variable

15. Which are the browsers supported by Selenium RC?


Supported browsers for Selenium RC include:

1. *firefox
2. *mock
3. *firefoxproxy
4. *pifirefox
5. *chrome
6. *iexploreproxy
7. *iexplore
8. *firefox3
9. *safariproxy
10. *googlechrome
11. *konqueror
12. *firefox2
13. *safari
14. *piiexplore
15. *firefoxchrome
16. *opera
17. *iehta
18. *custom

Does Selenium support mobile internet testing?


Selenium supports Opera. And opera is used in most of the Smart phones. So whichever Smart phone
supports opera, selenium can be used to test. So, one can use Selenium RC to run the tests on
mobiles.

What are the types of text patterns available in Selenium?


There are three types of patterns available in Selenium
1. globbing
2. regular expressions
3. exact

How to use regular expressions in Selenium?


Regular expressions in Selenium IDE can be used with the keyword – ​regexp:​ as a prefix to the value
and patterns needs to be included for the expected values.
For example if you want to use the regular expression for a command
Command: verifyText
Target: //font/font/b/font[1]
Value: Flight Confirmation # 2011-05-02451
in the above example Flight Confirmation is continuously changing each time you run the test case. So
this can be written with a regular expression as mentioned below

Command: verifyText
Target: //font/font/b/font[1]
Value: regexp:Flight Confirmation # [0-9]{4}-[0-9]{2}-[0-9]{5,10}

What are the regular expression patterns available in Selenium?


Selenium regular expression patterns offer the same wide array of special characters that exist in
JavaScript. Below are a subset of those special characters

PATTER MATCH
N
. any single character
[] character class: any single character that appears inside the brackets
* quantifier: 0 or more of the preceding character (or group)
+ quantifier: 1 or more of the preceding character (or group)
? quantifier: 0 or 1 of the preceding character (or group)
{1,5} quantifier: 1 through 5 of the preceding character (or group)
| alternation: the character/group on the left or the character/group on the
right
() grouping: often used with alternation and/or quantifier

How to capture bitmaps in Selenium?


Bitmaps are captured using the Selenium set of commands. There are two modes of capturing the
bitmaps

1) Capture the bitmap for the entire page – it captures the browser main page area of AUT
2) Capture the bitmap for the screen shots – it captures the entire screen shot like the print scree that
you give from your keyboard
Selenium doesn’t support bitmap capturing for an element on AUT.

What is the difference between captureEntirePageScreenshot and CaptureScreenShot?


captureEntirePageScreenshot
1. This captures the AUT web page only
2. This supports only mozilla firefox
3. Accepts two arguments. one is the file name to be saved and other argument is back ground color
CaptureScreenShot

1. This captures the System screen shot


2. This supports all the browsers when you run from Selenium RC
3. Accepts one argument. That is the file name to be saved.

How do you set user extensions in Selenium IDE?


1. Open user-extensions.js with an editor (Notepad, etc.); it’s found in the selenium\core\scripts
folder. If it doesn’t exist, just create it.
2. If you need to, commit the user-extensions.js file (like if you use subversion).
3. Open Selenium IDE and choose the Options menu and then Options… from that menu.
4. Make sure the path to your user-extensions.js file is entered in the Selenium Core extensions field
(like \selenium\core\scripts\user-extensions.js)
5. Press OK button on options
6. Restart the IDE to reflect your extensions.
Note:​ After reopen, Selenium IDE may show compilations errors if the user-extensions.js file has any
syntax errors.

What is difference between JDK, JRE and JVM?

JVM

JVM is an acronym for Java Virtual Machine, it is an abstract machine which provides the
runtime environment in which java bytecode can be executed. It is a specification.

JVMs are available for many hardware and software platforms (so JVM is platform dependent).

JRE

JRE stands for Java Runtime Environment. It is the implementation of JVM.

JDK

JDK is an acronym for Java Development Kit. It physically exists. It contains JRE +
development tools.

2) How many types of memory areas are allocated by JVM?


Many types:
1. Class(Method) Area

2. Heap

3. Stack

4. Program Counter Register

5. Native Method Stack

3) What is JIT compiler?


Just-In-Time(JIT) compiler:​It is used to improve the performance. JIT compiles parts of the
byte code that have similar functionality at the same time, and hence reduces the amount of time
needed for compilation.Here the term “compiler” refers to a translator from the instruction set of
a Java virtual machine (JVM) to the instruction set of a specific CPU.

4) What is platform?
A platform is basically the hardware or software environment in which a program runs. There are
two types of platforms software-based and hardware-based. Java provides software-based
platform.

5) What is the main difference between Java platform and other platforms?

The Java platform differs from most other platforms in the sense that it's a software-based
platform that runs on top of other hardware-based platforms.It has two components:

1. Runtime Environment

2. API(Application Programming Interface)

6) What gives Java its 'write once and run anywhere' nature?
The bytecode. Java is compiled to be a byte code which is the intermediate language between
source code and machine code. This byte code is not platform specific and hence can be fed to
any platform.
7) What is classloader?
The classloader is a subsystem of JVM that is used to load classes and interfaces.There are many
types of classloaders e.g. Bootstrap classloader, Extension classloader, System classloader,
Plugin classloader etc.
8) Is Empty .java file name a valid source file name?
Yes, save your java file by .java only, compile it by ​javac .java​ and run by ​java
yourclassname​ Let's take a simple example:
1. /save by .java only​
2. class​ A{
3. public​ ​static​ ​void​ main(String args[]){
4. System.out.println(​"Hello java"​);
5. }
6. }
7. //compile by javac .java​
8. //run by java A​

compile it by ​javac .java

9. run it by ​java A
9) Is delete,next,main,exit or null keyword in java?
No.
0) If I don't provide any arguments on the command line, then the String array of Main method
will be empty or null?
It is empty. But not null.

11) What if I write static public void instead of public static void?
Program compiles and runs properly.

12) What is the default value of the local variables?


The local variables are not initialized to any default value, neither primitives nor object
references.
There is given more than 50 OOPs (Object-Oriented Programming and System) interview
questions. But they have been categorized in many sections such as constructor interview
questions, static interview questions, Inheritance Interview questions, Abstraction interview
question, Polymorphism interview questions etc. for better understanding.

13) What is difference between object oriented programming language and object based
programming language?
Object based programming languages follow all the features of OOPs except Inheritance.
Examples of object based programming languages are JavaScript, VBScript etc.
14) What will be the initial value of an object reference which is defined as an instance variable?
The object references are all initialized to null in Java.
15) What is constructor?
● Constructor is just like a method that is used to initialize the state of an object. It is
invoked at the time of object creation

16) What is the purpose of default constructor?


● The default constructor provides the default values to the objects. The java compiler
creates a default constructor only if there is no constructor in the class.

17) Does constructor return any value?


​Ans: ​yes, that is current instance (You cannot use return type yet it returns a value).
18)Is constructor inherited?
No, constructor is not inherited.
19) Can you make a constructor final?
No, constructor can't be final.
20) What is static variable?
● static variable is used to refer the common property of all objects (that is not unique for
each object) e.g. company name of employees,college name of students etc.

● static variable gets memory only once in class area at the time of class loading.

21) What is static method?


● A static method belongs to the class rather than object of a class.

● A static method can be invoked without the need for creating an instance of a class.

● static method can access static data member and can change the value of it.

22) Why main method is static?

because object is not required to call static method if It were non-static method,jvm creats object
first then call main() method that will lead to the problem of extra memory allocation.
23) What is static block?
● Is used to initialize the static data member.

● It is excuted before main method at the time of classloading.

24) Can we execute a program without main() method?


Ans) Yes, one of the way is static block.
25) What if the static modifier is removed from the signature of the main method?
Program compiles. But at runtime throws an error "NoSuchMethodError".
26) What is difference between static (class) method and instance method?
static or class method instance method

1)A method i.e. declared as static is known as static method. A method i.e. not declared
as instance method.

2)Object is not required to call static method. Object is required to call in

3)Non-static (instance) members cannot be accessed in static context (static static and non-static variab
method, static block and static nested class) directly. accessed in instance metho
4)For example: public static int cube(int n){ return n*n*n;} For example: public void m

27) What is this in java?


It is a keyword that that refers to the current object.
28)What is Inheritance?
Inheritance is a mechanism in which one object acquires all the properties and behaviour of
another object of another class. It represents IS-A relationship. It is used for Code Resusability
and Method Overriding.
29) Which class is the superclass for every class.
Object class.
30) Why multiple inheritance is not supported in java?
● To reduce the complexity and simplify the language, multiple inheritance is not
supported in java in case of class.

31) What is composition?


Holding the reference of the other class within some other class is known as composition.
32) What is difference between aggregation and composition?
Aggregation represents weak relationship whereas composition represents strong relationship.
For example: bike has an indicator (aggregation) but bike has an engine (compostion).
33) Why Java does not support pointers?
Pointer is a variable that refers to the memory address. They are not used in java because they
are unsafe(unsecured) and complex to understand.
34) What is super in java?
It is a keyword that refers to the immediate parent class object.

35) Can you use this() and super() both in a constructor?


No. Because super() or this() must be the first statement.
36)What is object cloning?
The object cloning is used to create the exact copy of an object.
37) What is method overloading?
If a class have multiple methods by same name but different parameters, it is known as Method
Overloading. It increases the readability of the program.
38) Why method overloading is not possible by changing the return type in java?
Becauseof ambiguity.
39) Can we overload main() method?
Yes, You can have many main() methods in a class by overloading the main method.
40) What is method overriding:
If a subclass provides a specific implementation of a method that is already provided by its
parent class, it is known as Method Overriding. It is used for runtime polymorphism and to
provide the specific implementation of the method.
41) Can we override static method?
No, you can't override the static method because they are the part of class not object.
42) Why we cannot override static method?
It is because the static method is the part of class and it is bound with class whereas instance
method is bound with object and static gets memory in class area and instance gets memory in
heap.

43) Can we override the overloaded method?


Yes.
44) Difference between method Overloading and Overriding.
Method Overloading Method Overriding

1) Method overloading increases the Method overriding provides the specific implementation of
readability of the program. already provided by its super class.

2) method overlaoding is occurs within the Method overriding occurs in two classes that have IS-A rela
class.

3) In this case, parameter must be different. In this case, parameter must be same.

45) Can you have virtual functions in Java?


Yes, all functions in Java are virtual by default.
46) What is covariant return type?
Now, since java5, it is possible to override any method by changing the return type if the return
type of the subclass overriding method is subclass type. It is known as covariant return type.
47) What is final variable?
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
48) What is final method?
Final methods can't be overriden.

49) What is final class?


Final class can't be inherited.
50) What is blank final variable?
A final variable, not initalized at the time of declaration, is known as blank final variable.
51) Can we intialize blank final variable?
Yes, only in constructor if it is non-static. If it is static blank final variable, it can be initialized
only in the static block.​.
52) Can you declare the main method as final?
Yes, such as, public static final void main(String[] args){}.
53) What is Runtime Polymorphism?
Runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden
method is resolved at runtime rather than at compile-time.
In this process, an overridden method is called through the reference variable of a super class.
The determination of the method to be called is based on the object being referred to by the
reference variable.
54) Can you achieve Runtime Polymorphism by data members?
No.
55) What is the difference between static binding and dynamic binding?
In case of static binding type of object is determined at compile time whereas in dynamic binding
type of object is determined at runtime.

56) What is abstraction?


Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
Abstraction lets you focus on what the object does instead of how it does it.
57) What is the difference between abstraction and encapsulation?
Abstraction hides the implementation details whereas encapsulation wraps code and data into a
single unit.
58) What is abstract class?
A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.
59) Can there be any abstract method without abstract class?
No, if there is any abstract method in a class, that class must be abstract.
60) Can you use abstract and final both with a method?
No, because abstract method needs to be overridden whereas you can't override final method.
61) Is it possible to instantiate the abstract class?
No, abstract class can never be instantiated.
62) What is interface?
Interface is a blueprint of a class that have static constants and abstract methods.It can be used to
achieve fully abstraction and multiple inheritance.
63) Can you declare an interface method static?
No, because methods of an interface is abstract by default, and static and abstract keywords can't
be used together.
64) Can an Interface be final?
No, because its implementation is provided by another class.
65) What is marker interface?
An interface that have no data member and method is known as a marker interface.For example
Serializable, Cloneable etc.
66) What is difference between abstract class and interface?
Abstract class Interface

1)An abstract class can have method body (non-abstract methods). Interface have only abstract m

2)An abstract class can have instance variables. An interface cannot have insta

3)An abstract class can have constructor. Interface cannot have construc

4)An abstract class can have static methods. Interface cannot have static me

5)You can extends one abstract class. You can implement multiple in

67) Can we define private and protected modifiers for variables in interfaces?
No, they are implicitly public.
68) When can an object reference be cast to an interface reference?
An object reference can be cast to an interface reference when the object implements the
referenced interface.
69) What is package?
A package is a group of similar type of classes interfaces and sub-packages. It provides access
protection and removes naming collision.
70) Do I need to import java.lang package any time? Why ?
No. It is by default loaded internally by the JVM.
71) Can I import same package/class twice? Will the JVM load the package twice at runtime?
One can import the same package or same class multiple times. Neither compiler nor JVM
complains about it.But the JVM will internally load the class only once no matter how many
times you import the same class.
72) What is static import ?
By static import, we can access the static members of a class directly, there is no to qualify it
with the class name.
73) What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors.It is mainly used to handle checked
exceptions.
74) What is difference between Checked Exception and Unchecked Exception?
1)Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions e.g.IOException,SQLException etc. Checked exceptions are checked at
compile-time.
2)Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException,NullPointerException etc. Unchecked exceptions are not checked at
compile-time.
75) What is the base class for Error and Exception?
Throwable.

76) Is it necessary that each try block must be followed by a catch block?
It is not necessary that each try block must be followed by a catch block. It should be followed
by either a catch block OR a finally block. And whatever exceptions are likely to be thrown
should be declared in the throws clause of the method.
77) What is finally block?
● finally block is a block that is always executed.​more details...

78) Can finally block be used without catch?


● Yes, by try block. finally must be followed by either try or catch.​more details...

79) Is there any case when finally will not be executed?


finally block will not be executed if program exits(either by calling System.exit() or by causing a
fatal error that causes the process to abort).​more details...
80) What is difference between throw and throws?
throw keyword throws keyword

1)throw is used to explicitly throw an throws is used to declare an exception.


exception.

2)checked exceptions can not be propagated checked exception can be propagated with throws.
with throw only.

3)throw is followed by an instance. throws is followed by class.

4)throw is used within the method. throws is used with the method signature.

5)You cannot throw multiple exception You can declare multiple exception e.g. public void metho
IOException,SQLException.

81) Can an exception be rethrown?


Yes.

82) Can subclass overriding method declare an exception if parent class method doesn't throw an
exception ?
Yes but only unchecked exception not checked.
83) What is exception propagation ?
Forwarding the exception object to the invoking method is known as exception propagation.
There is given a list of string handling interview questions with short and pointed answers. If you
know any string handling interview question, kindly post it in the comment section.
84) What is the meaning of immutable in terms of String?
The simple meaning of immutable is unmodifiable or unchangeable. Once string object has been
created, its value can't be changed.
85) Why string objects are immutable in java?
Because java uses the concept of string literal. Suppose there are 5 reference variables,all referes
to one object "sachin".If one reference variable changes the value of the object, it will be affected
to all the reference variables. That is why string objects are immutable in java.

86) How many ways we can create the string object?


There are two ways to create the string object, by string literal and by new keyword.
87) How many objects will be created in the following code?
1. String s1=​"Welcome"​;
2. String s2=​"Welcome"​;
3. String s3=​"Welcome"​;
Only one object.
88) Why java uses the concept of string literal?
To make Java more memory efficient (because no new objects are created if it exists already in
string constant pool).
89)How many objects will be created in the following code?
1. String s = ​new​ String(​"Welcome"​);
Two objects, one in string constant pool and other in non-pool(heap).
90) What is the basic difference between string and stringbuffer object?
String is an immutable object. StringBuffer is a mutable object.
91) What is the difference between StringBuffer and StringBuilder ?
StringBuffer is synchronized whereas StringBuilder is not synchronized.
92) How can we create immutable class in java ?
We can create immutable class as the String class by defining final class and
93) What is the purpose of toString() method in java ?
The toString() method returns the string representation of any object. If you print any object, java
compiler internally invokes the toString() method on the object. So overriding the toString()
method, returns the desired output, it can be the state of an object etc. depends on your
implementation.
94)What is nested class?
A class which is declared inside another class is known as nested class. There are 4 types of
nested class member inner class, local inner class, annonymous inner class and static nested
class.
95) Is there any difference between nested classes and inner classes?
Yes, inner classes are non-static nested classes i.e. inner classes are the part of nested classes.
96) Can we access the non-final local variable, inside the local inner class?
No, local variable must be constant if you want to access it in local inner class.
97) What is nested interface ?
Any interface i.e. declared inside the interface or class, is known as nested interface. It is static
by default.
98) Can a class have an interface?
Yes, it is known as nested interface.
99) Can an Interface have a class?
Yes, they are static implicitely.
117) What is Garbage Collection?
Garbage collection is a process of reclaiming the runtime unused objects.It is performed for
memory management.
118) What is gc()?
gc() is a daemon thread.gc() method is defined in System class that is used to send request to
JVM to perform garbage collection.
119) What is the purpose of finalize() method?
finalize() method is invoked just before the object is garbage collected.It is used to perform
cleanup processing.
120) Can an unrefrenced objects be refrenced again?
Yes.
121)What kind of thread is the Garbage collector thread?
Daemon thread.
122)What is difference between final, finally and finalize?
final:​ final is a keyword, final can be variable, method or class.You, can't change the value of
final variable, can't override final method, can't inherit final class.

finally:​ finally block is used in exception handling. finally block is always executed.

finalize():​finalize() method is used in garbage collection.finalize() method is invoked just


before the object is garbage collected.The finalize() method can be used to perform any
cleanup processing.
123)What is the purpose of the Runtime class?
The purpose of the Runtime class is to provide access to the Java runtime system.
124)How will you invoke any external process in Java?
By Runtime.getRuntime().exec(?) method.

125)What is the difference between the Reader/Writer class hierarchy and the
InputStream/OutputStream class hierarchy?
The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class
hierarchy is byte-oriented.
126)What an I/O filter?
An I/O filter is an object that reads from one stream and writes to another, usually altering the
data in some way as it is passed from one stream to another.
127) What is serialization?
Serialization is a process of writing the state of an object into a byte stream.It is mainly used to
travel object's state on the network.
128) What is Deserialization?
Deserialization is the process of reconstructing the object from the serialized state.It is the
reverse operation of serialization.
129) What is transient keyword?
If you define any data member as transient,it will not be serialized.
130)What is Externalizable?
Externalizable interface is used to write the state of an object into a byte stream in compressed
format.It is not a marker interface.
131)What is the difference between Serializalble and Externalizable interface?
Serializable is a marker interface but Externalizable is not a marker interface.When you use
Serializable interface, your class is serialized automatically by default. But you can override
writeObject() and readObject() two methods to control more complex object serailization
process. When you use Externalizable interface, you have a complete control over your class's
serialization process.

133) What is reflection?


Reflection is the process of examining or modifying the runtime behaviour of a class at
runtime.It is used in:
● IDE (Integreted Development Environment) e.g. Eclipse, MyEclipse, NetBeans.
● Debugger

● Test Tools etc.

134) Can you access the private method from outside the class?
Yes, by changing the runtime behaviour of a class if the class is not secured.
148)What are wrapper classes?
Wrapper classes are classes that allow primitive types to be accessed as objects.
149)What is a native method?
A native method is a method that is implemented in a language other than Java.
150)What is the purpose of the System class?
The purpose of the System class is to provide access to system resources.
151)What comes to mind when someone mentions a shallow copy in Java?
Object cloning.
152)What is singleton class?
Singleton class means that any given time only one instance of the class is present, in one
153)Which containers use a border layout as their default layout?
The Window, Frame and Dialog classes use a border layout as their default layout.
154)Which containers use a FlowLayout as their default layout?
The Panel and Applet classes use the FlowLayout as their default layout.
155)What are peerless components?
The peerless components are called light weight components.
156)is the difference between a Scrollbar and a ScrollPane?
A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane
handles its own events and performs its own scrolling.
157)What is a lightweight component?
Lightweight components are the one which doesn?t go with the native call to obtain the graphical
units. They share their parent component graphical units to render them. For example, Swing
components.
158)What is a heavyweight component?
For every paint call, there will be a native call to get the graphical units.For Example, AWT.
159)What is an applet?
An applet is a small java program that runs inside the browser and generates dynamic contents.
160)Can you write a Java class that could be used both as an applet as well as an application?
Yes. Add a main() method to the applet.
161)What is Locale?
A Locale object represents a specific geographical, political, or cultural region.
162)How will you load a specific locale?
By ResourceBundle.getBundle(?) method.

163)What is a JavaBean?
are reusable software components written in the Java programming language, designed to be
manipulated visually by a software development environment, like JBuilder or VisualAge for
Java.

164)Can RMI and Corba based applications interact?


Yes they can. RMI is available with IIOP as the transport protocol instead of JRMP.
Java Multithreading Interview Questions
Multithreading and Synchronization is considered as the typical chapter in java programming. In
game development company, mulithreading related interview questions are asked mostly. A list
of frequently asked java multithreading interview questions are given below.

1) What is multithreading?
Multithreading is a process of executing multiple threads simultaneously. Its main advantage is:
● Threads share the same address space.

● Thread is lightweight.

● Cost of communication between process is low.

2) What is thread?
A thread is a lightweight subprocess.It is a separate path of execution.It is called separate path of
execution because each thread runs in a separate stack frame.
3)What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead
states or a higher priority task comes into existence. Under time slicing, a task executes for a
predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines
which task should execute next, based on priority and other factors.
4) What does join() method?
The join() method waits for a thread to die. In other words, it causes the currently running
threads to stop executing until the thread it joins with completes its task.
5) What is difference between wait() and sleep() method?
wait() sleep()

1) The wait() method is defined in Object class. The sleep() method is defined in Thread c

2) wait() method releases the lock. The sleep() method doesn't releases the lo

6) Is it possible to start a thread twice?


No, there is no possibility to start a thread twice. If we does, it throws an exception.
7) Can we call the run() method instead of start()?
yes, but it will not work as a thread rather it will work as a normal object so there will not be
context-switching between the threads.
8) What about the daemon threads?
The daemon threads are basically the low priority threads that provides the background support
to the user threads. It provides services to the user threads.
9)Can we make the user thread as daemon thread if thread is started?
No, if you do so, it will throw IllegalThreadStateException

10)What is shutdown hook?


The shutdown hook is basically a thread i.e. invoked implicitely before JVM shuts down. So we
can use it perform clean up resource.
11)When should we interrupt a thread?
We should interrupt a thread if we want to break out the sleep or wait state of a thread.
12) What is synchronization?
Synchronization is the capabilility of control the access of multiple threads to any shared
resource.It is used:

1. To prevent thread interference.

2. To prevent consistency problem.

13) What is the purpose of Synchronized block?


● Synchronized block is used to lock an object for any shared resource.
● Scope of synchronized block is smaller than the method.

14)Can Java object be locked down for exclusive use by a given thread?
Yes. You can lock an object by putting it in a "synchronized" block. The locked object is
inaccessible to any thread other than the one that explicitly claimed it.
15) What is static synchronization?
If you make any static method as synchronized, the lock will be on the class not on object.

16)What is the difference between notify() and notifyAll()?


The notify() is used to unblock one waiting thread whereas notifyAll() method is used to unblock
all the threads in waiting state.
17)What is deadlock?
Deadlock is a situation when two threads are waiting on each other to release a resource. Each
thread waiting for a resource which is held by the other waiting thread.

Java Collections Interview Questions


In java, collection interview questions are mostly asked by the interviewers. Here is the list of
mostly asked collections interview questions with answers.
1) What is the difference between ArrayList and Vector?
No. ArrayList Vector

1) ArrayList is not synchronized. Vector is synchronized.

2) ArrayList is not a legacy class. Vector is a legacy class.

3) ArrayList increases its size by 50% of the array size. Vector increases its size by doubling t

2) What is the difference between ArrayList and LinkedList?


No. ArrayList LinkedList

1 ArrayList uses a dynamic array. LinkedList uses doub


)

2 ArrayList is not efficient for manipulation because a lot of shifting is LinkedList is efficien
) required. manipulation.
3 ArrayList is better to store and fetch data. LinkedList is better t
)

3) What is the difference between Iterator and ListIterator?


Iterator traverses the elements in forward direction only whereas ListIterator traverses the
elements in forward and backward direction.
No. Iterator ListIterator

1 Iterator traverses the elements in forward ListIterator traverses the elements in backward a
) direction only. directions both.

2 Iterator can be used in List, Set and Queue. ListIterator can be used in List only.
)

4) What is the difference between Iterator and Enumeration?


No. Iterator Enumeration

1) Iterator can traverse legacy and non-legacy elements. Enumeration can traverse only legac

2) Iterator is fail-fast. Enumeration is not fail-fast.

3) Iterator is slower than Enumeration. Enumeration is faster than Iterator.

5) What is the difference between List and Set?


List can contain duplicate elements whereas Set contains only unique elements.
6) What is the difference between HashSet and TreeSet?
HashSet maintains ​no order​ whereas TreeSet maintains ​ascending order​.
7) What is the difference between Set and Map?
Set contains values only whereas Map contains key and values both.

8) What is the difference between HashSet and HashMap?


HashSet contains only values whereas HashMap contains entry(key,value). HashSet can be
iterated but HashMap need to convert into Set to be iterated.
9) What is the difference between HashMap and TreeMap?
HashMap maintains ​no order​ but TreeMap maintains ​ascending order​.
10) What is the difference between HashMap and Hashtable?
No. HashMap Hashtable

1) HashMap is not synchronized. Hashtable is synchronized.

2) HashMap can contain one null key and Hashtable cannot contain any
multiple null values.
null key or null value.

11) What is the difference between Collection and Collections?


Collection is an interface whereas Collections is a class. Collection interface provides normal
functionality of data structure to List, Set and Queue. But, Collections class is to sort and
synchronize collection elements.

12) What is the difference between Comparable and Comparator?


No. Comparable Comparator

1) Comparable provides only one sort of sequence. Comparator provides multiple sort of sequences

2) It provides one method named compareTo(). It provides one method named compare().

3) It is found in java.lang package. it is found in java.util package.

4) If we implement Comparable interface, actual Actual class is not modified.


class is modified.

13) What is the advantage of Properties file?


If you change the value in properties file, you don't need to recompile the java class. So, it makes
the application easy to manage.
14) What does the hashCode() method?
The hashCode() method returns a hash code value (an integer number).
The hashCode() method returns the same integer number, if two keys (by calling equals()
method) are same.
But, it is possible that two hash code numbers can have different or same keys.

15) Why we override equals() method?


The equals method is used to check whether two objects are same or not. It needs to be
overridden if we want to check the objects based on property.
For example, Employee is a class that has 3 data members: id, name and salary. But, we want to
check the equality of employee object on the basis of salary. Then, we need to override the
equals() method.

16) How to synchronize List, Set and Map elements?


Yes, Collections class provides methods to make List, Set or Map elements as synchronized:
public static List synchronizedList(List l){}

public static Set synchronizedSet(Set s){}

public static SortedSet synchronizedSortedSet(SortedSet s){}

public static Map synchronizedMap(Map m){}

public static SortedMap synchronizedSortedMap(SortedMap m){}

17) What is the advantage of generic collection?


If we use generic class, we don't need typecasting. It is typesafe and checked at compile time.
18) What is hash-collision in Hashtable and how it is handled in Java?
Two different keys with the same hash value is known as hash-collision. Two different entries
will be kept in a single hash bucket to avoid the collision.

19) What is the Dictionary class?


The Dictionary class provides the capability to store key-value pairs.
20) What is the default size of load factor in hashing based collection?
The default size of load factor is ​0.75​. The default capacity is computed as initial capacity * load
factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.
JDBC Interview Questions
A list of frequently asked jdbc interview questions with answers are given below.

1) What is JDBC?
JDBC is a Java API that is used to connect and execute query to the database. JDBC API uses
jdbc drivers to connects to the database.

2) What is JDBC Driver?


JDBC Driver is a software component that enables java application to interact with the
database.There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver

2. Native-API driver (partially java driver)

3. Network Protocol driver (fully java driver)

4. Thin driver (fully java driver)

3) What are the steps to connect to the database in java?


● Registering the driver class

● Creating connection

● Creating statement

● Executing queries

● Closing connection

4) What are the JDBC API components?


The java.sql package contains interfaces and classes for JDBC API.
Interfaces:
● Connection

● Statement
● PreparedStatement

● ResultSet

● ResultSetMetaData

● DatabaseMetaData

● CallableStatement etc.

Classes:
● DriverManager

● Blob

● Clob

● Types

● SQLException etc.

5) What are the JDBC statements?


There are 3 JDBC statements.
1. Statement

2. PreparedStatement

3. CallableStatement

6) What is the difference between Statement and PreparedStatement interface?


In case of Statement, query is complied each time whereas in case of PreparedStatement, query
is complied only once. So performance of PreparedStatement is better than Statement.
7) How can we execute stored procedures and functions?
By using ​Callable statement​ interface, we can execute procedures and functions.

8) What is the role of JDBC DriverManager class?


The ​DriverManager class​ manages the registered drivers. It can be used to register and
unregister drivers. It provides factory method that returns the instance of Connection.
9) What does the JDBC Connection interface?
The ​Connection interface​ maintains a session with the database. It can be used for transaction
management. It provides factory methods that returns the instance of Statement,
PreparedStatement, CallableStatement and DatabaseMetaData.

10) What does the JDBC ResultSet interface?


The ResultSet object represents a row of a table. It can be used to change the cursor pointer and
get the information from the database.

11) What does the JDBC ResultSetMetaData interface?


The ResultSetMetaData interface returns the information of table such as total number of
columns, column name, column type etc.
12) What does the JDBC DatabaseMetaData interface?
The DatabaseMetaData interface returns the information of the database such as username,
driver name, driver version, number of tables, number of views etc.

13) Which interface is responsible for transaction management in JDBC?


The ​Connection interface​ provides methods for transaction management such as commit(),
rollback() etc.
14) What is batch processing and how to perform batch processing in JDBC?
By using batch processing technique in JDBC, we can execute multiple queries. It makes the
performance fast.
15) How can we store and retrieve images from the database?
By using PreparedStatement interface, we can store and retrieve images.

You might also like