Java code examples

import java.util.HashMap;

import java.util.Map;

public class PeopleAddressList { private Map<String, String> addressList; public PeopleAddressList() { addressList = new HashMap<>(); }

public void addPerson(String name, String address) { addressList.put(name, address); }

public String getAddress(String name) { return addressList.get(name); }

public void removePerson(String name) { addressList.remove(name); }

public int size() { return addressList.size(); }

public void clear() { addressList.clear(); }

public void printAddressList() { for (String name : addressList.keySet()) { System.out.println(name + ” : ” + addressList.get(name)); } }

public static void main(String[] args) { PeopleAddressList list = new PeopleAddressList(); list.addPerson(“John Doe”, “123 Main Street”);

list.addPerson(“Jane Doe”, “456 Elm Street”); list.printAddressList(); }}

//Main class as below

import java.util.HashMap;

import java.util.Map;

public class AddressSummary {

private PeopleAddressList addressList; public void setAddressList(PeopleAddressList addressList) { this.addressList = addressList; }

public String toString() { StringBuilder sb = new StringBuilder(); for (String name : addressList.keySet()) { sb.append(name + ” : ” + addressList.get(name) + “\n”); } return sb.toString(); }

public static void main(String[] args) { AddressGeneration generation = new AddressGeneration(); PeopleAddressList list = generation.getPeopleAddressList(); AddressSummary summary = new AddressSummary(); summary.setAddressList(list); System.out.println(summary); }}

public class AddressGeneration {

public PeopleAddressList getPeopleAddressList() { PeopleAddressList list = new PeopleAddressList(); list.addPerson(“John Doe”, “123 Main Street”);

list.addPerson(“Jane Doe”, “456 Elm Street”);

return list; }}

//Facade Design pattern

import java.util.HashMap;
import java.util.Map;

public class AddressSummaryFacade {

private AddressGeneration generation;
private AddressSummary summary;

public AddressSummaryFacade() {
    generation = new AddressGeneration();
    summary = new AddressSummary();

public String getAddressSummary() {
    return summary.toString();


public class Main {

public static void main(String[] args) {
    AddressSummaryFacade facade = new AddressSummaryFacade();


tablesaw vs apachepoi

import*;import org.apache.poi.xssf.usermodel.XSSFWorkbook;import tech.tablesaw.api.Table;import org.openjdk.jmh.annotations.*;import;import;import;@BenchmarkMode(Mode.Throughput)@Warmup(iterations = 3, time = 1)@Measurement(iterations = 5, time = 1)@State(Scope.Benchmark)public class ExcelReadBenchmark { private File excelFile; private Table tablesawTable; @Setup public void setup() { // Initialize your Excel file and Tablesaw table here excelFile = new File(“your-excel-file.xlsx”); // Replace with your Excel file path tablesawTable =“your-csv-file.csv”); // Replace with your CSV file path } @Benchmark public void readAndPrintWithTablesaw() { // Perform reading and printing using Tablesaw String column1 = tablesawTable.column(“Column1”).toString(); // Print or process column1 here } @Benchmark public void readAndPrintWithApachePOI() throws IOException { // Perform reading and printing using Apache POI FileInputStream inputStream = new FileInputStream(excelFile); Workbook workbook = new XSSFWorkbook(inputStream); Sheet sheet = workbook.getSheetAt(0); // Assuming the data is in the first sheet for (Row row : sheet) { Cell cell = row.getCell(0); // Access the first cell (column 1) if (cell != null) { String cellValue = cell.toString(); // Print or process cellValue here } } workbook.close(); inputStream.close(); } public static void main(String[] args) throws Exception { org.openjdk.jmh.Main.main(args); }}

read from 100 to 200

import tech.tablesaw.api.*;

public class ReadCSVWithTablesaw {

public static void main(String[] args) {
    // Define the path to your CSV file
    String csvFilePath = "path/to/your/file.csv"; // Replace with your CSV file path

    // Define the range of rows you want to read (100 to 200)
    int startRow = 100;
    int endRow = 200;

    try {
        // Define read options
        CsvReadOptions options = CsvReadOptions.builder(csvFilePath)
                .header(true) // Assuming the CSV file has a header row

        // Read the CSV file into a Table
        Table table =;

        // Extract the desired rows (100 to 200) from column 1
        Column<String> column1 = table.column(1).subList(startRow, endRow + 1).asStringColumn();

        // Print or process the values in column1
        for (String value : column1) {
    } catch (Exception e) {



Selenide is a wrapper jar to Selenium automation projects.

How to get Selenide jars – reference

How does I disable webdriver manager api calls to github to avoid driver.exe pulls?

system property -Dselenide.driverManagerEnabled=false can avoid pulling driver exes and you could define driver binary path in selenium project configurations itself

Angular 12.1 new features

Angular 12.1 new features:

Improved CLI performanceng build defaults to prod, that avoids accident production deployment from development builds

New @use syntax points to new Saas API in Angular 12.1. Automatically happens when you do ng update on Angular 12.1

Angular components supports in line Saas in styles field in @component decorator

Strict mode can be enabled via CLI to catch errors early in development cycle

Webpack 5 module is Production ready

Unused methods will be removed to improve performance by DomAdaptor

Custom router outlet implementations are allowed

min max validators for forms are added

TypeScript 4.2 support has been added and dropped support for TypeScript 4.0 and 4.1

Deprecating support for IE11

Above some of the features, please go through official Angular docs for detailed info.

How to handle Webtable in Selenium

Simple way to handle Webtable in Selenium Web Automation

Steps/coding/dom inspecting logic:

  1. Right Click and Inspect html for table
  2. Identify the patern for colum 1 of table
  3. Carefully observe the xpath of column 1 row 1 to row 3
  4. Notice that xpath has “tr[1]/td[1]”, “tr[2]/td[1]” , “tr[3]/td[1]” etc for following rows in colmn 1
  5. Use For loop and replace tr[1],tr[2],tr[3] with for loop variable “i”

What is a proxy server?

What is a proxy server?

Proxy server is a server that acts like a middle-man between your computer and internet.

Why Proxy servers are used?

Main prupose is security by hiding your machine ip from internet.

Also tracking employee activity on various aite they access

What is VPN and why VPN is used?

Virtual private Network is used for data protection and building secure connection between your computer and internet.

VPN creates a virtual tunnel between your computer and internet or external server where you request info from.

Selenium tutorials

Selenium # Selenium Implicit and Explicit wait

//Implicit Wait
// Explicit wait
WebDriverWait wait = new

Selenium # Selenium Keyboard and Mouse events
keyDown(); keyUp(); sendKeys();doubleClick();

Code Example:
Actions builder = new Actions(driver);
Action actions = builder
.keyDown(“logintextbox”, Keys.SHIFT)
.sendKeys(“logintextbox”, “hello”)
.keyUp(“logintextbox”, Keys.SHIFT)
actions.perform() ;

What is Cucumber BDD for Selnium tests

Cucumber BDD (Behaviourdriven development):Cucumber is a testing toolused for Software testingwith behaviour drivendevelopment approach.Cucucmber BDD comes with feature file, whereacceptance, functional,regression tests are written in plain english called Gherkin language…Sample feature file inGherkin language is like below:

Feature: my app login test

Scenario: positve test on login

Given user enters correct credentials

Then user should be able to login

Scenario: login negative test

Given user enters wrong password

Then login is not allowed

in the above feature file,each line below to

Scenario, i. e Given, Then steps are mapped with java methods to perform selenium Automation tests

What is TestRunner in Cucumber:

TestRunner is a programused in Cucumber toaccess Feature fileTestRunner drives theselenium automationfeatures executionFeature file is somethingthat has user requirementscenarios written in Englishwhich gives more readabilityand understandability ofthe requirement which iscalled Gherkin language#shorts

Unit testing mocks, stubs

Mocks replaces external Interface. Mocks are not to check thereturn value but to verify function level call happened,called correctly etc.Stubs are replacement ofreturn value and is to test behavior of code.Stubs generates the pre defined output fakes to replace actual implemention like to replaceweb server with local httpserver or replace db serverwith fake in memory db to generate db response

TestNG Parameterization:

Approach 1: feed input parameters via TestNGand receive using@Parameters annotation at the target method

Approach 2: use Dataprovider when complex parameters like data from database, xls,property file, arraylist etc

What is Single slash ‘/’in Xpath in selenium:

Single slash ‘/’ is usedwhen absolute Xpathis considered for Elementidentification for SeleniumWebDriver

What is Double slash ‘//’in Xpath in selenium:

Double slash ‘//’ is usedwhen relative Xpathis considered for Element identification for SeleniumWebDriverRelative Xpath ‘//’is better Element identification strategy

What is Polymorphism:
Polymorphism is one
of the OOPs concepts
where many forms or
characteristics shown
by single  java  method

Different types of
Polymorphism are,

1. compile time/static
2. Runtime/Dynamic

1. Compile time/static
Polymorphism is
achieved by Method
2. Runtime/Dynamic
Polymorphism is
achieved by Method

Method overloading
is feature where
many methods having
same name but different
argument types
Method overriding is
a feature where child
class method override the
parent class method


Interface is like
class having variables
and methods but methods
are abstract by default.

abstract methods mean
no body/implementation

Any class can
implement Interface and
achieve abstraction and
multiple inheritance

#encapsulation#java#selenium#OOPS is binding of data or variableswith code/methodsas a sigle unit from classthis helps hiding datafrom other classes whendata is declared as private.and keeping methods/codeas public, other class canget data.

#shorts#Abstractclass#cpncreatclassAbstract class:a class declaredusing abstract keywordand has abstract methodsAbstract methodsdoes not haveimplementationor bodyConcreat class:Concreat class extendsAbstract class and implements the methodsfrom Super Abstract classConcreta class does notuse Abstract keywordSelenium classes:Selenium classesextends Concreatclass and instantiateConcreat class touse the implementedmethods from Concreat class

Selenium: Handling Captcha using Sikuli

Purpose of Captcha
is to avoid Automation.

However some level
of Captcha automation
can be done using Sikuli

Sikuli can capture
image captcha having
numbers or letters
as contents and store
as string values
to continue Automation

Sikuli is a library
that works based
on image recognition

Sikuli can read text from
image and that can be
used for some level of
captcha Automation



Dynamic Objects
are those it’s id or
other properties
are changing
during page load
or other
user actions

How to handle
dynamic objects:

1. use XPath axes
methods :
use child, parent, sibling
elements to write Xpath

2. use dynamic Xpath
having “contains,
or starts with
or  ends with  etc

What is SelectorsHub?

It is a Browser extension
helps to auto suggest
XPath or CSS Selector

How to setup SelectorsHub

1. download and install from
for browser type
chrome, opera, edge, firefox

2. after adding extention to
browser, it will appear
as browser toolbar item

3. after restarting
browser  inspect any
SelectorHub will be
displayed on Elements
tab on right

4. start typing XPath or
CSS Selector, you
would notice SelectorsHub
auto suggesting
Xpath or CSS Selector

Ref :

#shortsSwitch to Frame:driver.switchTo().frame(“frame name/frame index”);Switch backfrom Frame:driver.switchTo().defaultContent();note: commandsare single line

Selenium Locators :

WebDriver Exceptions :

         3. NoAlertPresent
        4. Nosuchwindow
         5. NoSuchElement


1. XPath(XML Path)
is used to find element
2. XPath is the locator
type used in Selenium
3. High success rate
in finding elemet
4. Xpath is slower in IE

CSS(Cascading Style
Sheet )
1. CSS Selector, a
selenium locator type,
used to find
elements using style
2. Faster in all
Browsers but may not
work on certain browser

1. W3C standard protocol
is used by Selenium 4
WebDriver to
to Browser, which makes
and no API encoding
/decoding required

2. Logging and tracing are
improved for better
3. Better documentation on
selenium features
4. enabled two url
opening on two browser

5. Relative Locators
like. toRightOf(),
above(), near()
6.Opera and
PhantomJs support
are removed

7. Optimized
by fixing open issues

for chrome:
DesiredCapabilities caps = new DesiredCapabilities();

caps.setCapability(“browserName”, “chrome”);
caps.setCapability(“browserVersion”, “80.0””);
caps.setCapability(“platformName”, “win10”);

WebDriver driver = new ChromeDriver(caps);
// Pass the capabilities
as an argument to driver object

for Firefox:
DesiredCapabilities caps = new DesiredCapabilities();

caps.setCapability(“browserName”, “chrome”);
caps.setCapability(“browserVersion”, “80.0””);
caps.setCapability(“platformName”, “win10”);

WebDriver driver = new FirefoxDriver(caps);
// Pass the capabilities
as an argument to driver object

DesiredCapabilities caps = new DesiredCapabilities();

caps.setCapability(“browserName”, “chrome”);
caps.setCapability(“browserVersion”, “80.0””);
caps.setCapability(“platformName”, “win10”);

WebDriver driver = new ChromeDriver(caps);
// Pass the capabilities
as an argument to driver object

#shorts// to retrieve the current URL of the webpagegetCurrentUrl() // to retrieve the current page source of the webpagegetPageSource() //to retrieve the text of the specified web elementgetText() //to retrieve the value specified in the attributegetAttribute() //to retrieve the current title of the webpagegetTitle()getCurrentUrl() getPageSource() getText()getAttribute() getTitle()

Driver will switch to specific
frame using
Name or ID or index
(“frameName value”)

.frame(“ID value”)


Fluent Wait in Selenium is used for defining the maximum time for the webdriver to wait for a condition, and also the frequency with which we want to check the condition before throwing Exception

Handle multiple Browser windows and tabs

//to retrieve the handle of the current page

getWindowHandles() vs getWindowHandle()

driver.close(); // closes the current browser window
driver.quit(); //This method Closes all browser windows opened by the WebDriver

Python short videos for interview preparations

Python #2 handling file not found error

Python # 15 Lambda function in Python 3 onwards

Python #7 Exceptions | AttributeError — happens when an attribute reference or assignment fails

Paython #8 Exception |IOError — happens when I/O operation open() function fails like file not found

Python #9 Exception | ImportError happens when import statement cannot locate the module definition

Python # 10 Exception | IndexError  happens when a sequence subscript is out of range

Python #11 Exception KeyError :happens when a dictionary key isn’t found in the set it existing keys

Python # 12 Exception | NameError happens when a local or global name can’t be found

Python # 14 Nested If statements to check multiple conditions

Python # 16 How to find highest value in an array

Python #13 What is if __name__ == “__main__”: in python

Python # 6 if elif else condtion code example for python | code logic

Python #5 How to define own function code example | python automation | programming

Python #4 argparse standard library for taking commandline arguments into python program

Python #1 for looping  | Python programming

Python #3 logging usage | import logging

Python # 19 Python 3.9 features | new features in Python 3.9

DevOps tool chain and important tools and frameworks

  1. Source code management:
    GitHub, BitBucket, GitLab
  2. Programming Languages:
    Java, Python,JavaScript,
  3. Build management tools:
    Gradle, Maven, Ant
  4. Configuration management:
    Ansible, Chef, Puppet,
    Salt Stack
  5. Container:
    Docker, LXC, RKT
  6. Container orchastrators:
    Kubernetes, Docker swarm,
    Openshift, NoMad
  7. Infrastructure Provisioning:
    Terraform, Azure template,
    AWS cloud formation,
    Google Deployment Manager
  8. Monitoring :
    DataDog, Grafana, Zabbix,
    Prometheus, Checkmk,
    New Relic
  9. Logging:
    Splunk, ELK, Graylog
  10. Clouds:
    Azure, AWS, GCP, OpenStack ,
    IBM Bluemix, Alicloud
  11. CI/CD:
    Jenkins, Travis CI, Circle CI
    TeamCity, AWS CodePipeline,
    Google Cloudbuild, Gitlab CI
    Bitbucket pipeline, Github action
  12. Web Server:
    Apache, Nginx, IIS,
    Jetty, Tomcat
  13. Caching Server:
    MemCache, Redis
  14. NoSQL Database:
    MongoDB, Cassandra,
    Google datastore,
    AWS Dynamo db
  15. SQL Database:
    Oracle, MySQL, MsSQL

Kubernetes concepts, cluster, nodes, docker container, image, Dockerfile

Kubernetes concepts to remember:

1. Kubernetes Cluster: combination of large number of node machines

2. node machines:where Kubernetes software is installed and docker containers are hosted

3. docker container:each node machines contain large number of docker containers

4. docker image:Docker instructions are build and stored as image

5.Dockerfile:Docker instructions are written in markup language and stored in Dockerfile

Docker more info:

  1. Docker image can be run in terminal interactive mode while container started.
  2. While running in the terminal interactive mode, any program runtime, or filesystem can be added to the live container.
  3. A commit on container can create another fresh image.
    4.Fresh image from container can be tagged for easy use.
  4. Now the fresh image will have ubundu and the additional file system, runtime(like Java runtime) associated.

Git basic concepts to remeber

Git basic concepts
to remeber:

  1. working directory:
    this is local folder where
    coding is done using IDE
  2. staging area:
    git add command move
    code from working directory (1)
    to staging area
  3. local repository:
    git commit command will move
    code to local repo with a commit id
  4. remote repository :
    During git push code will get moved to remote repo that will be git/bitbucket

git fetch will move remote
repo commits to local repo

git merge moves code from local
repo to working directory