Java Basics: JVM, Variables, OOPs Features
Java Basics: JVM, Variables, OOPs Features
A Java Virtual Machine (JVM) is a software component that allows Java programs to
run on different operating systems by acting as an interpreter between the compiled
Java bytecode and the underlying hardware, essentially creating a platform-
independent environment for executing Java applications; it verifies, loads, and
executes the bytecode, providing a runtime environment for Java programs to
function on various platforms.
JDK JRE
JVM
Used to develop Java applications Used to run Java
applications Responsible for running Java code
instance variable are variable which are declared inside the class but out side the
any method or block called instance variable.
instance variables are intiated at the time of the class loading.
instance user or programer need not provide the defualt intialization value to the
variable this will be provided by the jbl.
local variables:- these variables are declared with in the method but not get any
defualt value.
In programming, a local variable is declared within a method or block and is only
accessible within that specific scope.
static variable:-if the request is that the value of the variable thats not change
from object to object we go with static variables.
like instance variables and static variable should be declared with in the class
but outside any method or block.
the variable that is requested to be declared as ststic keyword should be declared
with the static keyword.
4)What if I write static public void instead of public static void main?
Yes, the Java program will run successfully if you write static public void main
instead of the conventional public static void main. Java is flexible regarding the
order of access modifiers, and both declarations are valid for the main method.
Public
The least restrictive access specifier
Classes, methods, and data members can be accessed from anywhere in the program
Typically used for methods and variables that need to be available to all other
classes
Protected
Similar to private, but provides limited access to other classes
Class members can be accessed within the class and its subclasses
Allows subclasses to access and override base class members
Private
The most restrictive access specifier
Methods, functions, and variables can only be accessed within their particular
class
Useful to hide data from the outside world
Default
Also known as package-private
The default class access level when no access specifier is specified
The class can be accessed only within the same package in which it is declared
In Java, a class is a blueprint for creating objects. It defines the structure and
behavior of objects that are created from it. Classes are a fundamental building
block of object-oriented programming.
parameter constructer:-
A primitive data type is a basic, built-in data type that directly stores simple
values like numbers, characters, or booleans, while a non-primitive data type is a
more complex data structure, like an array or object, which stores a reference to a
memory location where the actual data is held, allowing for more complex data
manipulation and flexibility; essentially, primitive types store the value itself,
while non-primitive types store a reference to the value in memory.
Key Differences:
Storage:
Primitive data types store the actual value directly in memory, whereas non-
primitive types store a reference to the data's location in memory.
Mutability:
Primitive data types are usually immutable (cannot be changed once assigned), while
non-primitive types can be mutable (their values can be modified).
Abstraction:-
hiding the internal implimaentaion details and showing only the fuctionality to the
user called abstraction.
@Override
void turnOff() {
[Link]("TV is turned OFF.");
}
}
ex:-
class GFG {
// Function to print N Fibonacci Number
static void Fibonacci(int N)
{
int num1 = 0, num2 = 1;
// Swap
int num3 = num2 + num1;
num1 = num2;
num2 = num3;
}
}
// Driver Code
public static void main(String args[])
{
// Given Number N
int N = 10;
// Function Call
Fibonacci(N);
}
}
[Link]:-
inheritence one acquires the properties of other classes can be called inhertiance
In Java, Inheritance means creating new classes based on existing ones.
Ex:-
// Driver Class
class Gfg {
public static void main(String args[])
{
Engineer E1 = new Engineer();
[Link]("Salary : " + [Link]
+ "\nBenefits : " + [Link]);
}
}
Ex:-
// Parent class
class One {
public void print_geek()
{
[Link]("Geeks");
}
}
// Driver class
public class Main {
// Main function
public static void main(String[] args)
{
Two g = new Two();
g.print_geek();
g.print_for();
}
}
3. polymporphisam:-
*method overloading:-
in a class if there is method with a same name, but varying with the number or type
of argument can be
consider as a method overloading.
// Class 1
// Helper class
class Helper {
// Method 2
// With same name but with 2 double parameters
static double Multiply(double a, double b)
{
// Returns product of double numbers
return a * b;
}
}
// Class 2
// Main class
class Geeks
{
// Main driver method
public static void main(String[] args) {
*method overridding:-
or
method overriding in java if sub class has the same method as declared in the
parent class.
when there is parent child relationship and both parent and child method with the
same name ,same return type
same number of arguments but varying with implation and when an object is created
like parent p=newchild
and when the method is invoked child method will be excuted insted of parent child.
Output
Dog is running.
Animal is eating.
Dog is barking.
[Link]:-
Encapsulation in Java is a technique for bundling data and methods into a single
unit, or class. This helps to hide the internal state of an object and only expose
what's necessary. using getter and setter method .
Output
Name: John
Age: 30
10) What is the Difference Between Method Overloading and Method Overriding?
Abstract class in java were the class is declred with the keyword as Abstract.
Abstract class can conatain abstract method and normal method as well.
but Abstract can't be intialised or object can't be created for an abstract class.
the class that id declared as abstact should be extened by normal and defination or
the implimentation for the abstract methods
should be provided by the class that extend the abstract class.
Abstatct can have the constructer.
the variable that are declared the inside the abstarct class need not to be final
or default it can be normal variable as well.
if the request is we are not sure about all the functionality of module we go with
abstarct class.
Abstrct keyword is associated with class or methods only it can't be applied
variables.
how to a restrict a class for creation of object or from instiation we can restrict
by declaring that particular as abstract.
Ex:-
abstract class Animal {
public abstract void animalSound();
public void sleep() {
[Link]("Zzz");
}
}
o/p:-zzzz
From the example above, it is not possible to create an object of the Animal class:
Ex:-
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
[Link]("Zzz");
}
}
o/p:-
The pig says: wee wee
Zzz
interface:-
the interfac is declared with interface keyword.
interface is fully abstarct blue print.
method present inside the interfce is public static by defualt.
varibles present inside the the inteferece are final by defualt.
interface can't have constructer.
the class that impliments the interface provide the implimentation for the abstract
methods.
multiple inheritence can be achived with the help of interfaces.
ex;-multiple inhertence
class a
class b
class c extends a ,b
ex:-
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
[Link]();
[Link]();
}
}
o/p:-
The pig says: wee wee
Zzz
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
}
class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
[Link]();
[Link]();
}
}
o/p:-
Some text...
Some other text..
In Java, ‘this’ is a reference variable that refers to the current object, or can
be said “this” in Java is a keyword that refers to the current object instance. It
can be used to call current class methods and fields, to pass an instance of the
current class as a parameter, and to differentiate between the local and instance
variables. Using “this” reference can improve code readability and reduce naming
conflicts.
super keyword:
The super keyword in Java is a reference variable that is used to refer to parent
class when we’re working with objects.
n a Java program, there are primarily two types of exceptions: checked exceptions
(compile-time exceptions) and unchecked exceptions (runtime exceptions).
The throws keyword indicates what exception type may be thrown by a method.
There are many exception types available in Java: ArithmeticException,
ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc.
Ex:-
The finally keyword is used to execute code (used with exceptions - try..catch
statements) no matter if there is an exception or not.
ex:-
try {
int[] myNumbers = {1, 2, 3};
[Link](myNumbers[10]);
} catch (Exception e) {
[Link]("Something went wrong.");
} finally {
[Link]("The 'try catch' is finished.");
}
The final keyword is a non-access modifier used for classes, attributes and
methods, which makes them non-changeable (impossible to inherit or override).
The final keyword is useful when you want a variable to always store the same
value, like PI (3.14159...)
The finally keyword is used to execute code (used with exceptions - try..catch
statements) no matter if there is an exception or not.
The finalize() method in Java is a method of the Object class used to perform
cleanup activity before destroying any object.
18) What are the differences between this and super keyword?
list set
map
The list interface allows duplicate elements. Set does not allow duplicate
elements. The map does not allow duplicate elements
The list maintains insertion order. Set do not maintain any insertion
order. map do not maintain any insertion order.
We can add any number of null values. But in set almost only one null
value. The map allows a single null key
List implementation classes are array Set implementation classes are
HashSet, Map implementation classes are HashMap,
list,linked list LinkedHashSet, and TreeSet.
TreeMap, ConcurrentHashMap,LinkedHashMap.
List:-
public class GFG {
// Creating a List
ArrayList<String> al = new ArrayList<>();
Set:-
public class SetExample {
// Adding Elements
[Link]("one");
[Link]("two");
[Link]("three");
[Link]("four");
[Link]("five");
Map:-
class MapExample {
100 Amit
101 Vijay
102 Rahul
20) How does garbage collection work in Java? Explain the different generations
of the garbage collector.
Java garbage collection is an automatic process that manages memory in the heap.
It identifies which objects are still in use (referenced) and which are not in use
(unreferenced).
Unreferenced objects can be deleted to free up memory.
The programmer does not need to mark objects to be deleted explicitly. The garbage
collection implementation lives in the JVM.
Young Generation:
Eden Space: This is where newly created objects are initially allocated.
Survivor Spaces (S0 and S1): When an object survives a garbage collection cycle in
Eden, it is moved to one of the Survivor spaces. During the next collection,
surviving objects are moved to the other Survivor space, and if they still survive,
they are then promoted to the Old Generation.
Old Generation (Tenured Generation):
This is where long-lived objects that have survived multiple garbage collection
cycles in the Young Generation are stored. Garbage collection in the Old Generation
is typically less frequent but more expensive than in the Young Generation.
21) Can you explain the concept of serialization in Java? How do you serialize
and deserialize objects?
Serialization in Java is the process of converting an object into a byte stream,
which can be easily saved to a file, transmitted over a network, or stored in a
database.
The byte stream created is platform independent. So, the object serialized on one
platform can be deserialized on a different platform. To make a Java object
serializable we implement the [Link] interface. The
ObjectOutputStream class contains writeObject() method for serializing an Object.
StringBuilder StringBuffer
uses:-
StringBuilder class can be used when you want to modify a string without creating a
new object. For example, using the StringBuilder class can boost performance when
concatenating many strings together in a loop.
String buffers are safe for use by multiple threads. The methods can be
synchronized wherever necessary so that all the operations on any particular
instance behave as if they occur in some serial order.
23) Can you explain the concept of Java annotations?Provide examples of built-in
annotations and their usage.
@Override:
Used to explicitly mark a method as overriding a method from a superclass, helping
catch potential errors if the method signature is accidentally changed.
@Deprecated:
Indicates that a method or class is considered outdated and should be avoided,
prompting a compiler warning when used.
@SuppressWarnings:
Tells the compiler to suppress specific warnings for a section of code, allowing
developers to bypass warnings when they are confident the code is correct.
@FunctionalInterface:
Marks an interface as a functional interface, which means it has exactly one
abstract method and can be used with lambda expressions.
@SafeVarargs:
A programmer assertion that a method does not perform unsafe operations on its
varargs parameter, helping to identify potential security vulnerabilities.
@Override // Indicates this method overrides a parent class method [1, 2, 10]
// Method implementation
}
@Deprecated // Marks this method as outdated, generates a warning [1, 2, 10]
// Method implementation
}
public void anotherMethod() {
@SuppressWarnings("unchecked")
// Interface definition
@FunctionalInterface
interface MyFunctionalInterface {
hashmap
hashtable
no methed is syncronised .
every method is syncronised.
Multiple threads can operate simultaneously and At a time only
one thread is allowed to operate the Hashtable’s object is not thread safe.
Hence it is thread-safe.
performance is high. performance is low.
It is non-legacy. It is non-legacy.
class Ideone
{
public static void main(String args[])
{
//----------hashtable -------------------------
Hashtable<Integer,String> ht=new Hashtable<Integer,String>();
[Link](101," ajay");
[Link](101,"Vijay");
[Link](102,"Ravi");
[Link](103,"Rahul");
[Link]("-------------Hash table--------------");
for ([Link] m:[Link]()) {
[Link]([Link]()+" "+[Link]());
}
//----------------hashmap--------------------------------
HashMap<Integer,String> hm=new HashMap<Integer,String>();
[Link](100,"Amit");
[Link](104,"Amit");
[Link](101,"Vijay");
[Link](102,"Rahul");
[Link]("-----------Hash map-----------");
for ([Link] m:[Link]()) {
[Link]([Link]()+" "+[Link]());
}
}
}
Output
-------------Hash table--------------
103 Rahul
102 Ravi
101 Vijay
-----------Hash map-----------
100 Amit
101 Vijay
102 Rahul
104 Amit
Array
collection
Arrays are fixed in size that is once we create Collection
are growable in nature that is based on our
an array we can not increased or decreased based
requirement. We can increase or decrease of size.
on our requirement.
Write in memory Arrays are not recommended to use. Write in
memory collection are recommended to use.
Arrays can hold only homogeneous data types elements. Collection can
hold both homogeneous and heterogeneous
elements.
Arrays can hold both object and primitive data type . Collection can
hold only object types but not primitive
datatypes such as int, long,
short, etc
26) What are the various interfaces used in Java Collections Framework?
The primary interfaces used in the Java Collections Framework are: Collection,
List, Set, Queue, Map, SortedSet, NavigableSet, Deque, and SortedMap; with
"Collection" being the most fundamental interface, and the others extending it to
provide specific functionalities like ordered sequences (List), unique elements
(Set), key-value pairs (Map), and FIFO access (Queue).
Explanation of key interfaces:
Collection:
The most basic interface, defining common operations like adding, removing, and
checking for elements in a collection.
List:
Represents an ordered collection where elements can be accessed using an index,
allowing for insertion and retrieval at specific positions.
Set:
Stores unique elements, meaning no duplicates are allowed within the collection.
Queue:
A collection that follows the First-In-First-Out (FIFO) principle, where the first
element added is the first to be removed.
Map:
Represents a collection of key-value pairs, where each unique key is associated
with a value.
SortedSet:
An extension of the Set interface that maintains elements in a sorted order.
Deque (Double-Ended Queue):
Allows adding and removing elements from both the front and back of the queue.
27) What are the differences between the constructors and methods?
constructer
method
class Person {
String name;
int age;
// Constructor
public Person(String name, int age) {
[Link] = name;
[Link] = age;
}
// Method
}
}
// Usage:
Person person1 = new Person("John", 30); // Creates a new Person object and calls
the constructor
Advanced features:
TestNG provides features like annotations to define test methods, grouping tests
based on functionality, setting priorities for test execution, and handling
dependencies between tests, which are not readily available in basic Selenium
WebDriver.
Integration with Selenium:
TestNG seamlessly integrates with Selenium WebDriver, allowing you to write test
scripts using Selenium commands while leveraging TestNG's robust test management
capabilities.
Reporting:
TestNG generates comprehensive test reports that detail the execution status of
each test case, including pass/fail results, execution time, and error messages.
Parametrization:
TestNG allows you to easily parameterize test cases by providing data through data
providers, enabling you to run the same test with different sets of input data.
Parallel execution:
TestNG supports parallel test execution, which can significantly reduce the overall
test execution time.
30) Why should Selenium be selected as a testing tool for web applications or
systems?
Cross-browser compatibility:
Test web applications on multiple browsers like Chrome, Firefox, Safari, Edge,
etc., ensuring consistent functionality across different platforms.
Ease of use:
Relatively simple to learn and use, making it suitable for both beginners and
experienced testers.
31) What is meant by a locator and name a few different types of locators present
in Selenium
A locator is a way to find and match elements on a web page that Selenium needs to
interact with.
32) What is XPath in Selenium? Explain XPath Absolute and XPath Relative.
Absolute XPath: Begins from the root of the HTML document and specifies the
complete path to the element. It's not as flexible and can break if the page
structure changes. Relative XPath: Starts from a specific element and navigates
through the DOM hierarchy to locate the desired element.
driver = [Link]()
if len(checkbox_list) > 0:
To switch from the main page to a child frame (or iframe) in Selenium WebDriver,
use the switchTo().frame() method, providing either the frame's index, name, or ID,
or a WebElement representing the frame.
By Index:
[Link]().frame(0)
y Name or ID:
[Link]().frame("frameName") or [Link]().frame("frameId").
By WebElement:
If you have a WebElement representing the frame, use
[Link]().frame(frameWebElement).
Switching Back:
To return to the main page from a frame, use [Link]().defaultContent().
Switching to Parent:
To switch to the parent frame, use [Link]().parentFrame().
defaultContent(); in selenium helps to switch the context to top most frame which
is main page. Regardless of your current context, you can switch to the main page
using the driver. switchTo(). defaultContent(); switches the context back to the
main page automatically.
adavantages
#parrallel excecution
#dependency management
#priority excecution
#test grouping
#data driven testing
#flexibility
#integration with tools
#annotations
In the context of software testing and bug management, severity refers to the
impact a bug has on the software's functionality and user experience, while
priority determines the urgency or order in which bugs should be addressed.
High Priority:
While the issue might seem minor, it's crucial to fix it quickly because it
directly impacts the user's first impression and reflects poorly on the company's
professionalism.
Low Severity:
The actual functionality of the website or application remains intact, and the user
can still access and use it normally.
42)Difference between xpath and css selector
CSS selectors and XPath are both used to locate elements in web pages. CSS
selectors are simpler and faster, ideal for straightforward HTML element selection.
XPath, however, offers more flexibility and power, capable of navigating complex
and dynamic web page structures, including non-HTML elements.
In software testing, parameters are variables that hold data used to execute test
cases, allowing for dynamic testing with different inputs without duplicating test
scripts. For example, when testing a login feature, you can use parameters for
usernames and passwords to test various valid and invalid combinations.
Types of Parameters:
Step-specific Parameters: Parameters related to specific steps and treated
separately in each step.
Group Parameters: Parameters defined within a group of tests and reusable across
multiple tests within that group.
Export (out) Parameters: Parameters defined within a step and can be used later in
other steps, depending on the defined scope.
Test Data Parameters: Parameters defined in the test data and then used in the
various steps
For Java automation testing, popular test management tools include TestRail,
Zephyr, Qase, and Allure TestOps, which facilitate test case management, execution,
and reporting, often integrating with CI/CD systems.
To run test cases in parallel, use a testing framework that supports it, configure
the framework for parallel execution, and ensure your tests are designed to be
independent and safe for running concurrently.
Here's a more detailed breakdown:
1. Choose a Suitable Testing Framework:
JUnit (Java):
JUnit 5, in particular, supports parallel execution with specific configurations.
[Link] (Java):
TestNG is designed for parallel test execution and offers various options for
controlling the number of threads and test execution order.
The defect life cycle, also known as the bug life cycle, is a structured process
that outlines the stages a bug or defect goes through, from its identification to
its resolution, ensuring efficient management and tracking.
Here's a breakdown of the typical stages:
New/Identified: The defect is initially discovered and reported.
Assigned: The defect is assigned to a specific developer or team for resolution.
Open: The defect is open and actively being worked on.
Fixed: The developer identifies and implements a solution to the defect.
Retest/Verified: The defect is retested to ensure the fix is effective and doesn't
introduce new issues.
Reopened: If the retest reveals that the fix is not satisfactory, the defect is
reopened and the process restarts from the "Fixed" stage.
Closed: Once the defect is verified as resolved, it is closed.
Selenium Remote Control (RC) uses a proxy server and JavaScript commands to control
browsers, while Selenium WebDriver interacts directly with the browser at the
operating system level, offering a simpler, faster, and more reliable architecture
for browser automation.
Absolute XPath: Begins from the root of the HTML document and specifies the
complete path to the element. It's not as flexible and can break if the page
structure changes. Relative XPath: Starts from a specific element and navigates
through the DOM hierarchy to locate the desired element.
findElement():
Locates the first matching web element on the page based on the provided locator
strategy (e.g., ID, class name, XPath).
Returns a WebElement object representing the found element.
If no element matches the locator, it throws a NoSuchElementException.
findElements():
Locates all web elements on the page that match the provided locator strategy.
Returns a List<WebElement> containing all the matching elements.
If no elements match the locator, it returns an empty list, not an exception.
In Selenium, you handle popups and alerts using the Alert interface, which allows
you to switch to the popup, accept or dismiss the alert, and retrieve its text
using methods like accept(), dismiss(), and getText()
Handling Alerts:
To handle multiple browser windows or tabs in Selenium, you can use the
getWindowHandles() method to get a set of all window handles, then use
switchTo().window() to switch between them.
Close a Window:
Use [Link]() to close the currently active window.
58)What are implicit, explicit, and fluent waits in Selenium? How do they differ?
In Selenium, implicit waits set a global timeout for all element lookups, explicit
waits wait for specific conditions, and fluent waits offer more control over the
wait process, including polling intervals and exception handling.
1. Implicit Wait:
Purpose:
Instructs WebDriver to wait for a specified amount of time for an element to be
found before throwing an exception.
Example (Java):
[Link]().timeouts().implicitlyWait(10, [Link]);
2. Explicit Wait:
Purpose:
Pauses script execution until a specific condition is met (e.g., an element is
visible, clickable, or a certain value is present).
How it works:
You use WebDriverWait to wait for a condition to become true, and if the condition
is not met within the specified timeout, a TimeoutException is thrown.
3. Fluent Wait:
Purpose: Provides advanced control over the wait process, allowing you to customize
the polling interval, timeout, and exceptions to ignore.
To handle frames and iframes in Selenium WebDriver, you use the switchTo().frame()
method, specifying the frame by index, name/ID, or WebElement, and use
switchTo().defaultContent() to return to the main page.
Here's a breakdown:
Switching to a Frame:
By Index: [Link]().frame(0) (the first frame is index 0).
By Name or ID: [Link]().frame("frameNameOrId").
By WebElement:
Locate the frame element using a locator (e.g., [Link](), [Link]()).
WebElement frameElement = [Link]([Link]("frameId"));.
[Link]().frame(frameElement);.
Switching Back to Default Content: [Link]().defaultContent().
In Selenium, you can perform mouse and keyboard actions using the Actions class,
which allows you to simulate user interactions like clicks, hovers, drags, and
keyboard input.
Mouse Actions:
click(): Simulates a single left-click.
doubleClick(): Simulates a double-click.
clickAndHold(): Simulates a click and hold (without releasing).
contextClick(): Simulates a right-click (context menu).
dragAndDrop(WebElement source, WebElement target): Simulates dragging an element
from the source to the target.
dragAndDropBy(WebElement source, int xOffset, int yOffset): Simulates dragging an
element by a specified offset.
moveToElement(WebElement target): Moves the mouse cursor to the center of the
specified element.
moveByOffset(int xOffset, int yOffset): Moves the mouse cursor by a specified
offset.
release(): Releases the mouse button (used after clickAndHold or dragAndDropBy).
Keyboard Actions:
sendKeys(String text): Simulates typing text into a field or sending a sequence of
keys.
keyDown(Keys key): Simulates pressing down a key (e.g., Shift, Ctrl).
keyUp(Keys key): Simulates releasing a key.
[Link]().perform(): Chains multiple actions together and executes them.
Example (Java):
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
// Navigate to a webpage
[Link]("[Link] // Replace with your URL
// Find elements
WebElement button = [Link]([Link]("myButton"));
WebElement inputField = [Link]([Link]("myInput"));
source tree
test cases
agile methodology
To handle dynamic elements in Selenium WebDriver, you can use strategies like
explicit waits, relative locators, and JavaScript Executor, while avoiding hard-
coded delays and maintaining test scripts for robust automation.
In Selenium, you handle dropdowns (select elements) using the Select class, which
provides methods like selectByVisibleText(), selectByIndex(), and selectByValue()
to interact with the dropdown options.
Example (Java):
Java
import [Link];
import [Link];
import [Link];
import [Link];
65)What are the different types of exceptions in Selenium WebDriver, and how do you
handle them?
Selenium WebDriver exceptions, which indicate errors during test execution, are
broadly categorized as checked and unchecked, and common examples include
NoSuchElementException, TimeoutException, and StaleElementReferenceException.
Handling them involves using try-catch blocks, implementing waits, and verifying
the state of elements.
File Upload:
Locate the File Input Element:
Use Selenium's findElement method to find the <input type="file"> element on the
page.
File download:-
Configure Browser Options: If you're using Chrome or Firefox, you can configure
browser options to specify the download directory and handle downloads
automatically.
Selenium Grid is a tool within the Selenium suite that allows you to run tests in
parallel across multiple machines and browsers, significantly speeding up the test
execution process and enabling cross-browser testing. It works by routing commands
from a client to remote browser instances, managed by a hub and nodes architecture.
To run tests in parallel using Selenium Grid, configure your testing framework
(like TestNG or JUnit) to utilize the hub-node architecture of Selenium Grid,
enabling tests to execute simultaneously on multiple machines and browsers.
close() closes only the current window on which Selenium is running automated
tests. The WebDriver session, however, remains active. On the other hand, the
driver. quit() method closes all browser windows and ends the WebDriver session.
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
// Launch Website
[Link]("[Link]
// Create a reference
JavascriptExecutor js = (JavascriptExecutor)driver;
Selenium Webdriver can be used to handle Ajax calls. Ajax also known as
Asynchronous JavaScript is vastly made up of XML and JavaScript. From the UI point
of view, a JavaScript call is made to the server and we receive the response in XML
format from the server.
AJAX allows web pages to be updated asynchronously by exchanging data with a web
server behind the scenes. This means that it is possible to update parts of a web
page, without reloading the whole page.
75)What are headless browsers, and how do you use them with Selenium?
Benefits:
Faster Execution: No UI rendering speeds up test execution.
Resource Efficiency: Less memory and CPU usage compared to GUI-based browsers.
CI/CD Integration: Ideal for running tests in automated pipelines.
Headless browsers: Almost every modern browser has the option of running in
headless mode.
Chrome:
Use the ChromeOptions class to configure the browser.
Add the "--headless" argument to the options.
Example (Java):
Java
76)How can you integrate Selenium with testing frameworks like TestNG or JUnit?
To integrate Selenium with testing frameworks like TestNG or JUnit, you'll use
annotations within your test classes to define test cases, configurations, and
execution order, and then run these tests using the framework's tools.
import [Link];
import [Link];
import [Link];
@Test
public void myTest() {
WebDriver driver = new ChromeDriver();
[Link]("[Link]
// Add your test logic here
[Link]();
}
}
import [Link];
import [Link];
import [Link];
// Chrome test
[Link]("[Link]", "/path/to/chromedriver");
WebDriver chromeDriver = new ChromeDriver();
[Link]("[Link]
// Add your test logic here
[Link]();
// Firefox test
[Link]("[Link]", "/path/to/geckodriver");
WebDriver firefoxDriver = new FirefoxDriver();
[Link]("[Link]
// Add your test logic here
[Link]();
}
}
Parameters of pageLoadTimeout()
Duration of Timeout: This tells how long Selenium will wait for a page to load. It
is represented in numeric form. It tells the unit of time for the timeout like
seconds, milliseconds, minutes, etc. The most commonly used unit is seconds.
[Link]().timeouts().pageLoadTimeout(10, [Link]);
What is TestNG?
Testing Framework:
TestNG is a framework for writing and running tests, providing a structured way to
organize and execute test cases.
Open-Source:
It's an open-source project, making it freely available and widely used in the
testing community.
Features:
Test Groups: You can group tests for execution based on functionality or priority.
Data Providers: TestNG allows you to feed different data sets to your test methods,
enabling data-driven testing.
Test Dependencies: You can define dependencies between tests, ensuring that certain
tests are executed before others.
Parameterization: TestNG supports parameterization, allowing you to pass parameters
to test methods, making them more flexible.
Reporting: TestNG provides detailed reports, making it easy to identify failed
tests and understand execution results.
Configure TestNG:
Create a [Link] file to configure test suites, test cases, and parameters.
Run Tests:
Use the TestNG IDE plugin or command-line tools to execute your tests.
Analyze Reports:
Review the TestNG reports to identify failed tests and understand execution
results.
import [Link];
import [Link];
import [Link];
import [Link];
@BeforeTest
public void setUp() {
[Link]("[Link]", "path/to/[Link]");
driver = new ChromeDriver();
}
@Test
public void testExample() {
[Link]("[Link]
// Add your test logic here
}
@AfterTest
public void tearDown() {
[Link]();
}
}
try {
WebElement element = [Link]([Link]("myElement"));
[Link]();
} catch (StaleElementReferenceException e) {
WebElement element = [Link]([Link]("myElement")); // Re-
locate
[Link](); // Retry
The method scrollBy(x,y) scrolls the page relative to its current position. For
instance, scrollBy(0,10) scrolls the page 10px down.
This scrollTo() method is valuable for scrolling a web page to a specific location
using Selenium WebDriver. This method requires the (x, y) coordinates of the
desired location as arguments.
To manage SSL certificate issues in Selenium, you can use browser-specific options
to ignore certificate errors or accept untrusted certificates, or import the SSL
certificate into the browser's trust store.
To handle SSL certificate issues in Selenium Java, you can use browser-specific
options like ChromeOptions (for Chrome) or FirefoxOptions (for Firefox) to ignore
certificate errors or accept insecure certificates.
ChromeOptions options = new ChromeOptions();
[Link]("--ignore-certificate-errors");
[Link]("--ignore-ssl-errors=yes");
WebDriver driver = new ChromeDriver(options);
85)What are some common challenges you face in Selenium automation, and how do you
overcome them?
2. Cross-Browser Compatibility:
Challenge:
Ensuring tests work consistently across different browsers (e.g., Chrome, Firefox,
Safari) and versions can be complex.
Overcoming:
Cross-Browser Testing: Use Selenium Grid or cloud-based testing services to run
tests on multiple browsers simultaneously.
Browser-Specific Code: Implement conditional code to handle browser-specific quirks
or differences in rendering.
Browser Compatibility Testing: Thoroughly test your application on the target
browsers to identify and address any issues.
3. Asynchronous Operations:
Challenge:
Web applications often use asynchronous JavaScript techniques (AJAX calls,
timeouts) that can cause timing issues during testing.
Overcoming:
Explicit Waits: Use WebDriverWait to wait for specific conditions to be met before
proceeding.
Asynchronous JavaScript: Use [Link] to execute JavaScript
code asynchronously.
Event Listeners: Implement event listeners to track asynchronous events and ensure
that tests are synchronized with the application's behavior.
86)How can you simulate pressing browser back, forward, and refresh buttons in
Selenium
WebDriver?
Using [Link]().refresh()
1. to() Command
Loads a new web page in the current browser window. It accepts a string parameter
that specifies the URL of the web page to be loaded.
[Link]().to("[Link]
2. back() Command
Moves back one step in the browser’s history stack. It does not accept any
parameters and does not return anything.
[Link]().back();
3. forward() Command
Moves forward one step in the browser’s history stack. It does not accept any
parameters and does not return anything.
[Link]().forward();
4. refresh() Command
Reloads the current web page in the browser window. It does not accept any
parameters and does not return anything.
[Link]().refresh();
import [Link];
import [Link];
import [Link];
import [Link];
public class TooltipVerification {
The waitForVisible tells the IDE to wait for an element to exist and be visible.
This command will wait till element visible on the page. Once command will visible
on page, the Ui. Vision RPA selenium IDE will go for executing next command.
Implicit wait makes WebDriver to wait for a specified amount of time when trying to
locate an element before throwing a NoSuchElementException. When implicit wait is
set, the WebDriver will wait for a defined period, allowing for elements to load
dynamically.
To check for broken links in a web page using Selenium WebDriver, you can collect
all links using the <a> tag, send an HTTP request to each link, and analyze the
HTTP response code to determine if the link is valid or broken.
Here's a more detailed breakdown:
1. Setting up Selenium WebDriver:
Install Selenium WebDriver for your preferred language (e.g., Java, Python).
Download and install the appropriate browser driver (e.g., ChromeDriver,
GeckoDriver).
91)What are some best practices you follow while writing Selenium scripts?
4. Common ExpectedConditions:
In Selenium, a robot class is used to handle the keyboard and mouse functions. It
is used to close the pop-up window. You can get the window handle of the pop-up
window using the WindowHandle() function.
There are the four methods that we would be using along with the Alert interface:
void dismiss() – The dismiss() method clicks on the “Cancel” button as soon as the
pop up window appears. void accept() – The accept() method clicks on the “Ok”
button as soon as the pop up window appears.
[Link] dismiss(): This method clicks on the ‘Cancel’ button of the alert or dismiss
the popup . It returns void.
Syntax:
[Link]().alert().dismiss();
[Link] accept(): This method click on the ‘OK’ button of the alert and returns void
Syntax:
[Link]().alert().accept();
[Link] getText() : This method captures the alert message and returns the String.
Syntax:
[Link]().alert().getText();
[Link] sendKeys(String Text):This method passes some data to alert input text and
it returns void
Syntax:
[Link]().alert().sendKeys(“Text”);
95)How can you run Selenium tests in Jenkins for Continuous Integration?
To run Selenium tests in Jenkins for continuous integration, create a Jenkins job,
configure it to fetch your code repository, and add a build step to execute your
Selenium tests, optionally using plugins for reporting and integration with tools
like Maven.
To perform responsive testing with Selenium WebDriver, you can simulate different
screen sizes by resizing the browser window using manage().window().setSize(width,
height) and then verifying the website's layout and functionality across those
sizes.
import [Link];
import [Link];
import [Link];
import [Link];
// Perform double-click
Actions act = new Actions(driver);
[Link](element).perform();
// Perform right-click
[Link](element).perform();
Step 1: Prepare the Test Data. First, we need an Excel sheet on which we will have
the test information. ...
Step 2: Set Up the Test Code. Here is a Code in Java language. ...
Step 3: Execute the Test Script. This script executes just to read each row from
the Excel file.
99)What are the challenges of automating CAPTCHA with Selenium WebDriver?
To generate reports for Selenium test execution, you can leverage external tools
like TestNG, JUnit, or Extent Reports, which offer customizable and detailed
reports, including test status, logs, and screenshots.
PROGRAMS:-
A given number can be said palindromic in nature if the reverse of the given number
is the same as that of a given number. In this article, we will write a Program to
check if a number is a Palindrome Number in Java.
Input : n = 46355364
Output: Reverse of n = 46355364
Palindrome : Yes
Input : n = 1234561111111111654321
Output: Reverse of n = 1234561111111111654321
Palindrome : Yes
temp = num;
//loop to find reverse number
while (temp != 0)
{
rem = temp % 10;
reverse = reverse * 10 + rem;
temp /= 10;
};
PRIME NUMBER:-
class Prime2 {
static boolean isPrime(int n)
{
// Corner case
if (n <= 1)
return false;
return true;
}
// Driver Program
public static void main(String args[])
{
if (isPrime(11))
[Link](" true");
else
[Link](" false");
if (isPrime(15))
[Link](" true");
else
[Link](" false");
}
}
NTH FIBONASERIES:-
class Fibo1 {
// Function to calculate the nth Fibonacci number using
// recursion
static int nthFibonacci(int n){
// Base case: if n is 0 or 1, return n
if (n <= 1) {
return n;
}
// Recursive case: sum of the two preceding
// Fibonacci numbers
return nthFibonacci(n - 1) + nthFibonacci(n - 2);
}
package main11;
package main11;
int max=arr[0];
for(int i=1;i<[Link];i++) {
if(arr[i]>max)
{
max=arr[i];
}
}
[Link]("largest number in the array=" +max);
}
[Link](s);
}
// Function call
remove(a);
}
}
package main11;
}
}}
package main11;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
// Navigate to Amazon
[Link]("[Link]
try {
// Save the screenshot to desired location
[Link](screenshot, new File("amazon_screenshot.png"));
[Link]("Screenshot taken successfully!");
} catch (IOException e) {
[Link]("Failed to save screenshot: " + [Link]());
}