Table of contents
1.
Introduction
2.
Selenium with Java- What is it?
3.
Significant Parts of Selenium
4.
Java on Selenium?
5.
Example of a Simple Selenium + Java Program
6.
How does Selenium Work?
7.
Step-by-Step Flow
8.
Example: Logging into a Website
9.
What is the Reason to Choose Selenium and Java?
10.
Example: Using TestNG with Selenium Java
11.
Steps to Configure Java Environment
11.1.
1. Install Java (JDK)
11.2.
Verify installation by opening Command Prompt/Terminal
11.3.
2. Set JAVA_HOME Environment Variable
11.4.
3. Install Eclipse (or IntelliJ IDEA)
11.5.
4. Set Up Selenium WebDriver
11.6.
5. Download Browser Drivers
11.7.
Verify Your Setup
12.
Create a Selenium with Java Project in Eclipse
12.1.
1. Create a New Java Project
12.2.
2. Convert to Maven Project (Recommended)
12.3.
3. Add Selenium Dependencies
12.4.
4. Create Package Structure
12.5.
5. Add ChromeDriver
12.6.
6. Create Your First Test Class
12.7.
7. Run the Test
13.
Project Structure Should Look Like
14.
Steps for Writing Selenium Code in Java
14.1.
1. Basic Test Structure
14.2.
2. Locating Web Elements
14.3.
3. Common Interactions
14.4.
4. Complete Login Test Example
14.5.
5. Best Practices
14.6.
6. Running Tests
15.
Frequently Asked Questions
15.1.
What is Java application used at Selenium automation?
15.2.
What to do with slow-loading pages?
15.3.
Does Selenium support testing of mobile applications?
16.
Conclusion
Last Updated: Jun 22, 2025
Easy

Selenium with Java

Author Rahul Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Automated testing is an important aspect of software development, which will make sure that applications are functioning as expected prior to their delivery to the users. Selenium is a potent framework that can be utilized to automate web browsers so that testers can mimic user behavior, such as clicking buttons, filling forms, and traversing pages. Selenium is more effective in writing excellent test scripts when coupled with Java, one of the common and oft-used programming languages. 

Selenium with Java

In this article, we shall see what Selenium Java is, how it functions, why it is a desired choice, and how to configure it. We are also going to go about creating a project within Eclipse, and also some simple test scripts.

Selenium with Java- What is it?

Selenium is an open-source software that is free and automates web browsers. It allows you to create scripts that can open a browser, click buttons, type text, and verify whether web pages are functioning in a way a real user should.

Java, on the other hand, is a common programming language and is very stable and used in most program developments. By mixing Selenium with Java, we end up having an excellent solution to create automated tests on websites.

Significant Parts of Selenium

  • Selenium WebDriver - the principal tool by the help of which the browser is managed and through which the actions are undertaken (such as clicking, writing, etc.).
     
  • Selenium IDE is an easy record-and-playback mechanism to create tests in a hurry (no coding is required).
     
  • Selenium grid- The grid is employed in the running of tests on many machines and browsers simultaneously.

Java on Selenium?

  • Java does not require a particular platform (I can use it in Windows, Mac, Linux).
     
  • Good neighborhood and loads of libraries.
     
  • Integrates nicely with 1 frame testing e.g TestNG & JUnit.

Example of a Simple Selenium + Java Program

Let’s take a basic script that opens Chrome, goes to Google, and searches for "Selenium Java":

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;


public class FirstSeleniumTest {
    public static void main(String[] args) {
        // Set the path of ChromeDriver
        System.setProperty("webdriver.chrome.driver", "C:\\path\\to\\chromedriver.exe");
        
        // Initialize Chrome browser
        WebDriver driver = new ChromeDriver();
        
        // Open Google
        driver.get("https://www.google.com");
        
        // Find the search box and type "Selenium Java"
        WebElement searchBox = driver.findElement(By.name("q"));
        searchBox.sendKeys("Selenium Java");
        searchBox.submit();
        
        // Close the browser after 3 seconds
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        driver.quit();
    }
}
You can also try this code with Online Java Compiler
Run Code

 

In this Code: 

 

  • System.setProperty() – Tells Selenium where the ChromeDriver is located.
     
  • WebDriver driver = new ChromeDriver(); – Opens a new Chrome window.
     
  • driver.get("https://www.google.com"); – Navigates to Google.
     
  • driver.findElement() – Finds the search box using its HTML name (q).
     
  • sendKeys() – Types "Selenium Java" into the search box.
     
  • submit() – Presses the "Enter" key to search.
     
  • driver.quit(); – Closes the browser.

How does Selenium Work?

Selenium is a program that works like a web browser is controlled by a person: the browser does what the code tells it, as opposed to a user. The question is how it takes place, and we will talk about the way it happens:
 

  • Your Java Code: You use Java and Selenium WebDriver commands to write test scripts.
     
  • Browser Driver (e.g. chrome driver) - This is an interface between your code and the real browser.
     
  • Chrome, Firefox, etc. are browsers. The browser gets the orders through the driver and undertakes the activities.

Step-by-Step Flow

  • You would develop a Selenium script (as another example was the Google search).
     
  • When executing the script WebDriver opens the browser.
     
  • The script gives an instruction to the browser on what to perform (open a page, press a button, type text).
     
  • The browser gives a response (e.g. page loaded successfully).
     
  • There is also available the check that there are elements and compare the text, or provide the screenshots.

Example: Logging into a Website

Let’s automate logging into a demo site (like https://example.com/login):

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;


public class LoginTest {
    public static void main(String[] args) {
        // Set ChromeDriver path
        System.setProperty("webdriver.chrome.driver", "C:\\path\\to\\chromedriver.exe");
        
        // Open Chrome
        WebDriver driver = new ChromeDriver();
        
        // Go to login page
        driver.get("https://example.com/login");
        
        // Find username & password fields and enter data
        WebElement username = driver.findElement(By.id("username"));
        WebElement password = driver.findElement(By.id("password"));
        
        username.sendKeys("testuser");
        password.sendKeys("password123");
        
        // Click the login button
        WebElement loginButton = driver.findElement(By.id("login-btn"));
        loginButton.click();
        
        // Check if login was successful (verify page title)
        String pageTitle = driver.getTitle();
        if (pageTitle.equals("Welcome Page")) {
            System.out.println("Login Successful!");
        } else {
            System.out.println("Login Failed.");
        }
        
        // Close browser
        driver.quit();
    }
}
You can also try this code with Online Java Compiler
Run Code

In this script: 

  • The script opens Chrome and goes to a login page.
     
  • It finds the username & password fields using their HTML id.
     
  • It types the credentials and clicks the login button.
     
  • After login, it checks the page title to confirm success.

What is the Reason to Choose Selenium and Java?

In the case of automated testing, Selenium helps with numerous program languages such as Python, C# and JavaScript. Java however is one of the most popular ones. Here's why:

1. Good Community & Networking

Java is not new, and therefore there are multiple tons of tutorials, forums, and StackOverflow answers.

Java bindings of selenium are simple and supported properly.
 

2. Works dealing with Major Testing Frameworks

Java can be incorporated in:
 

  • JUnit (to structure the simple tests)
     
  • TestNG (more features, such as parallel testing)
     
  • Maven/Gradle (depeendency management)
     

3. Complex Tests: On challenging tests suites, Java is more efficient to work with, even though Python can be easier to learn. Its statical typing allows it to identify an error early.
 

4. Cross-Platform: Write once, execute everywhere - java can be used on Window, Mac and even Linux without rewriting.
 

5. Enterprise Adoption: Java is a useful skill in most large enterprises as far as automation of tests in the organizations goes.

Example: Using TestNG with Selenium Java

Let’s see how you'd set up a simple TestNG test case:

First, add TestNG to your Maven pom.xml:

xml
<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>7.4.0</version>
</dependency>
You can also try this code with Online Java Compiler
Run Code


Then write a test:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
import org.testng.Assert;

public class TestNGExample {
    @Test
    public void testPageTitle() {
        WebDriver driver = new ChromeDriver();
        driver.get("https://google.com");
        
        String expectedTitle = "Google";
        String actualTitle = driver.getTitle();
        
        Assert.assertEquals(actualTitle, expectedTitle);
        driver.quit();
    }
}
You can also try this code with Online Java Compiler
Run Code


When You Might Choose Something Else

  1. If you're testing a simple website and want fastest setup → Python
     
  2. If your team already uses C# → Selenium with C#
     
  3. For quick record/playback → Selenium IDE (no coding)

 

But for most professional test automation, Java with Selenium provides the best balance of power and reliability.

Steps to Configure Java Environment

Before writing Selenium tests in Java, you need to set up your development environment. Let’s see how to do it step by step:

1. Install Java (JDK)

First, you need Java installed on your computer:

  • Go to Oracle's JDK download page
     
  • Download the latest LTS version (Java 11 or 17 recommended)
     
  • Run the installer and follow the steps

Verify installation by opening Command Prompt/Terminal

java -version


You should see something like:

java version "17.0.1" 2021-10-19 LTS

2. Set JAVA_HOME Environment Variable

This helps your system find Java:

Windows:

 

  1. Search for "Environment Variables" in Start Menu
     
  2. Click "Environment Variables"
     
  3. Under System variables, click "New"
     
  4. Variable name: JAVA_HOME
     
  5. Variable value: Path to your JDK (e.g., C:\Program Files\Java\jdk-17.0.1)
     
  6. Click OK
     

Mac/Linux:

Add this to your ~/.bashrc or ~/.zshrc:

 

export JAVA_HOME=$(/usr/libexec/java_home)

3. Install Eclipse (or IntelliJ IDEA)

Download Eclipse IDE for Java Developers from eclipse.org:
 

  • Choose "Eclipse IDE for Java Developers"
     
  • Extract and run the installer
     
  • Select a workspace folder when prompted
     

4. Set Up Selenium WebDriver

There are two ways to add Selenium to your project:
 

Option 1: Using Maven (Recommended)
 

  1. In Eclipse, create a new Maven project
     
  2. Open pom.xml and add these dependencies:
xml
<dependencies>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>4.1.2</version>
    </dependency>
</dependencies>


Option 2: Manual JAR Files
 

  1. Download Selenium Java client from Selenium website
     
  2. Right-click project → Build Path → Add External JARs
     
  3. Select all downloaded JAR files

5. Download Browser Drivers

Each browser needs its own driver:
 

  • Chrome: ChromeDriver
     
  • Firefox: GeckoDriver
     

Important:
 

  • Place the driver executable in a known location
     
  • Add its path in your code (we'll show this in next section)

Verify Your Setup

Let's test everything works with a simple program:

public class EnvTest {
    public static void main(String[] args) {
        System.out.println("Java Version: " + System.getProperty("java.version"));
        System.out.println("Java Home: " + System.getProperty("java.home"));
    }
}


Run this in Eclipse. You should see your Java version printed.

Create a Selenium with Java Project in Eclipse

Now that your environment is ready, let's create your first Selenium project in Eclipse. This will be a step-by-step guide with everything you need.

1. Create a New Java Project

 

  1. Open Eclipse
     
  2. Click File → New → Java Project
     
  3. Enter project name (e.g., "FirstSeleniumProject")
     
  4. Make sure "Use project folder as root" is selected
     
  5. Click Finish

2. Convert to Maven Project (Recommended)

Right-click project → Configure → Convert to Maven Project
 

  • This creates a pom.xml file for managing dependencies

3. Add Selenium Dependencies

Open pom.xml and add these inside <dependencies>:

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>7.4.0</version>
    <scope>test</scope>
</dependency>


Save the file - Eclipse will automatically download the libraries.

4. Create Package Structure

  1. Right-click src/main/java
     
  2. New → Package
     
  3. Name it (e.g., "com.tests")

5. Add ChromeDriver

  1. Download ChromeDriver from here
     
  2. Create a drivers folder in your project
     
  3. Copy the ChromeDriver.exe there

6. Create Your First Test Class

Right-click your package → New → Class

Name it "FirstTest"
 

Let’s see a complete test example:

package com.tests;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;


public class FirstTest {
    
    @Test
    public void openGoogle() {
        // Set path to ChromeDriver
        System.setProperty("webdriver.chrome.driver", 
            "drivers/chromedriver.exe");
        
        // Initialize Chrome
        WebDriver driver = new ChromeDriver();
        
        // Open Google
        driver.get("https://www.google.com");
        
        // Print title
        System.out.println("Page title: " + driver.getTitle());
        
        // Close browser
        driver.quit();
    }
}

7. Run the Test

Right-click the class → Run As → TestNG Test
 

You should see:
 

  1. Chrome browser opening automatically
     
  2. Google homepage loading
     
  3. Console output showing the page title
     
  4. Browser closing automatically

Project Structure Should Look Like

FirstSeleniumProject
├── src/main/java
│   └── com.tests
│       └── FirstTest.java
├── drivers
│   └── chromedriver.exe
└── pom.xml

Troubleshooting Tips

If you get errors:

  1. Check ChromeDriver path is correct
     
  2. Make sure Chrome is updated
     
  3. Verify TestNG is in your dependencies
     
  4. Check Java version matches what you installed

Steps for Writing Selenium Code in Java

Now that your project is set up, let's learn how to write effective Selenium tests. These steps will help you create reliable automation scripts.

1. Basic Test Structure

Every Selenium test follows this pattern:
 

  1. Initialize WebDriver
     
  2. Perform actions
     
  3. Verify results
     
  4. Clean up (close browser)
     

Let’s take a look at the template:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class TestTemplate {
    public static void main(String[] args) {
        // 1. Initialize
        System.setProperty("webdriver.chrome.driver", "drivers/chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        
        // 2. Perform actions
        driver.get("https://example.com");
        
        // 3. Verification would go here
        
        // 4. Clean up
        driver.quit();
    }
}

2. Locating Web Elements

You need to find elements before interacting with them. Common methods:

// By ID

driver.findElement(By.id("username"));


// By Name

driver.findElement(By.name("q"));


// By CSS Selector (most powerful)

driver.findElement(By.cssSelector("input.login-btn"));


// By XPath (when no good selector exists)

driver.findElement(By.xpath("//button[contains(text(),'Submit')]"));

3. Common Interactions

Here's how to perform basic actions:

// Type text

WebElement search = driver.findElement(By.name("q"));
search.sendKeys("Selenium testing");


// Click

WebElement button = driver.findElement(By.id("submit"));
button.click();


// Get text

String heading = driver.findElement(By.tagName("h1")).getText();


// Check if element exists

boolean isDisplayed = driver.findElement(By.id("logo")).isDisplayed();

4. Complete Login Test Example

Let's combine everything into a practical test:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class LoginTest {
    public static void main(String[] args) {
        // Setup
        System.setProperty("webdriver.chrome.driver", "drivers/chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        
        // Test steps
        driver.get("https://practice.expandtesting.com/login");
        
        WebElement username = driver.findElement(By.id("username"));
        WebElement password = driver.findElement(By.id("password"));
        WebElement loginBtn = driver.findElement(By.cssSelector("button[type='submit']"));
        
        username.sendKeys("practice");
        password.sendKeys("SuperSecretPassword!");
        loginBtn.click();
        
        // Verification
        String successMsg = driver.findElement(By.className("alert-success")).getText();
        if(successMsg.contains("You logged into a secure area")) {
            System.out.println("TEST PASSED!");
        } else {
            System.out.println("TEST FAILED");
        }
        
        // Cleanup
        driver.quit();
    }
}

5. Best Practices


1. Use Explicit Waits (don't use Thread.sleep)

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("dynamicElement")));


2. Organize Tests using TestNG annotations:

@Test
public void validLoginTest() {
    // test code
}

@BeforeMethod
public void setup() {
    // runs before each test
}

@AfterMethod 
public void teardown() {
    // runs after each test
}


3. Page Object Model (for larger projects):

Create separate classes for each page:

public class LoginPage {
    WebDriver driver;
    
    By username = By.id("username");
    By password = By.id("password");
    
    public LoginPage(WebDriver driver) {
        this.driver = driver;
    }
    
    public void enterCredentials(String user, String pass) {
        driver.findElement(username).sendKeys(user);
        driver.findElement(password).sendKeys(pass);
    }
}

6. Running Tests

To execute:
 

  • Right-click the class → Run As → Java Application (for main methods)
     
  • Or Run As → TestNG Test (if using TestNG)


You'll see the browser automatically perform all actions and get output in Eclipse's console.

Frequently Asked Questions

What is Java application used at Selenium automation?

Java has strong typing, improved speed with large test suites, and broad corporate compatibility, which qualifies it as a tool to use in professional test automation work.

What to do with slow-loading pages?

To wait effectively on the elements to render consider using explicit waits to prevent delays in the execution of tests that will not be necessary while waiting on the elements to load.

Does Selenium support testing of mobile applications?

No, Selenium just tests Web apps. In the case of mobile testing, Appium with like principles can be used, except that the native/hybrid mobile apps are targeted.

Conclusion

In this article, we had been taught Selenium with Java basics in detail - installation to test script writing. We discussed browser automation, interaction with elements and also the best practice to develop effective test automation. To master Selenium automation, it is enough to replicate easy scripts and subsequently boost the complexity of the test cases.

Live masterclass