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 CodeIn 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
- If you're testing a simple website and want fastest setup → Python
- If your team already uses C# → Selenium with C#
- 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:
- Search for "Environment Variables" in Start Menu
- Click "Environment Variables"
- Under System variables, click "New"
- Variable name: JAVA_HOME
- Variable value: Path to your JDK (e.g., C:\Program Files\Java\jdk-17.0.1)
- 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)
- In Eclipse, create a new Maven project
- 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
- Download Selenium Java client from Selenium website
- Right-click project → Build Path → Add External JARs
- 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
- Open Eclipse
- Click File → New → Java Project
- Enter project name (e.g., "FirstSeleniumProject")
- Make sure "Use project folder as root" is selected
- 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
- Right-click src/main/java
- New → Package
- Name it (e.g., "com.tests")
5. Add ChromeDriver
- Download ChromeDriver from here
- Create a drivers folder in your project
- 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:
- Chrome browser opening automatically
- Google homepage loading
- Console output showing the page title
- 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:
- Check ChromeDriver path is correct
- Make sure Chrome is updated
- Verify TestNG is in your dependencies
- 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:
- Initialize WebDriver
- Perform actions
- Verify results
- 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.