Wednesday, September 30, 2020

String

 Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

Cognizant Interview Questions


Core Java

1.Array and Array list

2.Arraylist and hash map predefined methods

3.Overloading and Overriding

4.Interface and abstract class

5.Access Modifiers

6.List and Map

Selenium

1.Implcit wait and explicit wait

2.Hadling popup windows

3.Handling alerts

4.selecting the dates in calendar

5.upload and download the files .

6.TestNG annotations

7.different locators

8.frame work flow

9.Reading the data from excel


https://www.softwaretestingo.com/cts-cognizant-interview-questions/

https://www.hackerrank.com/

https://testrigor.com/

==================================================================================

RERUN FAILED TEST CASES


This will run all your tests and then list all failed scenarios in rerun.txt file.


@RunWith(Cucumber.class)

@CucumberOptions(feature={“classpath:feature”}, 

glue{“path to stepdefs”},

plugin = {“rerun:target/rerun.txt” })

public class CukesRunner {}




Create another runner class.

Next step is to create a new runner class to run failed scenarios.


@RunWith(Cucumber.class)


@CucumberOptions(features = “@target/rerun.txt”,

plugin = {“rerun:target/rerun.txt”})


public class FailedRunner {}


Add maven surefire plugin to your pom.xml

*******************************************************************

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-surefire-plugin</artifactId>

<version>2.19.1</version>

<configuration>

<includes>

<include>**/*Runner.java</include>

</includes>

</configuration>

</plugin>


Running Tests

In order to use rerun option you need to execute maven goals from terminal, open the terminal and go to the folder where your pom.xml is located and then run “mvn clean test”

$mvn clean test

==================================================================================


Reflection in Java

Reflection is an API which is used to examine or modify the behavior of methods, classes, interfaces at runtime.


The required classes for reflection are provided under java.lang.reflect package.

Reflection gives us information about the class to which an object belongs and also the methods of that class

which can be executed by using the object.

Through reflection we can invoke methods at runtime irrespective of the access specifier used with them.


Reflection can be used to get information about –


Class: The getClass() method is used to get the name of the class to which an object belongs.


Constructors: The getConstructors() method is used to get the public constructors of the class to which an object belongs.


Methods: The getMethods() method is used to get the public methods of the class to which an objects belongs.

import java.lang.reflect.Method; 

import java.lang.reflect.Field; 

import java.lang.reflect.Constructor; 

  

// class whose object is to be created 

class Test 

    // creating a private field 

    private String s; 

  

    // creating a public constructor 

    public Test()  {  s = "GeeksforGeeks"; } 

  

    // Creating a public method with no arguments 

    public void method1()  { 

        System.out.println("The string is " + s); 

    } 

  

    // Creating a public method with int as argument 

    public void method2(int n)  { 

        System.out.println("The number is " + n); 

    } 

  

    // creating a private method 

    private void method3() { 

        System.out.println("Private method invoked"); 

    } 

  

class Demo 

    public static void main(String args[]) throws Exception 

    { 

        // Creating object whose property is to be checked 

        Test obj = new Test(); 

  

        // Creating class object from the object using 

        // getclass method 

        Class cls = obj.getClass(); 

        System.out.println("The name of class is " + 

                            cls.getName()); 

  

        // Getting the constructor of the class through the 

        // object of the class 

        Constructor constructor = cls.getConstructor(); 

        System.out.println("The name of constructor is " + 

                            constructor.getName()); 

  

        System.out.println("The public methods of class are : "); 

  

        // Getting methods of the class through the object 

        // of the class by using getMethods 

        Method[] methods = cls.getMethods(); 

  

        // Printing method names 

        for (Method method:methods) 

            System.out.println(method.getName()); 

  

        // creates object of desired method by providing the 

        // method name and parameter class as arguments to 

        // the getDeclaredMethod 

        Method methodcall1 = cls.getDeclaredMethod("method2", 

                                                 int.class); 

  

        // invokes the method at runtime 

        methodcall1.invoke(obj, 19); 

  

        // creates object of the desired field by providing 

        // the name of field as argument to the  

        // getDeclaredField method 

        Field field = cls.getDeclaredField("s"); 

  

        // allows the object to access the field irrespective 

        // of the access specifier used with the field 

        field.setAccessible(true); 

  

        // takes object and the new value to be assigned 

        // to the field as arguments 

        field.set(obj, "JAVA"); 

  

        // Creates object of desired method by providing the 

        // method name as argument to the getDeclaredMethod 

        Method methodcall2 = cls.getDeclaredMethod("method1"); 

  

        // invokes the method at runtime 

        methodcall2.invoke(obj); 

  

        // Creates object of the desired method by providing 

        // the name of method as argument to the  

        // getDeclaredMethod method 

        Method methodcall3 = cls.getDeclaredMethod("method3"); 

  

        // allows the object to access the method irrespective  

        // of the access specifier used with the method 

        methodcall3.setAccessible(true); 

  

        // invokes the method at runtime 

        methodcall3.invoke(obj); 

    } 

Output :


The name of class is Test

The name of constructor is Test

The public methods of class are : 

method2

method1

wait

wait

wait

equals

toString

hashCode

getClass

notify

notifyAll

The number is 19

The string is JAVA

Private method invoked


========================================================================================================================


CONTRUCTOR CHANING:

URL: https://dzone.com/articles/constructor-chaining-in-java


Calling a constructor from the another constructor of same class is known as Constructor chaining. The real purpose of Constructor Chaining is that you can pass parameters through a bunch of different constructors, but only have the initialization done in a single place.


How Does Constructor Chaining Work?

When you invoke a constructor from another constructor, it's called constructor chaining. Whether you're dealing with a standalone constructor or a parent class' constructor, the end of the chain will always be the Object's class constructor because every class is inherited from the Object class by default.


So lets' look at the below scenario to understand it better:


class Parent {

    public void Parent() {

        System.out.println("inside parent without arguments");

    }

    public Parent(int a) {

        System.out.println("inside parent with argument");

    }

}

class Child extends Parent {

    public void Child() {

        System.out.println("inside child without arguments");

    }

    public Child(int b) {

        System.out.println("inside child with argument");

    }

    public static void main(String[] args) {

        Child child = new Child();

        Child child1 = new Child(15);

    }

}



So what should the output be? It will give a compilation error. 


1. Line 18 will give a compilation error saying that there is no default constructor in the Parent class. Huh?


Doesn't the compiler add a default constructor by itself? No.


Let's understand what the compiler is trying to do here: 


The compiler doesn't add a default constructor (no args) if you have already defined a constructor with arguments. 


The compiler tries to add a super() call as the first call in the constructor if you don't add it yourself.


2. Line 23 will give compiler error because there is no default constructor defined in Child.


So how can we fix it?


1. We can fix line 18 in the following two ways:


Add a super(b), super call with an argument to the Parent class in the constructor of the Child class.


Add a default constructor in the Parent class.


2. We can fix line 23 by adding a default constructor in the Child class:


class Parent {

    // this is method not a constructor

    public void Parent() {

        System.out.println("inside parent without arguments");

    }

    // this is default constructor.

    public Parent() {

        super(); // hidden call to Object's default constructor

        System.out.println("inside parent's default constructor");

    }

    public Parent(int a) {

        super(); // hidden call to Object's default constructor

        System.out.println("inside parent's argument constructor");

    }

}

class Child extends Parent {

    // this is a method

    public void Child() {

        System.out.println("inside child without arguments");

    }

    // this is a default constructor

    public Child() {

        super(); // hidden call to Parent's default constructor

        System.out.println("inside child's default constructor");

    }

    public Child(int b) {

        super(b); // Case - 1 : call to Parent's argument constructor

        System.out.println("inside child's argument constructor");

    }

    public static void main(String[] args) {

        Child child = new Child();

        Child child1 = new Child(15);

    }

}



Output : 


inside parents's default constructor

inside child's default constructor

inside parent's argument constructor

inside child's argument constructor



What Is this() Used For?

If you need to call the same class' constructor, then you can use this() as the first statement of the constructor. It can be with or without arguments based on which constructor you want to invoke.


class Child extends Parent {

    // this is a method

    public void Child() {

        System.out.println("inside child without arguments");

    }

    // this is a default constructor

    public Child() {

        this(); //can we call this here?                         // 9 number line

        System.out.println("inside child's default constructor");

    }

    public Child(int b) {

        this(); // invoke default constructor of Child class  // 14 line

        System.out.println("inside child's argument constructor");

    }

    public static void main(String[] args) {

        Child child = new Child(15);

    }

}



Output: 


Line 9, will give a compilation error. It is a recursive call to the default constructor. However, it is legitimate to call it on line 14 because it is being called from an argument constructor. If we remove line 9, then the output will be :



inside parent's default constructor 

(the compiler will add a call to super() in the default constructor of the Child class, which will invoke Parent's default constructor)

inside child's default constructor

inside child's argument constructor


================================================================================================================

pom.xml

URL: https://stackoverflow.com/questions/29614934/what-happens-when-i-add-a-maven-dependency



In general in all pom.xml we found dependency like this -


<dependency>

    <groupId>org.apache.commons</groupId>

    <artifactId>commons-lang3</artifactId>

    <version>3.4</version>

</dependency>

Here groupId, artifactId and version are 3 keys by which a jar is uniquely identified. These 3 combination works like a coordinate system for uniquely identifying a point in a space using x, y and z coordinates.


Whenever you issue a mvn package command maven tries to add the the jar file indicating by the dependency to you build path. For doing this maven follows these steps -


Maven search in your local repository (default is ~/.m2 for linux). If the dependency/jar is found here then it add the jar file to you build path. After that it uses required class file from the jar for compilation.


If the dependency is not found in ~/.m2 then it looks for your local private repository (If you already have configured any using setting.xml file) and maven central remote repository respectively. If you don't have any local private repository then it directly goes to the maven central remote repository.


Whenever the jar is found in the local/remote repository it is downloaded and saved in ~/.m2.


Going forward, when you again issue a mvn package command then it's never search for the dependency to any repository since it already in your ~/.m2.

================================================================================================================

Exception 

Synchronize

Thread

List and ArrayList

Collection and ArrayList

Hashmap and hashTable

Hashmap and HashSet

how to run specific method from xml in testNG

Reverse String without split method

DB connection

What challeges faced in FW 

What pom.xml dependacies works and from where its getting.

========================================================================================================================

Roles and Responsibilities?

Roles and Responsibilities of Manual Test Engineer: 


Understanding the Software Requirements specification document.

After learning how the end user will use the appliance with the flow.

Make test cases with user stories or test scenarios.

Perform test case execution with scenarios.

If the defect is found, then report it to the developer and fix it.

Where fault is found, re-test there.

Make sure the application is the free defect.

Send the test report to test lead.

 


Roles and Responsibilities of Automation Test Engineer:

Selection or identification of test cases for automation from existing test case documentation.

Applying Designing and Test Automation Strategy Document

Creating an automation test plan and getting approval.

Configure Selenium Test Environment for setup(ex: Java, Selenium WebDriver and TestNG etc.).

Participation in Selenium Environmental Setup with IDE.

Automation framework design and implementation according to project structure.

Creating, Enhancing, Debugging and Running Test Cases.

Organizing, monitoring defect management process Handling changes and conducting regression tests.

Find solutions for issues related to object identity issues and error handling.

Coordination of the members of the Test team and the development team to solve the issues.

Interaction with the people of the client side to solve problems and update the situation.

Create a software defect tracking report entire project release status to stakeholders.

Roles and Responsibilities of API Automation test Engineer:

Must be able to use all web methods like GET, PUT, POST, DELETE etc.

Validate feedback, response time, error code.

Able to validate xml and json body using json parser.

Know how to use the OAuth and OAuth2 authentication mechanisms.

Able to Load and Security testing on web services.

Able to read and understand API documents.

Able to get a good number of test cases and scenarios.

To validate API and DB data elements, SQL queries should be good.

 


Roles and Responsibilities of Performance test Engineer:

Conduct performance system testing to verify system scalability, efficiency and reliability.

Coordinate with the testing team to develop performance test plans and cases.

Analyze the test results and coordinate with the development teams for bug fixes.

Create a test summary report for management review.

Analyze the underlying causes of performance issues and provide corrective action.

Organize job training and provide assistance to junior test engineers as needed.

Suggest new tools and techniques to improve test efficiency.

Help in project planning, scheduling, budget and tracking activities.

Provide assistance in project design, development and deployment activities.

Develop an automated test scenario and environment for performance testing.

Review and recommend improvements in existing test procedures.



The role of Test Automation Engineer (Test Engineer) is to design, create, test and deploy effective test automation solutions for software.


In order to fulfill this role, automation engineer implements the appropriate automation techniques to meet the short and long-term goals of the testing organization with accuracy.


With the minimum set of objective codes / scripts, automate the testing effort as much as possible within minimum amount of time.


The test of coverage should be kept in mind without testing the test.


For example, if the preparation process for the manual test case or manual test consumes large scale testing resources, then this manual process should be automated first on priority.

======================================================================================================================== 

What is your Job?


======================================================================================================================== 

What Challeges you faced till date as an Automation Tester ??

URL: https://www.nexsoftsys.com/articles/9-challenges-selenium-test-automation.html

Selenium is a widely used portable framework for web automation testing supported with multiple languages like Java, Python, JavaScript, C#, etc. Like other frameworks and tools, Selenium also has its pros and cons. being selenium automated testing service provider, we have personally faced a fair number of challenges in our test automation projects, which we would like to share in this blog.


Selenium Automation 

1) Cross Browser Testing


Selenium Automation

Sometimes our web application may not response the same in different browsers, and there might be a possibility that our website works fine on Chrome but not on Firefox. Since there are plenty of browsers in the market nowadays, performing test automation on every browser might not be possible. However, we still need to check if the application under test is fully compatible with most used browsers such as Chrome, Firefox, Safari, Edge, and IE. Testing on widely used browsers is still not enough, and we may need to test on widely used versions of these browsers along with different operating systems and resolutions. This strategy sums up to Cross Browser Testing and makes test automation challenging for testers.


 

2) Scalability


Selenium Automation

The major challenge faced in automation is test scalability. As discussed in the previous point, running tests on different browsers, OS and resolutions is something significant to perform. Selenium WebDriver provides us a way for running tests sequentially and doesn’t offer an effective way to perform Cross Browser Testing. An application under test may grow concerning multiple features with time, which would lead to more test cases, and running multiple test cases sequentially might become a hassle.


To overcome this, Selenium has overcome with Selenium Grid, where we can test our web application on multiple combinations of browsers and OS. However, Selenium Grid would only help perform Cross Browser Testing on the physical machines or browsers that we have, hence running automation tests on the scale becomes challenging for testers.


 

3) Synchronizing Events


Selenium Automation

Sync issues are one of the primary reasons for our automation script failure. The sync issues may arise when we expect some event to occur. However, it might get delayed or might not happen due to some unknown reason, which further causes our test case to fail. For example, when we are running an automation script, just after launching the website, we expect a “accept/decline cookies” prompt to come up, but due to some reason, it got delayed, or it didn’t even occur. This type of synchronization becomes the reason for our test script failure.


To handle this, we generally use waits defined in Selenium like Implicit wait and Explicit wait.


 

4) Handling Dynamic Elements


New websites developed using high technologies might have dynamic content that changes over time. Even the sites that are accessible globally might contain content based on geo-locations.


For example, Amazon is an e-commerce application whose catalog changes overtime and reacts differently with different content in different regions. Automating such web applications becomes challenging with Selenium since the locators that we have used might fail to interact with the web elements. Web content based on AJAX sometimes takes time to load, which also becomes a possible reason for test script failure. As mentioned previously, we have waits integrated with Selenium like Implicit wait and Explicit wait, which can be helpful in such cases. We can even create dynamic or custom XPath for handling dynamic web content.


 

5) False Positive and False Negative Results


False Positive and False Negative results have always been a nightmare for automation testers. False Positive refers to the scenario where we get errors in our test cases even though the application under test works fine. Vice Versa, false-negative results refer to the situation where we get passing results for our test cases; yet the application under test has bugs. Such flakiness misleads the testing team and increases the communication gap between the QA team and the development team. Handling flaky tests is itself a challenging task for automation testers.


To overcome this flakiness, we need to make sure that the test plans, test cases, and the testing environment are managed in an appropriate and organized manner.


 

6) Pop up and Alert Handling


Selenium Automation

Different types of popup and alerts occur while interacting with a web application, below are few listed:


Browser level notification: Examples of such notifications can be; “Allow/Decline camera access,” “Allow/Decline microphone access,” etc. These are browser level notifications that are handled in different ways depending upon the browsers. For the Chrome browser, ChromeOptions can be used. Similarly, for the Firefox browser, FirefoxOptions/FirefoxProfile can be used.


 

Web-based alerts: Examples of such notifications can be; “This site says….”, “Do you want to leave this site” etc. These are the alerts that can be handled using Selenium predefined class “Alerts,” which provide various methods like accept(), dismiss(), etc.


 

OS level pop-ups: Selenium capabilities are only bounded with web interaction; hence, handling OS level interactions is something that can’t be performed using Selenium. These types of pop-ups can be categorized as flash objects which can’t be accessed using Selenium Locators. “Robot” class is commonly used for interaction with such pop-ups.


 

7) Captcha or OTP Handling


Selenium Automation

As we know, Captcha and OTP cannot be assumed or predicted as its values are different every time it is generated. Automating features like payment gateway, new account registration, etc. where Captcha and OTP is required, becomes challenging for automation testers. This can also be considered as a proof that an application cannot be 100% automated and manual testing cannot be avoided.


 

8) Limited Reporting


Reporting plays a vital role in the testing phase. Tests reports act as a bridge between developers and testers. As of now, Selenium doesn’t provide much reporting capabilities.


Generating and maintaining reports is the critical challenge faced by automation testers.


We generally use programming language based frameworks for our better code designs and reporting. Examples of Java frameworks that provide useful reports are TestNG, Gauge. Similarly, the Pytest framework can be considered for Python.


 

9) Restricted to only Desktop Browsers Testing


Selenium Automation

Nobody can deny the fact that Selenium is a widely used portable framework for testing web applications. However, it doesn't provide support for testing native mobile applications or mobile web applications. For this, we have another open-source framework, "Appium," a.k.a cousin of Selenium. Appium is itself a widely used framework for testing of iOS and Android mobile apps and web apps. Here the challenging part for automation testers is that they have to create different drivers and scripts for testing a single web application in the same browser of desktop and mobile while working in a software testing company.


Friday, September 4, 2020

Framework Structure

 1. Junit+TestNG+Cucumber (Act as a base FW) = Hybrid FW

All Dependancies in pom.xml


Junit Annotations 

@Before

@Test

@After

@Runwith

Junits gives marking with the help of annotation. Its tell its Test Method, Its Prerequisites.

Junit gives execution flow and what will be executed After and Before.



KISS - Keep it simple, Stupid its Design Principle.

When you start to implement FW Development from the Scratch  in that case in early phase FW development is fast and Test case implementation is slow till proper FW not done. 

Plugin

use to execute TC

maven-surefire Plugin add in to POM.xml


Run from command line:

1. make sure your on root Folder, where all file src, pom, target (use command for it- ls)

$ ls

2. mvn clean install (It compile the code and start running TCs)

$ mvn clean install

3. git status 

4. git add . && git commit -m"mistake corrected" && git push origin branch name 

if what to update any changes in branch use above command

if we run 

mvn clean install -Dbrowser=chrome

mvn clean install -Dbrowser=firefox

-Dbrowser - its command for virtual machine to create variable and get browser which set in Test base class file.

String browsersentfromcmnd = System.getProperty("browser");









Tuesday, March 31, 2020

Interview Questions

What is Session Time?
Specifies the number of minutes that a session can remain idle before the server terminates it automatically. The default is 10 minutes. SessionTimeout has no hard-coded limit. ... It should not be set higher than 20 minutes (except in special cases) because every open session is holding onto memory
Tracking session expiration in browser
<session-config>
  <session-timeout>10</session-timeout>
 </session-config>
what is authentication and what is authorization
Authentication vs Authorization. ... Authentication means confirming your own identity, whereas authorization means being allowed access to the system. In even more simpler terms authentication is the process of verifying oneself, while authorization is the process of verifying what you have access to
- what is difference between scrum and Agile
Agile
Scrum
Agile is a development methodology based on iterative and incremental approach.Scrum is one of the implementations of agile methodology. In which incremental builds are delivered to the customer in every two to three weeks' time.
Agile software development has been widely seen as highly suited to environments which have small but expert project development teamScrum is ideally used in the project where the requirement is rapidly changing.
In the Agile process, the leadership plays a vital role.Scrum fosters a self-organizing, cross-functional team.
Compared to Scrum it is a more rigid method. So there is not much room for frequent changes.The biggest advantage of Scrum is its flexibility as it quickly reacts to changes.
Agile involves collaborations and face-to-face interactions between the members of various cross-functional teams.In Scrum, collaboration is achieved in daily stand up meeting with a fixed role assigned to scrum master, product owner, and team members.
Agile can require lots of up-front development process and organizational change.Not too many changes needed while implementing scrum process.
The agile method needs frequent delivery to the end user for their feedback.In the scrum, after each sprint, a build is delivered to the client for their feedback.
In this method, each step of development like requirements, analysis, design, are continually monitored during the lifecycle.A demonstration of the functionality is provided at the end of every sprint. So that regular feedback can be taken before next sprint.
Project head takes cares of all the tasks in the agile method.There is no team leader, so the entire team addresses the issues or problems.
The Agile method encourages feedback during the process from the end user. In this way, the end product will be more useful.Daily sprint meeting is conducted to review and feedback to decide future progress of the project.
Deliver and update the software on a regular basis.When the team is done with the current sprint activities, the next sprint can be planned.
Design and execution should be kept simple.Design and execution can be innovative and experimental.
In the Agile method, the priority is always to satisfy the customer by providing continuous delivery of valuable software.Empirical Process Control is a core philosophy of Scrum based process.
Working software is the most elementary measure of progress.Working software is not an elementary measure.
It is best to have face-to-face communication, and techniques like these should be used to get as close to this goal as possible.Scrum team focus to deliver maximum business value, from beginning early in the project and continuing throughout.
Following are Agile principles:
-Welcome changing requirements, even late in development. Agile processes allow change according to customer's competitive advantage.
-Business people and developers will work daily throughout the project.
-Attention to technical excellence and right design enhances agility
-Agile team, work on to become more effective, for that they adjust its behavior according to the project.
Following are scrum principles:
-Self-organization: This results in healthier shared ownership among the team members. It is also an innovative and creative environment which is conducive to growth.
-Collaboration: Collaboration is another essential principle which focuses collaborative work. 1. awareness 2. articulation, and 3. appropriation. It also considers project management as a shared value-creation process with teams working together to offer the highest value.
-Time-boxing: This principle defines how time is a limiting constraint in Scrum method. An important element of time-boxed elements are Daily Sprint planning and Review Meetings.
-Iterative Development: This principle emphasizes how to manage changes better and build products which satisfy customer needs. It also defines the organization's responsibilities regarding iterative development.

Wednesday, March 25, 2020

How To Find Broken Links Using Selenium WebDriver

Find Broken Links Using Selenium WebDriver:

One of the key test case is to find broken links on a webpage. Due to existence of broken links, your website reputation gets damaged and there will be a negative impact on your business. It’s mandatory to find and fix all the broken links before release. If a link is not working, we face a message as 404 Page Not Found.
Let’s see some of the HTTP status codes.
200 – Valid Link
404 – Link not found
400 – Bad request
401 – Unauthorized
500 – Internal Error
Consider a test case to test all the links in the home page of “SoftwareTestingMateria.com”
Below code fetches all the links of a given website (i.e., SoftwareTestingMateria.com) using WebDriver commands and reads the status of each href link with the help of HttpURLConnection class.
Click here for more information on HttpURLConnection
Given clear explanation in the comments section with in the program itself. Please go through it to understand the flow.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package softwareTestingMaterial;
 
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class BrokenLinks {
public static void main(String[] args) throws InterruptedException {
//Instantiating FirefoxDriver
System.setProperty("webdriver.gecko.driver", "D:\\Selenium Environment\\Drivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//Maximize the browser
driver.manage().window().maximize();
//Implicit wait for 10 seconds
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//To launch softwaretestingmateria.com
driver.get("https://www.softwaretestingmaterial.com");
//Wait for 5 seconds
Thread.sleep(5000);
//Used tagName method to collect the list of items with tagName "a"
//findElements - to find all the elements with in the current page. It returns a list of all webelements or an empty list if nothing matches
List<WebElement> links = driver.findElements(By.tagName("a"));
//To print the total number of links
System.out.println("Total links are "+links.size());
//used for loop to
for(int i=0; i<links.size(); i++) {
WebElement element = links.get(i);
//By using "href" attribute, we could get the url of the requried link
String url=element.getAttribute("href");
//calling verifyLink() method here. Passing the parameter as url which we collected in the above link
//See the detailed functionality of the verifyLink(url) method below
verifyLink(url);
}
}
// The below function verifyLink(String urlLink) verifies any broken links and return the server status.
public static void verifyLink(String urlLink) {
        //Sometimes we may face exception "java.net.MalformedURLException". Keep the code in try catch block to continue the broken link analysis
        try {
//Use URL Class - Create object of the URL Class and pass the urlLink as parameter
URL link = new URL(urlLink);
// Create a connection using URL object (i.e., link)
HttpURLConnection httpConn =(HttpURLConnection)link.openConnection();
//Set the timeout for 2 seconds
httpConn.setConnectTimeout(2000);
//connect using connect method
httpConn.connect();
//use getResponseCode() to get the response code.
if(httpConn.getResponseCode()== 200) {
System.out.println(urlLink+" - "+httpConn.getResponseMessage());
}
if(httpConn.getResponseCode()== 404) {
System.out.println(urlLink+" - "+httpConn.getResponseMessage());
}
}
//getResponseCode method returns = IOException - if an error occurred connecting to the server.
catch (Exception e) {
//e.printStackTrace();
}
    }

String

  Java String  class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), re...