Beruflich Dokumente
Kultur Dokumente
Java C++
• Java is platform independent • C++ is platform dependent.
• There are no pointers in java • There are pointers in C++.
• There is no operator overloading in • C++ has operator overloading.
java • There is no garbage collection
• There is garbage collection in java • Does’nt support multithreading
• Supports multithreading • There are templates in C++.
• There are no templates in java • There are global variables in
• There are no global variables in java c++
10) What is JIT compiler ?
JIT compiler stands for Just in time compiler. JIT compiler compiles byte code in to executable
code . JIT a part of JVM .JIT cannot convert complete java program in to executable code it
converts as and when it is needed during execution.
public classFirstClass {
public static voidmain(String[] args) {
FirstClass f=new FirstClass();
System.out.println(“My First class”);
To instantiate the FirstClass we use this statement
FirstClass f=new FirstClass();
f is used to refer FirstClass object.
15)What is method in java ?
It contains the executable body that can be applied to the specific object of the class.
Method includes method name, parameters or arguments and return type and a body of
executable code.
Syntax : type methodName(Argument List){}
ex : public float add(int a, int b, int c)
methods can have multiple arguments. Separate with commas when we have multiple
arguments.
Signature : public classname()
Signature : public classname(parameters list)
{
Overriding Overloading
• In overriding method names must • In overloading method names
be same must be same
• Argument List must be same • Argument list must be different
• Return type can be same or we atleast order of arguments.
can return covariant type. • Return type can be different in
• We cant increase the level of overloading.
checked exceptions. No restrictions • In overloading different
for unchecked exceptions exceptions can be thrown.
• A method can only be overridden • A method can be overloaded in
in subclass same class or subclass
• Private,static and final variables • Private , static and final
cannot be overridden. variables can be overloaded.
• In overriding which method is • In overloading which method to
called is decided at runtime based call is decided at compile time
on the type of object referenced at based on reference type.
run time • Overloading is also known as
• Overriding is also known as Compile time polymorphism,
Runtime polymorphism, dynamic static polymorphism or early
polymorphism or late binding binding.
32) What is ‘IS-A ‘ relationship in java?
‘is a’ relationship is also known as inheritance. We can implement ‘is a’ relationship or inheritance
in java using
extends keyword. The advantage or inheritance or is a relationship is reusability of code instead
of duplicating the code.
Ex : Motor cycle is a vehicle
Car is a vehicle Both car and motorcycle extends vehicle.
public classInstanceOfExample
public static voidmain(String[] args)
Integer a = newInteger(5);
if (a instanceof java.lang.Integer) {
System.out.println(true);
} else {
System.out.println(false);
38) What all access modifiers are allowed for top class ?
For top level class only two access modifiers are allowed. public and default. If a class is declared
as public it is visible everywhere.
If a class is declared default it is visible only in same package.
If we try to give private and protected as access modifier to class we get the below compilation
error.
Illegal Modifier for the class only public,abstract and final are permitted.
40) Can we have more than one package statement in source file ?
We can’t have more than one package statement in source file. In any java program there can be
atmost only 1package statement. We will get compilation error if we have more than one package
statement in source file.
44) What is the difference between access specifiers and access modifiers in java?
In C++ we have access specifiers as public,private,protected and default and access modifiers as
static, final. But there is no such divison of access specifiers and access modifiers in java. In Java
we have access modifiers and non access modifiers.
Access Modifiers : public, private, protected, default Non Access Modifiers : abstract, final, stricfp.
Syntax :
try
}
Catch(Exception e)
63) Can we have any code between try and catch blocks?
We shouldn’t declare any code between try and catch block. Catch block should immediately start
after try block.
try{
//code
}
System.out.println(“one line of code”); // illegal
catch(Exception e){
//
}
64) Can we have any code between try and finally blocks?
We shouldn’t declare any code between try and finally block. finally block should immediately
start after catch block. If there is no catch block it should immediately start after try block.
try{
//code
}
System.out.println(“one line of code”); // illegal
finally{
//
}
65) Can we catch more than one exception in single catch block?
From Java 7, we can catch more than one exception with single catch block. This type of
handling reduces the code duplication.
Note : When we catch more than one exception in single catch block , catch parameter is implicity
final. We cannot assign any value to catch parameter.
Ex : catch(ArrayIndexOutOfBoundsException || ArithmeticException e)
{
}
In the above example e is final we cannot assign any value or modify e in catch statement.
75) Can we use catch statement for checked exceptions when there is no chance of raising
exception in our code?
If there is no chance of raising an exception in our code then we can’t declare catch block for
handling checked exceptions .This raises compile time error if we try to handle checked
exceptions when there is no possibility of causing exception.
Process Thread
1) Program in execution. 1. Separate path of execution in program. One or more threads is called
as process.
2) Processes are heavy weight 2. Threads are light weight.
3) Processes require separate address space. 3. Threads share same address space.
4) Interprocess communication is expensive. 4. Interthread communication is less expensive
compared to processes.
5) Context switching from one process to another is costly. 5. Context switching between threads
is low cost.
109) When a thread is executing synchronized methods , then is it possible to execute other
synchronized methods simultaneously by other threads?
No it is not possible to execute synchronized methods by other threads when a thread is inside a
synchronized method.
110) When a thread is executing a synchronized method , then is it possible for the same thread
to access other synchronized methods of an object ?
Yes it is possible for thread executing a synchronized method to execute another synchronized
method of an object.
public synchronized void methodName()
{
}
To execute synchronized method first lock has to be acquired on that object. Once synchronized
method is called lock will be automatically acquired on that method when no other thread has lock
on that method. once lock has been acquired then synchronized method gets executed. Once
synchronized method execution completes automatically lock will be released. The prerequisite to
execute a synchronized method is to acquire lock before method execution. If there is a lock
already acquired by any other thread it waits till the other thread completes.
112) When do we use synchronized blocks and advantages of using synchronized blocks?
If very few lines of code requires synchronization then it is recommended to use synchronized
blocks. The main
advantage of synchronized blocks over synchronized methods is it reduces the waiting time of
threads and improves performance of the system.
116) What are thread priorities and importance of thread priorities in java?
When there are several threads in waiting, thread priorities determine which thread to run. In java
programming language every thread has a priority. A thread inherits priority of its parent thread.
By default thread has normal priority of 5. Thread scheduler uses thread priorities to decide when
each thread is allowed to run. Thread scheduler runs higher priority threads first.
Thread. MAX_PRIORITY=10;
118) How to change the priority of thread or how to set priority of thread?
Thread class has a set method to set the priority of thread and get method to get the priority of
the thread.
Signature : final void setPriority(int value);
The setPriority() method is a request to jvm to set the priority. JVM may or may not oblige the
request.
We can get the priority of current thread by using getPriority() method of Thread class.
final int getPriority()
{
}
119) If two threads have same priority which thread will be executed first ?
We are not guaranteed which thread will be executed first when there are threads with equal
priorities in the pool. It depends on thread scheduler to which thread to execute. The scheduler
can do any of the following things :
1) It can pick any thread from the pool and run it till it completes.
2) It can give equal opportunity for all the threads by time slicing.
122) Is it possible for yielded thread to get chance for its execution again ?
yield() causes current thread to sleep for specified amount of time giving opportunity for other
threads of equal priority to
execute. Thread scheduler decides whether it get chance for execution again or not. It all
depends on mercy of thread
scheduler.
public static native void sleep(long millis) throws
InterruptedException{
public static void sleep(long millis, int nanos)
throws InterruptedException {
125) Assume a thread has lock on it, calling sleep() method on that thread will release the lock?
Calling sleep() method on thread which has lock does’nt affect. Lock will not be released though
the thread sleeps for a specified amount of time.
128) Explain about interthread communication and how it takes place in java?
Usually threads are created to perform different unrelated tasks but there may be situations
where they may perform
related tasks. Interthread communication in java is done with the help of following three methods :
1) wait()
2) notify()
3) notifyAll()
129) Explain wait(), notify() and notifyAll() methods of object class ?
wait() : wait() method() makes the thread current thread sleeps and releases the lock until some
other thread acquires the lock and calls notify().
notify() :notify() method wakes up the thread that called wait on the same object.
notfiyAll() :notifyAll() method wakes up all the threads that are called wait() on the same object.
The highest priority threads will run first.
All the above three methods are in object class and are called only in synchronized context.
All the above three methods must handle InterruptedException by using throws clause or by
using try catch clause.
130) Explain why wait() , notify() and notifyAll() methods are in Object class rather than in thread
class?
First to know why they are in object class we should know what wait(), notify(), notifyAll() methods
do. wait() , notify(), notifyAll() methods are object level methods they are called on same
object.wait(), notify(), notifyAll() are called on an shared object so to they are kept in object class
rather than thread class.
140) What are inner classes or non static nested classes in java?
Nested classes without any static keyword declaration in class definition are defined as non static
nested classes.
Generally non static nested classes are referred as inner classes.
There are three types of inner classes in java :
1) Local inner class
2) Member inner class
3) Anonymous inner class
144) Explain about method local inner classes or local inner classes in java?
Nested classes defined inside a method are local inner classes. We can create objects of local
inner class only inside
method where class is defined. A local inner classes exist only when method is invoked and goes
out of scope when method returns.
Runnable r = new Runnable() {
@Override
public void run() {
}};
Runnable is an interface.If we see the above code it looks like we are instantiating Runnable
interface. But we are not
instantiating interface we are instantiating anonymous inner class which is implementation of
Runnable interface.
9. What is an XPath?
Xpath or XML path is a query language for selecting nodes from XML documents. XPath
is one of the locators supported by selenium webdriver.
12. What is the difference between single slash(/) and double slash(//) in XPath?
In XPath a single slash is used for creating XPaths with absolute paths beginning from
root node.
Whereas double slash is used for creating relative XPaths.
13. How can we inspect the web element attributes in order to use them in different
locators?
Using Firebug or developer tools we can inspect the specific web elements.
Firebug is a plugin of firefox that provides various development tools for debugging
applications. From automation perspective, firebug is used specifically for inspecting
web-elements in order to use their attributes like id, class, name etc. in different locators.
14. How can we locate an element by only partially matching its attributes value in
Xpath?
Using contains() method we can locate an element by partially matching its attribute’s
value. This is particularly helpful in the scenarios where the attributes have dynamic
values with certain constant part.
xPath expression = //*[contains(@name,'user')]
The above statement will match the all the values of name attribute containing the word
‘user’ in them.
xPathExpression = //*[text()='username']
18. What is the syntax of finding elements by class using CSS Selector?
By .className we can select all the element belonging to a particluar class e.g. ‘.red’
will select all elements having class ‘red’.
20. How can we select elements by their attribute value using CSS Selector?
Using [attribute=value] we can select all the element belonging to a particluar class e.g.
‘[type=small]’ will select the element having attribute type of value ‘small’.
21. How can we move to nth child element using css selector?
Using :nth-child(n) we can move to the nth child element e.g. div:nth-child(2) will locate
2nd div element of its parent.
WebDriver driver = new FirefoxDriver();
WebElement searchTextBox = driver.findElement(By.id("search"));
searchTextBox.sendKeys("searchTerm");
driver.findElement(By.id("elementLocator")).clear();
driver.findElement(By.id("form1")).submit();
Also, the click() method can be used for the same purpose.
for (String windowHandle : driver.getWindowHandles()) {
driver.switchTo().window(handle);
}
31. What is the difference between driver.getWindowHandle() and
driver.getWindowHandles() in selenium?
driver.getWindowHandle() returns a handle of the current page (a unique identifier)
Whereas driver.getWindowHandles() returns a set of handles of the all the pages
available.
driver.switchTo().frame("{frameIndex/frameId/frameName}");
For locating a frame we can either use the index (starting from 0), its name or Id.
driver.manage().window().maximize();
String text = driver.findElement("elementLocator").getText();
37. How can we find the value of different attributes like name, class, value of an
element?
Using getAttribute(“{attributeName}”) method we can find the value of different attrbutes
of an element e.g.-
String valueAttribute =
driver.findElement(By.id(“elementLocator”)).getAttribute(“value”);
41. What are some expected conditions that can be used in Explicit waits?
Some of the commonly used expected conditions of an element that can be used with
expicit waits are-
elementToBeClickable(WebElement element or By locator)
stalenessOf(WebElement element)
visibilityOf(WebElement element)
visibilityOfElementLocated(By locator)
invisibilityOfElementLocated(By locator)
attributeContains(WebElement element, String attribute, String value)
alertIsPresent()
titleContains(String title)
titleIs(String title)
textToBePresentInElementLocated(By, String)
Wait wait = new FluentWait(driver)
.withTimeout(20, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement textBox = wait.until(new Function() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("textBoxId"));
}
);
43. What are the different keyboard operations that can be performed in selenium?
The different keyboard operations that can be performed in selenium are-
.sendKeys(“sequence of characters”) – Used for passing charcter sequesnce to an input
or textbox element.
.pressKey(“non-text keys”) – Used for keys like control, function keys etc that ae non
text.
.releaseKey(“non-text keys”) – Used in conjuntion with keypress event to simulate
releasing a key from keyboard event.
44. What are the different mouse actions that can be performed?
The different mouse evenets supported in selenium are
click(WebElement element)
doubleClick(WebElement element)
contextClick(WebElement element)
mouseDown(WebElement element)
mouseUp(WebElement element)
mouseMove(WebElement element)
mouseMove(WebElement element, long xOffset, long yOffset)
Actions action = new Actions(driver);
WebElement element=driver.findElement(By.id("elementId"));
action.doubleClick(element).perform();
Tooltips webelements have an attribute of type ‘title’. By fetching the value of ‘title’
attribute we can verify the tooltip text in selenium.
Using linkText() and partialLinkText() we can locate a link. The difference between the
two is linkText matches the complete string passed as parameter to the link texts.
Whereas partialLinkText matches the string parameter partially with the link texts.
Desired capabilities are a set of key-value pairs that are used for storing or configuring
browser specific properties like its version, platform etc in the browser instances.
All the links are of anchor tag ‘a’. So by locating elements of tagName ‘a’ we can find all
the links on a webpage.
60. How can we check if an element is enabled for interaction on a web page?
Using isEnabled method we can check if an element is enabled or not.
driver.findElement(By locator).isEnabled();
61. What is the difference between driver.findElement() and driver.findElements()
commands?
The difference between driver.findElement() and driver.findElements() commands is-
findElement() returns a single WebElement (found first) based on the locator passed as
parameter. Whereas findElements() returns a list of WebElements, all satisfying the
locator value passed.
Syntax of findElement()-
WebElement textbox = driver.findElement(By.id(“textBoxLocator”));
Syntax of findElements()-
List elements = element.findElements(By.id(“value”));
Another difference between the two is- if no element is found then findElement() throws
NoSuchElementException whereas findElements() returns a list of 0 elements.
62. Explain the difference between implicit wait and explicit wait.?
An implicit wait, while finding an element waits for a specified time before throwing
NoSuchElementException in case element is not found. The timeout value remains valid
throughout the webDriver’s instance and for all the elements.
driver.manage().timeouts().implicitlyWait(180, TimeUnit.SECONDS);
Whereas, Explicit wait is applied to a specified element only-
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.presenceOfElementLocated(ElementLocator));
It is advisable to use explicit waits over implicit waits because higher timeout value of
implicit wait set due to an element that takes time to be visible gets applied to all the
elements. Thus increasing overall execution time of the script. On the other hand, we
can apply different timeouts to different element in case of explicit waits.
63. How can we handle window UI elements and window POP ups using selenium?
Selenium is used for automating Web based application only(or browsers only). For
handling window GUI elements we can use AutoIT. AutoIT is a freeware used for
automating window GUI. The AutoIt scripts follow simple BASIC lanaguage like syntax
and can be easily integrated with selenium tests.
66. How to handle HTTPS website in selenium? or How to accept the SSL untrusted
connection?
Using profiles in firefox we can handle accept the SSL untrusted connection certificate.
Profiles are basically set of user preferences stored in a file.
FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(true);
profile.setAssumeUntrustedCertificateIssuer(false);
WebDriver driver = new FirefoxDriver(profile);
public class SamplePage {
WebDriver driver;
@FindBy(id="search")
WebElement searchTextBox;
@FindBy(name="searchBtn")
WebElement searchButton;
//Constructor
public samplePage(WebDriver driver){
this.driver = driver;
//initElements method to initialize all elements
PageFactory.initElements(driver, this);
}
//Sample method
public void search(String searchTerm){
searchTextBox.sendKeys(searchTerm);
searchButton.click();
}
<suite name="sampleTestSuite">
<test name="sampleTest">
<parameter name="sampleParamName" value="sampleParamValue"/>
<classes>
<class name="TestFile" />
</classes>
</test>
</suite>
public class TestFile {
@Test
@Parameters("sampleParamName")
public void parameterTest(String paramValue) {
System.out.println("Value of sampleParamName is " +
sampleParamName);
}
//Data provider returning 2D array of 3*2 matrix
@DataProvider(name = "dataProvider1")
public Object[][] dataProviderMethod1() {
return new Object[][] {{"kuldeep","rana"}, {"k1","r1"},
{"k2","r2"}};
}
//This method is bound to the above data provider returning 2D array
of 3*2 matrix
//The test case will run 3 times with different set of values
@Test(dataProvider = "dataProvider1")
public void sampleTest(String s1, String s2) {
System.out.println(s1 + " " + s2); }
@Listeners(PackageName.CustomizedListenerClassName.class)
public class TestClass {
WebDriver driver= new FirefoxDriver();@Test
public void testMethod(){
//test logic
}}
91. What is the use of @Factory annotation in TestNG?
@Factory annotation helps in dynamic execution of test cases. Using @Factory
annotation we can pass parameters to the whole test class at run time. The parameters
passed can be used by one or more test methods of that class.
Example – there are two classes TestClass and the TestFactory class. Because of the
@Factory annotation the test methods in class TestClass will run twice with the data “k1”
and “k2”
public class TestClass{
private String str;
//Constructor
public TestClass(String str) {
this.str = str;
}
@Test
public void TestMethod() {
System.out.println(str);
}}
public class TestFactory{
//The test methods in class TestClass will run twice with data "k1"
and "k2"
@Factory
public Object[] factoryMethod() {
return new Object[] { new TestClass("K1"), new
TestClass("k2") }; }}
93. How can we make one test method dependent on other using TestNG?
Using dependsOnMethods parameter inside @Test annotation in testNG we can make
one test method run only after successful execution of dependent test method.
@Test(dependsOnMethods = { “preTests” })